Skip to main content

targeted_mutation/
driver.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::time::{Duration, Instant};
13
14use anyhow::{Context, Result, anyhow, bail};
15use serde::Deserialize;
16
17use crate::instrument::{self, LiteralSide, RUNTIME_MOD, Rendered, Site, SiteKind};
18use crate::plan::{self, Mutation, Obs};
19use crate::propagation::{self, Change};
20use crate::report::{self, Finding, Report};
21use crate::scope::{self, Scope};
22use crate::trace::Trace;
23use crate::{git_index, progress};
24
25pub struct Options {
26    /// Directory of the package (or workspace) to analyse.
27    pub dir: PathBuf,
28    pub package: Option<String>,
29    /// Re-run the tests against one survivor per input gap to confirm the prediction.
30    pub verify: bool,
31    /// Where to put the copy and its build. Default: `<target dir>/tmt`.
32    pub work_dir: Option<PathBuf>,
33    /// Progress lines on stderr.
34    pub progress: bool,
35    /// Analyse only code changed since this git revision (plus untracked files).
36    pub since: Option<String>,
37    /// Analyse only these lines: `FILE:FROM-TO`, with `FILE` relative to the package.
38    pub lines: Vec<String>,
39    /// Findings listed in this file are not reported.
40    pub baseline: Option<PathBuf>,
41    /// Write the findings of this run to this file, as a baseline for later runs.
42    pub write_baseline: Option<PathBuf>,
43    /// Other workspace packages whose tests are run too.
44    pub also_test: Vec<String>,
45    /// Run the tests of every workspace package that depends on the analysed one.
46    pub dependents: bool,
47    /// Trace surviving mutants to say what they change in the tests.
48    pub effects: bool,
49    /// Build and run, one by one, the mutants that cannot be switched at run time.
50    pub rebuild: bool,
51    pub source_only: bool,
52    pub test_selection: TestSelection,
53    /// Optimisation level to build the tests with, instead of the profile's own.
54    pub opt_level: Option<u8>,
55    /// Run this many surviving mutants against all tests and record the tests twice.
56    pub audit: Option<usize>,
57    /// Cargo's choice of features and of the lock file, the same for every cargo command.
58    pub cargo: CargoConfig,
59    /// How many mutants to run at the same time.
60    pub jobs: usize,
61    /// Copy every file of the workspace, including the ones git ignores.
62    pub all_files: bool,
63    pub git_index: bool,
64    pub copy_fixtures: Vec<PathBuf>,
65    /// Also run the doc tests (slow: rustdoc recompiles them for every mutant they reach).
66    pub doc: bool,
67}
68
69#[derive(Default)]
70pub struct TestSelection {
71    pub isolate: bool,
72    pub targets: Vec<String>,
73    pub include: Vec<String>,
74    pub exclude: Vec<String>,
75    pub include_ignored: bool,
76    pub wrapper: Option<PathBuf>,
77}
78
79impl TestSelection {
80    fn enabled(&self) -> bool {
81        self.isolate
82            || !self.targets.is_empty()
83            || !self.include.is_empty()
84            || !self.exclude.is_empty()
85            || self.include_ignored
86            || self.wrapper.is_some()
87    }
88}
89
90pub use crate::report::CargoConfig;
91
92impl CargoConfig {
93    /// The arguments that say the same to `cargo metadata`, `cargo test` and rustdoc.
94    pub fn flags(&self) -> Vec<String> {
95        let mut flags = vec![];
96        if !self.features.is_empty() {
97            flags.extend(["--features".to_string(), self.features.join(",")]);
98        }
99        for (on, flag) in [
100            (self.all_features, "--all-features"),
101            (self.no_default_features, "--no-default-features"),
102            (self.locked, "--locked"),
103        ] {
104            if on {
105                flags.push(flag.to_string());
106            }
107        }
108        flags
109    }
110}
111
112/// How far from an error to look for the probe that caused it (a probe can break type
113/// inference a few lines further down).
114const NEARBY_LINES: usize = 6;
115/// File that marks a directory as tmt's own working directory.
116const WORK_MARKER: &str = ".tmt-work-dir";
117/// Name under which the crate root re-declares `std` for the runtime module.
118const STD_ALIAS: &str = "__tmt_std";
119/// More rebuilds than this means the blame logic is not converging.
120const MAX_REPAIR_ROUNDS: usize = 40;
121/// Above this many tests, run the whole binary instead of passing names.
122const MAX_TEST_FILTERS: usize = 200;
123
124#[derive(Deserialize)]
125struct Metadata {
126    packages: Vec<Package>,
127    workspace_root: PathBuf,
128    target_directory: PathBuf,
129}
130
131#[derive(Deserialize)]
132struct Package {
133    name: String,
134    #[serde(default)]
135    dependencies: Vec<Dependency>,
136    features: BTreeMap<String, Vec<String>>,
137    manifest_path: PathBuf,
138    targets: Vec<Target>,
139}
140
141impl Package {
142    /// Only count features we can establish without resolving the dependency graph.
143    fn enabled_local_features(&self, workspace: &Path, cargo: &CargoConfig) -> BTreeSet<&str> {
144        if cargo.all_features {
145            return self.features.keys().map(String::as_str).collect();
146        }
147        let mut pending = Vec::new();
148        if !cargo.no_default_features {
149            pending.push("default");
150        }
151        // With resolver 1, unqualified CLI features only apply to the current package.
152        let at_workspace_root = self.manifest_path.parent() == Some(workspace);
153        for feature in cargo
154            .features
155            .iter()
156            .flat_map(|features| features.split(|c: char| c == ',' || c.is_whitespace()))
157        {
158            match feature.split_once('/') {
159                Some((package, name)) if package == self.name => pending.push(name),
160                None if at_workspace_root => pending.push(feature),
161                _ => {}
162            }
163        }
164        let mut enabled = BTreeSet::new();
165        while let Some(feature) = pending.pop() {
166            if let Some((name, activates)) = self.features.get_key_value(feature)
167                && enabled.insert(name.as_str())
168            {
169                pending.extend(activates.iter().map(String::as_str));
170            }
171        }
172        enabled
173    }
174}
175
176#[derive(Deserialize)]
177struct Dependency {
178    name: String,
179}
180
181#[derive(Deserialize)]
182struct Target {
183    name: String,
184    kind: Vec<String>,
185    src_path: PathBuf,
186    test: bool,
187    #[serde(default, rename = "required-features")]
188    required_features: Vec<String>,
189}
190
191impl Target {
192    /// The Cargo selector and its optional name. `--lib` selects every package's library.
193    fn test_build_arg(&self) -> Option<(&'static str, Option<&str>)> {
194        match self.kind.first()?.as_str() {
195            "lib" | "rlib" | "cdylib" | "dylib" | "staticlib" | "proc-macro" => {
196                Some(("--lib", None))
197            }
198            "bin" => Some(("--bin", Some(&self.name))),
199            "example" => Some(("--example", Some(&self.name))),
200            "test" => Some(("--test", Some(&self.name))),
201            "bench" => Some(("--bench", Some(&self.name))),
202            _ => None,
203        }
204    }
205}
206
207/// Select only test targets that Cargo's flags can express without broadening the selection.
208fn test_build_flags(
209    packages: &[&Package],
210    names: &[String],
211    workspace: &Path,
212    cargo: &CargoConfig,
213) -> Option<Vec<String>> {
214    if names.is_empty() {
215        return None;
216    }
217    let selected = |target: &Target| target.test && names.contains(&target.name);
218    let mut selectors = BTreeSet::new();
219    for package in packages {
220        let enabled_features = package.enabled_local_features(workspace, cargo);
221        for target in package.targets.iter().filter(|t| selected(t)) {
222            let selector = target.test_build_arg()?;
223            // Cargo skips gated targets in a default build but errors if named explicitly.
224            if target
225                .required_features
226                .iter()
227                .any(|feature| !enabled_features.contains(feature.as_str()))
228                || selector
229                    .1
230                    .is_some_and(|name| name.contains(['*', '?', '[']))
231            {
232                return None;
233            }
234            selectors.insert(selector);
235        }
236    }
237    // A selector applies to all the chosen packages and can override `test = false`.
238    if selectors.is_empty()
239        || packages.iter().flat_map(|p| &p.targets).any(|target| {
240            !selected(target)
241                && target
242                    .test_build_arg()
243                    .is_some_and(|selector| selectors.contains(&selector))
244        })
245    {
246        return None;
247    }
248    Some(
249        selectors
250            .into_iter()
251            .map(|(flag, name)| match name {
252                Some(name) => format!("{flag}={name}"),
253                None => flag.to_owned(),
254            })
255            .collect(),
256    )
257}
258
259/// One line of `cargo --message-format=json`.
260#[derive(Deserialize)]
261struct CargoMessage {
262    reason: String,
263    package_id: Option<String>,
264    target: Option<ArtifactTarget>,
265    profile: Option<Profile>,
266    executable: Option<PathBuf>,
267    message: Option<Diagnostic>,
268}
269
270#[derive(Deserialize)]
271struct ArtifactTarget {
272    name: String,
273    kind: Vec<String>,
274}
275
276#[derive(Deserialize)]
277struct Profile {
278    test: bool,
279}
280
281#[derive(Deserialize)]
282struct Diagnostic {
283    level: String,
284    rendered: Option<String>,
285    spans: Vec<DiagnosticSpan>,
286}
287
288#[derive(Deserialize)]
289struct DiagnosticSpan {
290    file_name: String,
291    byte_start: usize,
292    line_start: usize,
293    is_primary: bool,
294}
295
296#[derive(Debug, PartialEq, Clone)]
297struct ErrorSpan {
298    file: String,
299    byte_start: usize,
300    line: usize,
301}
302
303/// One compiler error. The primary spans say where it was detected, the secondary ones
304/// often point at the cause (for "possibly-uninitialized", at the guard we inserted).
305#[derive(Debug, PartialEq)]
306struct CompileError {
307    primary: Vec<ErrorSpan>,
308    secondary: Vec<ErrorSpan>,
309    rendered: String,
310}
311
312#[derive(Debug, Default, PartialEq)]
313struct BuildOutput {
314    /// `(target name, executable, package, target kind)` of the test binaries.
315    test_binaries: Vec<(String, PathBuf, String, Vec<String>)>,
316    errors: Vec<CompileError>,
317}
318
319/// The workspace packages that depend on `package`, directly or through others.
320fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
321    let mut found: Vec<String> = vec![];
322    let mut frontier = vec![package.to_string()];
323    while let Some(current) = frontier.pop() {
324        for other in packages {
325            if other.name != package
326                && !found.contains(&other.name)
327                && other.dependencies.iter().any(|d| d.name == current)
328            {
329                found.push(other.name.clone());
330                frontier.push(other.name.clone());
331            }
332        }
333    }
334    found.sort();
335    found
336}
337
338/// Package ids embed the path, and the build runs in a copy, so compare by name.
339/// Ids look like `path+file:///dir#name@1.0.0`, `path+file:///dir/name#1.0.0` or `name 1.0.0 (path+...)`.
340fn is_package(id: &str, name: &str) -> bool {
341    let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
342    fragment.split('@').next() == Some(name)
343        || path.rsplit('/').next() == Some(name)
344        || id.split(' ').next() == Some(name)
345}
346
347fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
348    let mut out = BuildOutput::default();
349    for line in stdout.lines() {
350        let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
351            continue;
352        };
353        match msg.reason.as_str() {
354            "compiler-artifact" => {
355                if let (Some(exe), Some(target), Some(profile), Some(id)) = (
356                    msg.executable,
357                    msg.target,
358                    msg.profile,
359                    msg.package_id.as_deref(),
360                ) && profile.test
361                    && let Some(package) = packages.iter().find(|name| is_package(id, name))
362                {
363                    out.test_binaries
364                        .push((target.name, exe, package.to_string(), target.kind));
365                }
366            }
367            "compiler-message" => {
368                let Some(diag) = msg.message else { continue };
369                if diag.level != "error" {
370                    continue;
371                }
372                let span = |s: &DiagnosticSpan| ErrorSpan {
373                    file: s.file_name.clone(),
374                    byte_start: s.byte_start,
375                    line: s.line_start,
376                };
377                let error = CompileError {
378                    primary: diag
379                        .spans
380                        .iter()
381                        .filter(|s| s.is_primary)
382                        .map(span)
383                        .collect(),
384                    secondary: diag
385                        .spans
386                        .iter()
387                        .filter(|s| !s.is_primary)
388                        .map(span)
389                        .collect(),
390                    rendered: diag.rendered.unwrap_or_default(),
391                };
392                // "aborting due to N previous errors" and friends carry no location, and the
393                // lib is compiled twice (plain and test), which reports everything twice.
394                if !error.primary.is_empty() && !out.errors.contains(&error) {
395                    out.errors.push(error);
396                }
397            }
398            _ => {}
399        }
400    }
401    out
402}
403
404struct SourceFile {
405    /// Path relative to the package directory, for reports.
406    display: String,
407    /// Path inside the working copy.
408    path: PathBuf,
409    original: String,
410    sites: Vec<Site>,
411    /// Sites whose mutants are built one by one.
412    rebuild_sites: Vec<Site>,
413    /// Where every site of the file is (line, column, code), also those a run of a part
414    /// leaves out: findings are numbered by these.
415    places: Vec<(usize, usize, String)>,
416    rendered: Option<Rendered>,
417}
418
419/// How a group of tests is started.
420enum Runner {
421    /// A libtest executable.
422    Exe(PathBuf),
423    Isolated {
424        exe: PathBuf,
425        test: String,
426        ignored: bool,
427        wrapper: Option<PathBuf>,
428    },
429    /// The package's doc tests, through `cargo test --doc` in the working copy. rustdoc
430    /// compiles them on every run, and they cannot be selected by name.
431    Doc {
432        copy: PathBuf,
433        target_dir: PathBuf,
434        package: String,
435        opt_level: Option<u8>,
436        flags: Vec<String>,
437    },
438}
439
440struct TestBinary {
441    name: String,
442    /// Directory the tests run in: their package's, as under `cargo test`.
443    cwd: PathBuf,
444    /// Where the marks of its runs are made: a directory of this analysis alone.
445    marks: PathBuf,
446    git_ceiling: PathBuf,
447    /// The tests the binary contains, by the name libtest selects them with.
448    tests: BTreeSet<String>,
449    runner: Runner,
450    /// How long the tests take when nothing is recorded: what a mutant is measured against.
451    baseline: Duration,
452    /// How long they took while recording.
453    traced: Duration,
454    trace: Trace,
455}
456
457#[derive(Debug, PartialEq, Clone, Copy)]
458enum Outcome {
459    Pass,
460    Fail,
461    Timeout,
462    /// The run gave up: it could not go on as the mutant it was started with.
463    Unable,
464}
465
466impl From<Outcome> for progress::Outcome {
467    fn from(outcome: Outcome) -> Self {
468        match outcome {
469            Outcome::Pass => Self::Survived,
470            Outcome::Fail => Self::Failed,
471            Outcome::Timeout => Self::TimedOut,
472            Outcome::Unable => Self::Unable,
473        }
474    }
475}
476
477fn isolate_copy_command(command: &mut Command, work: &Path) {
478    git_index::remove_git_overrides(command);
479    command.env("GIT_CEILING_DIRECTORIES", work);
480}
481
482/// Keeps two runs from rebuilding the same working copy under each other.
483struct WorkLock(PathBuf);
484
485impl WorkLock {
486    fn take(work: &Path) -> Result<WorkLock> {
487        let path = work.join(".tmt-lock");
488        match fs::OpenOptions::new()
489            .write(true)
490            .create_new(true)
491            .open(&path)
492        {
493            Ok(_) => Ok(WorkLock(path)),
494            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => bail!(
495                "another tmt run is using {}. If none is running, delete {}.",
496                work.display(),
497                path.display()
498            ),
499            Err(err) => Err(err).with_context(|| format!("creating {}", path.display())),
500        }
501    }
502}
503
504impl Drop for WorkLock {
505    fn drop(&mut self) {
506        let _ = fs::remove_file(&self.0);
507    }
508}
509
510/// Name of the log of written files, beside the working copy.
511const WRITTEN_LOG: &str = ".tmt-written";
512
513/// The working copy and what the runs did to it (formal/tla/WorkCopy.tla).
514///
515/// Most of the copy is plain copies of the user's files. The files a run instruments
516/// are rewritten, and the log names them. The next run leaves those alone when it brings
517/// the copy up to date, renders them again from the user's files, and writes only what
518/// came out different: a file that keeps its modification time is not rebuilt by cargo.
519/// What the log names and the run did not write again goes back to a plain copy.
520struct WorkCopy {
521    root: PathBuf,
522    log: PathBuf,
523    /// Paths of the copy that the current run wants to exist.
524    kept: RefCell<HashSet<PathBuf>>,
525    /// Named by the log when the run started.
526    earlier: HashSet<PathBuf>,
527    /// Those of `earlier` that the user's tree still has.
528    visited: RefCell<HashSet<PathBuf>>,
529    /// Written by this run.
530    written: RefCell<HashSet<PathBuf>>,
531    /// What the log names now.
532    logged: RefCell<HashSet<PathBuf>>,
533}
534
535impl WorkCopy {
536    fn open(work: &Path, root: &Path) -> WorkCopy {
537        let log = work.join(WRITTEN_LOG);
538        // The log is appended to and replaced: never through a link to somewhere else.
539        for file in [log.clone(), log.with_extension("new")] {
540            if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
541                let _ = fs::remove_file(&file);
542            }
543        }
544        let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
545            .unwrap_or_default()
546            .lines()
547            .map(Path::new)
548            // Nothing but a path below the copy: the entries are deleted and overwritten.
549            .filter(|relative| {
550                let mut parts = relative.components();
551                parts.clone().next().is_some()
552                    && parts.all(|part| matches!(part, std::path::Component::Normal(_)))
553            })
554            .map(|relative| root.join(relative))
555            .collect();
556        WorkCopy {
557            root: root.to_path_buf(),
558            log,
559            kept: RefCell::default(),
560            logged: RefCell::new(earlier.clone()),
561            earlier,
562            visited: RefCell::default(),
563            written: RefCell::default(),
564        }
565    }
566
567    fn is_kept(&self, path: &Path) -> bool {
568        self.kept.borrow().contains(path) || self.earlier.contains(path)
569    }
570
571    /// The text of the user's file that `path` of the copy stands for. `None` for what
572    /// only an earlier run left there.
573    fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
574        let source = if !self.earlier.contains(path) {
575            path.to_path_buf() // a plain copy
576        } else if !self.visited.borrow().contains(path) {
577            return Ok(None);
578        } else {
579            workspace.join(path.strip_prefix(&self.root).unwrap_or(path))
580        };
581        fs::read_to_string(&source)
582            .map(Some)
583            .with_context(|| format!("reading {}", source.display()))
584    }
585
586    /// Writes a file of the working copy. Refuses to write anywhere else, and never
587    /// through a symbolic link. The log names the file before it changes.
588    fn write(&self, path: &Path, content: &str) -> Result<()> {
589        if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
590            fs::remove_file(path)?;
591        }
592        let parent = path.parent().and_then(|p| p.canonicalize().ok());
593        let inside = match (parent, self.root.canonicalize()) {
594            (Some(parent), Ok(root)) => parent.starts_with(root),
595            _ => false,
596        };
597        if !inside {
598            bail!(
599                "refusing to write outside the working copy: {}",
600                path.display()
601            );
602        }
603        self.record(path)?;
604        if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
605            return Ok(()); // keep the modification time: nothing to rebuild
606        }
607        fs::write(path, content).with_context(|| format!("writing {}", path.display()))
608    }
609
610    fn record(&self, path: &Path) -> Result<()> {
611        self.written.borrow_mut().insert(path.to_path_buf());
612        if self.logged.borrow().contains(path) {
613            return Ok(());
614        }
615        let line = path
616            .strip_prefix(&self.root)
617            .ok()
618            .and_then(Path::to_str)
619            .filter(|text| !text.chars().any(char::is_control));
620        let Some(line) = line else {
621            bail!(
622                "cannot instrument {}: its name cannot be written on a line of the log",
623                path.display()
624            );
625        };
626        use std::io::Write as _;
627        let mut log = fs::OpenOptions::new()
628            .create(true)
629            .append(true)
630            .open(&self.log)
631            .with_context(|| format!("opening {}", self.log.display()))?;
632        writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
633        self.logged.borrow_mut().insert(path.to_path_buf());
634        Ok(())
635    }
636
637    /// Before the build: what earlier runs wrote and this one did not is a plain copy
638    /// again (or gone, like its source), and only then leaves the log.
639    fn settle(&self, workspace: &Path) -> Result<()> {
640        let written = self.written.borrow();
641        for path in self.earlier.difference(&written) {
642            if fs::symlink_metadata(path).is_ok() {
643                fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
644            }
645            if self.visited.borrow().contains(path) {
646                let source = workspace.join(path.strip_prefix(&self.root).unwrap_or(path));
647                copy_as_new(&source, path)?;
648            }
649        }
650        let mut lines: Vec<&str> = written
651            .iter()
652            .filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
653            .collect();
654        lines.sort_unstable();
655        let fresh = self.log.with_extension("new");
656        fs::write(
657            &fresh,
658            lines
659                .iter()
660                .map(|line| format!("{line}\n"))
661                .collect::<String>(),
662        )?;
663        fs::rename(&fresh, &self.log)?;
664        *self.logged.borrow_mut() = written.clone();
665        Ok(())
666    }
667}
668
669/// Makes `dst` a copy of the file `src`, leaving it alone if it already is one. A file
670/// that keeps its modification time is not rebuilt by cargo, so a second run only
671/// recompiles what changed.
672fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
673    state.kept.borrow_mut().insert(dst.to_path_buf());
674    if state.earlier.contains(dst) {
675        state.visited.borrow_mut().insert(dst.to_path_buf());
676        if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
677            // Written by an earlier run: this one decides what becomes of it.
678            return Ok(());
679        }
680    }
681    // Times say nothing certain: a file put back from an archive is older than the copy
682    // of what it replaces. A copy is what holds the same bytes.
683    // A link is not a copy, whatever it points to.
684    let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
685    if up_to_date {
686        return Ok(());
687    }
688    if let Ok(existing) = fs::symlink_metadata(dst) {
689        if existing.is_dir() {
690            fs::remove_dir_all(dst)?;
691        } else {
692            fs::remove_file(dst)?;
693        }
694    }
695    copy_as_new(src, dst)
696}
697
698/// Whether two files hold the same bytes. One that cannot be read is not the same.
699fn same_bytes(a: &Path, b: &Path) -> bool {
700    fs::read(a)
701        .ok()
702        .zip(fs::read(b).ok())
703        .is_some_and(|(a, b)| a == b)
704}
705
706/// Makes `dir` a directory of the working copy. Whatever else is in the way below the
707/// copy's root goes first, a link above all: a link is followed, and what is written
708/// "into the copy" would land where it points.
709fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
710    if let Ok(below) = dir.strip_prefix(&state.root) {
711        let mut path = state.root.clone();
712        for part in below.components() {
713            path.push(part);
714            match fs::symlink_metadata(&path) {
715                Ok(found) if !found.is_dir() => fs::remove_file(&path)
716                    .with_context(|| format!("removing {}", path.display()))?,
717                _ => {}
718            }
719        }
720    }
721    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
722}
723
724/// Copies a file and gives the copy the current time. Some systems copy the modification
725/// time along, and a file that changed in the working copy but looks older than the last
726/// build would not be rebuilt.
727fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
728    fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
729    // Opened for reading: the copy of a read-only file is read-only too.
730    fs::File::open(dst)
731        .and_then(|file| file.set_modified(std::time::SystemTime::now()))
732        .with_context(|| format!("touching {}", dst.display()))
733}
734
735/// Removes from the working copy whatever the current run did not put there.
736fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
737    let mut empty = true;
738    for entry in fs::read_dir(dir)? {
739        let path = entry?.path();
740        let is_dir = fs::symlink_metadata(&path)?.is_dir();
741        if is_dir {
742            if prune(&path, state)? && !state.is_kept(&path) {
743                fs::remove_dir(&path)?;
744            } else {
745                empty = false;
746            }
747        } else if state.is_kept(&path) {
748            empty = false;
749        } else {
750            fs::remove_file(&path)?;
751        }
752    }
753    Ok(empty)
754}
755
756/// Copies one file, directory or symbolic link into the working copy.
757///
758/// The copy never contains a symbolic link: instrumented sources are written into it, and
759/// a link would send those writes back to the user's files. A link to a file becomes a
760/// plain file with the same content. A link to a directory is followed only when the
761/// directory lies inside `workspace` and does not contain the link itself.
762fn copy_entry(
763    src: &Path,
764    dst: &Path,
765    workspace: &Path,
766    skip: &dyn Fn(&Path) -> bool,
767    state: &WorkCopy,
768) -> Result<()> {
769    let kind = fs::symlink_metadata(src)?.file_type();
770    if kind.is_symlink() {
771        let Ok(target) = src.canonicalize() else {
772            return Ok(()); // dangling
773        };
774        if target.is_dir() {
775            let contains_link = src
776                .parent()
777                .is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
778            if !target.starts_with(workspace) || contains_link || skip(&target) {
779                return Ok(());
780            }
781            return copy_tree(&target, dst, workspace, skip, state);
782        }
783        sync_file(&target, dst, state)?;
784    } else if kind.is_dir() {
785        // Build output and other caches (cargo marks its target directories this way).
786        if !src.join("CACHEDIR.TAG").exists() {
787            copy_tree(src, dst, workspace, skip, state)?;
788        }
789    } else {
790        sync_file(src, dst, state)?;
791    }
792    Ok(())
793}
794
795fn copy_tree(
796    from: &Path,
797    to: &Path,
798    workspace: &Path,
799    skip: &dyn Fn(&Path) -> bool,
800    state: &WorkCopy,
801) -> Result<()> {
802    real_dir(to, state)?;
803    for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
804        let src = entry?.path();
805        if skip(&src) {
806            continue;
807        }
808        let Some(name) = src.file_name() else {
809            continue;
810        };
811        copy_entry(&src, &to.join(name), workspace, skip, state)?;
812    }
813    Ok(())
814}
815
816/// An explicitly selected fixture may include ignored directories. Resolve links to
817/// their contents inside the workspace, without following them into a parent cycle.
818fn copy_fixture_entry(
819    from: &Path,
820    to: &Path,
821    workspace: &Path,
822    forbidden: &dyn Fn(&Path) -> bool,
823    state: &WorkCopy,
824    visiting: &mut BTreeSet<PathBuf>,
825) -> Result<()> {
826    let resolved = from
827        .canonicalize()
828        .with_context(|| format!("resolving fixture {}", from.display()))?;
829    let allowed = |path: &Path| {
830        path.starts_with(workspace)
831            && path != workspace
832            && !path
833                .ancestors()
834                .take_while(|part| *part != workspace)
835                .any(forbidden)
836    };
837    if !allowed(from) || !allowed(&resolved) {
838        bail!(
839            "fixture {} resolves to an excluded path: {}",
840            from.display(),
841            resolved.display()
842        );
843    }
844    let kind = fs::metadata(&resolved)?.file_type();
845    real_dir(to.parent().expect("fixture has a parent"), state)?;
846    if kind.is_file() {
847        return sync_file(&resolved, to, state);
848    }
849    if !kind.is_dir() || !visiting.insert(resolved.clone()) {
850        bail!(
851            "fixture {} is a cycle or is not a regular file or directory",
852            from.display()
853        );
854    }
855    real_dir(to, state)?;
856    state.kept.borrow_mut().insert(to.to_path_buf());
857    for entry in fs::read_dir(&resolved)? {
858        let entry = entry?;
859        let path = entry.path();
860        if !forbidden(&path) {
861            copy_fixture_entry(
862                &path,
863                &to.join(entry.file_name()),
864                workspace,
865                forbidden,
866                state,
867                visiting,
868            )?;
869        }
870    }
871    visiting.remove(&resolved);
872    Ok(())
873}
874
875fn rust_files(dir: &Path, skip: &dyn Fn(&Path) -> bool, out: &mut Vec<PathBuf>) -> Result<()> {
876    let mut entries: Vec<PathBuf> = fs::read_dir(dir)?
877        .map(|e| e.map(|e| e.path()))
878        .collect::<std::io::Result<_>>()?;
879    entries.sort();
880    for path in entries {
881        let Ok(kind) = fs::symlink_metadata(&path).map(|m| m.file_type()) else {
882            continue;
883        };
884        if skip(&path) || kind.is_symlink() {
885            continue;
886        }
887        if kind.is_dir() {
888            rust_files(&path, skip, out)?;
889        } else if path.extension().is_some_and(|e| e == "rs") {
890            out.push(path);
891        }
892    }
893    Ok(())
894}
895
896/// The files under `dir` that git tracks or would track (not ignored), relative to `dir`.
897/// `None` when `dir` is not in a git work tree, or is itself ignored: then git has nothing
898/// to say about which files matter.
899fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
900    let git = |args: &[&str]| {
901        Command::new("git")
902            .arg("-C")
903            .arg(dir)
904            .args(args)
905            .stderr(Stdio::null())
906            .output()
907    };
908    // No git, not a work tree, or a directory git ignores: nothing to go by.
909    let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
910        return Ok(None);
911    };
912    if !inside.status.success() {
913        return Ok(None);
914    }
915    // Exit status 0 means "ignored".
916    if git(&["check-ignore", "-q", "."])?.status.success() {
917        return Ok(None);
918    }
919    // From here on a failure must not turn into "copy everything": that would copy the
920    // very files the ignore rules keep out.
921    let listing = git(&[
922        "ls-files",
923        "--cached",
924        "--others",
925        "--exclude-standard",
926        "-z",
927    ])?;
928    if !listing.status.success() {
929        bail!(
930            "git could not list the files of {}; pass --all-files to copy everything",
931            dir.display()
932        );
933    }
934    Ok(Some(
935        listing
936            .stdout
937            .split(|b| *b == 0)
938            .filter(|name| !name.is_empty())
939            .filter_map(|name| std::str::from_utf8(name).ok())
940            .map(PathBuf::from)
941            .collect(),
942    ))
943}
944
945/// Copies the files of `from` that git does not ignore. A submodule is listed by its
946/// parent as one directory and has ignore rules of its own, so it is copied the same way.
947fn copy_git_visible(
948    from: &Path,
949    to: &Path,
950    files: Vec<PathBuf>,
951    workspace: &Path,
952    skip: &dyn Fn(&Path) -> bool,
953    state: &WorkCopy,
954) -> Result<usize> {
955    let mut copied = 0;
956    for relative in files {
957        let (src, dst) = (from.join(&relative), to.join(&relative));
958        if skip(&src)
959            || src
960                .ancestors()
961                .any(|a| a != from && a.starts_with(from) && skip(a))
962        {
963            continue;
964        }
965        let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
966            continue; // deleted in the working tree
967        };
968        if let Some(parent) = dst.parent() {
969            real_dir(parent, state)?;
970        }
971        if kind.is_dir() {
972            match git_visible_files(&src)? {
973                Some(inner) => {
974                    copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
975                }
976                None => copy_tree(&src, &dst, workspace, skip, state)?,
977            }
978        } else {
979            copy_entry(&src, &dst, workspace, skip, state)?;
980            copied += 1;
981        }
982    }
983    Ok(copied)
984}
985
986/// Where the out-of-line module `module` declared in `file` lives.
987fn module_paths(file: &Path, module: &instrument::TestModule) -> Vec<PathBuf> {
988    let dir = file.parent().unwrap_or(Path::new("."));
989    if let Some(path) = &module.path {
990        return vec![dir.join(path)];
991    }
992    let name = &module.name;
993    let stem = file.file_stem().and_then(|s| s.to_str()).unwrap_or("");
994    let base = if matches!(stem, "lib" | "main" | "mod") {
995        dir.to_path_buf()
996    } else {
997        dir.join(stem)
998    };
999    vec![base.join(format!("{name}.rs")), base.join(name)]
1000}
1001
1002/// Resolves `.` and `..` without touching the file system.
1003fn normalize(path: &Path) -> PathBuf {
1004    let mut out = PathBuf::new();
1005    for component in path.components() {
1006        match component {
1007            std::path::Component::CurDir => {}
1008            std::path::Component::ParentDir => {
1009                out.pop();
1010            }
1011            other => out.push(other),
1012        }
1013    }
1014    out
1015}
1016
1017/// Rewrites `path = "../outside"` dependencies of a manifest to absolute paths when they
1018/// point outside `workspace`. Returns `None` when nothing has to change.
1019fn absolutize_path_dependencies(
1020    manifest: &str,
1021    manifest_dir: &Path,
1022    workspace: &Path,
1023    copy: &Path,
1024) -> Result<Option<String>> {
1025    use toml_edit::{DocumentMut, Item, TableLike, value};
1026
1027    fn fix(deps: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1028        let (manifest_dir, workspace, copy) = dirs;
1029        for (_, dep) in deps.iter_mut() {
1030            let Some(dep) = dep.as_table_like_mut() else {
1031                continue;
1032            };
1033            let Some(path) = dep.get("path").and_then(Item::as_str) else {
1034                continue;
1035            };
1036            let absolute = Path::new(path).is_absolute();
1037            let target = normalize(&manifest_dir.join(path));
1038            let rewritten = match target.strip_prefix(workspace) {
1039                // Outside the workspace: not copied, so point at the original.
1040                Err(_) => target,
1041                // Inside, but spelled as an absolute path: that is the original too, and
1042                // the build has to use the copy.
1043                Ok(inside) if absolute => copy.join(inside),
1044                Ok(_) => continue,
1045            };
1046            dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
1047            *changed = true;
1048        }
1049    }
1050    const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
1051    fn fix_sections(table: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1052        for section in SECTIONS {
1053            if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
1054                fix(deps, dirs, changed);
1055            }
1056        }
1057    }
1058
1059    let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
1060    let mut changed = false;
1061    let dirs = (manifest_dir, workspace, copy);
1062    fix_sections(doc.as_table_mut(), dirs, &mut changed);
1063    if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
1064        fix_sections(ws, dirs, &mut changed);
1065    }
1066    for per_key in ["target", "patch"] {
1067        let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
1068            continue;
1069        };
1070        for (_, inner) in outer.iter_mut() {
1071            let Some(inner) = inner.as_table_like_mut() else {
1072                continue;
1073            };
1074            if per_key == "target" {
1075                fix_sections(inner, dirs, &mut changed);
1076            } else {
1077                fix(inner, dirs, &mut changed);
1078            }
1079        }
1080    }
1081    Ok(changed.then(|| doc.to_string()))
1082}
1083
1084/// Tests to pass to the binary, or `None` for "run everything".
1085///
1086/// A name that is not one of the binary's tests comes from a thread the test named
1087/// itself; passing it to libtest would select nothing and "pass". Such observations
1088/// belong to some unknown test, like those of unnamed threads.
1089fn test_filter(tests: &BTreeSet<String>, known: &BTreeSet<String>) -> Option<Vec<String>> {
1090    if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
1091        None
1092    } else {
1093        Some(tests.iter().cloned().collect())
1094    }
1095}
1096
1097/// Names of the tests in libtest's `--list --format terse` output.
1098fn parse_test_list(stdout: &str) -> BTreeSet<String> {
1099    stdout
1100        .lines()
1101        .filter_map(|line| line.strip_suffix(": test"))
1102        .map(str::to_string)
1103        .collect()
1104}
1105
1106/// What makes cargo build the tests (and what they depend on) at an optimisation level.
1107fn list_tests(
1108    exe: &Path,
1109    cwd: &Path,
1110    work: &Path,
1111    ignored: bool,
1112    strict: bool,
1113) -> Result<BTreeSet<String>> {
1114    let mut command = Command::new(exe);
1115    isolate_copy_command(&mut command, work);
1116    command.args(["--list", "--format", "terse"]);
1117    if ignored {
1118        command.arg("--ignored");
1119    }
1120    let listing = command
1121        .current_dir(cwd)
1122        .stdin(Stdio::null())
1123        .output()
1124        .with_context(|| format!("listing tests of {}", exe.display()))?;
1125    if !listing.status.success() {
1126        if !strict {
1127            return Ok(BTreeSet::new());
1128        }
1129        bail!(
1130            "listing tests of {} failed: {}",
1131            exe.display(),
1132            String::from_utf8_lossy(&listing.stderr)
1133        );
1134    }
1135    Ok(parse_test_list(&String::from_utf8_lossy(&listing.stdout)))
1136}
1137
1138/// Overflow checks and debug assertions stay as the profile has them.
1139fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
1140    opt_level.map_or(vec![], |level| {
1141        vec![
1142            ("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
1143            ("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
1144        ]
1145    })
1146}
1147
1148/// A trace run longer than this is followed by a run without recording, for the timing.
1149const SLOW_TRACE: Duration = Duration::from_secs(2);
1150
1151fn mutant_timeout(baseline: Duration) -> Duration {
1152    Duration::from_secs(5) + baseline * 5
1153}
1154
1155/// The test threads of one test binary when `sharing` of them run at the same time: its
1156/// share of the cores. Never fewer than two, because the harness runs the tests of a
1157/// single thread on the main thread, where they have no name to be told apart by.
1158fn test_threads(cores: usize, sharing: usize) -> usize {
1159    (cores / sharing.max(1)).max(2)
1160}
1161
1162enum RunOutput<'a> {
1163    Quiet,
1164    FirstFailure,
1165    Capture(&'a fs::File),
1166}
1167
1168fn run_binary(
1169    bin: &TestBinary,
1170    tests: Option<&[String]>,
1171    env: &[(&str, &str)],
1172    timeout: Duration,
1173    output: RunOutput<'_>,
1174    sharing: usize,
1175) -> Result<Outcome> {
1176    let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
1177    let threads = test_threads(cores, sharing);
1178    static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1179    let unable_mark = reserve_mark(&bin.marks, &RUNS)?;
1180
1181    let mut cmd = match &bin.runner {
1182        Runner::Exe(exe) => {
1183            let mut cmd = Command::new(exe);
1184            // With one test thread libtest runs tests on the main thread, and the runtime
1185            // could no longer tell which test it is in.
1186            cmd.arg(format!("--test-threads={threads}"));
1187            if let Some(tests) = tests {
1188                cmd.arg("--exact").args(tests);
1189            }
1190            cmd.current_dir(&bin.cwd)
1191                .env("CARGO_MANIFEST_DIR", &bin.cwd);
1192            cmd
1193        }
1194        Runner::Isolated {
1195            exe,
1196            test,
1197            ignored,
1198            wrapper,
1199        } => {
1200            let mut cmd = if let Some(wrapper) = wrapper {
1201                let mut cmd = Command::new(wrapper);
1202                cmd.arg(exe);
1203                cmd
1204            } else {
1205                Command::new(exe)
1206            };
1207            cmd.args(["--exact", "--test-threads=1", test]);
1208            if *ignored {
1209                cmd.arg("--ignored");
1210            }
1211            cmd.current_dir(&bin.cwd)
1212                .env("CARGO_MANIFEST_DIR", &bin.cwd);
1213            cmd
1214        }
1215        Runner::Doc {
1216            copy,
1217            target_dir,
1218            package,
1219            opt_level,
1220            flags,
1221        } => {
1222            let mut cmd = Command::new("cargo");
1223            cmd.args(["test", "--doc", "-p", package])
1224                .args(flags)
1225                .current_dir(copy)
1226                .env("CARGO_TARGET_DIR", target_dir)
1227                .env("CARGO_BUILD_BUILD_DIR", target_dir)
1228                .envs(profile_env(*opt_level));
1229            cmd
1230        }
1231    };
1232    isolate_copy_command(&mut cmd, &bin.git_ceiling);
1233    cmd.env_remove("TMT_TRACE")
1234        .env_remove("TMT_MUTANT")
1235        .env_remove("TMT_TEST")
1236        .env("TMT_UNABLE", &unable_mark)
1237        .envs(env.iter().copied())
1238        .stdin(Stdio::null());
1239    if let Runner::Isolated { test, .. } = &bin.runner {
1240        cmd.env("TMT_TEST", test);
1241    }
1242    let mut output_to_watch = None;
1243    match output {
1244        RunOutput::Capture(file) => {
1245            cmd.stdout(file.try_clone()?).stderr(file.try_clone()?);
1246        }
1247        RunOutput::FirstFailure if !matches!(bin.runner, Runner::Isolated { .. }) => {
1248            // A regular file has a readable end even if a descendant keeps stdout.
1249            // Reuse the per-run marker, whose contents are never interpreted by probes.
1250            let writer = fs::OpenOptions::new().append(true).open(&unable_mark)?;
1251            output_to_watch = Some(FailureOutput::new(fs::File::open(&unable_mark)?));
1252            cmd.stdout(writer).stderr(Stdio::null());
1253        }
1254        RunOutput::Quiet | RunOutput::FirstFailure => {
1255            cmd.stdout(Stdio::null()).stderr(Stdio::null());
1256        }
1257    }
1258    // Its own process group, so that a timeout can stop whatever the tests started too.
1259    #[cfg(unix)]
1260    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1261    let mut child = cmd
1262        .spawn()
1263        .with_context(|| format!("starting the tests of `{}`", bin.name))?;
1264    let group = child.id();
1265    let kill = |child: &mut std::process::Child| {
1266        kill_test_group(group);
1267        let _ = child.kill();
1268        let _ = child.wait();
1269    };
1270    let started = Instant::now();
1271    let result: Result<Outcome> = (|| loop {
1272        if let Some(status) = child.try_wait()? {
1273            if matches!(bin.runner, Runner::Isolated { .. }) || output_to_watch.is_some() {
1274                kill_test_group(group);
1275            }
1276            return Ok(if status.success() {
1277                Outcome::Pass
1278            } else {
1279                Outcome::Fail
1280            });
1281        }
1282        if output_to_watch
1283            .as_mut()
1284            .map(FailureOutput::failed)
1285            .transpose()?
1286            .unwrap_or(false)
1287        {
1288            kill(&mut child);
1289            return Ok(Outcome::Fail);
1290        }
1291        if started.elapsed() > timeout {
1292            kill(&mut child);
1293            return Ok(Outcome::Timeout);
1294        }
1295        std::thread::sleep(Duration::from_millis(5));
1296    })();
1297    drop(output_to_watch);
1298    if result.is_err() {
1299        kill(&mut child);
1300        let _ = release_mark(&unable_mark);
1301    }
1302    let outcome = result?;
1303
1304    // Whatever the tests made of it, a run that left the mark was not the mutant's. The
1305    // mark alone says so: a status is the tests' to choose, and one of them may well end
1306    // with the runtime's when it finds a mutant out.
1307    if release_mark(&unable_mark)? {
1308        return Ok(Outcome::Unable);
1309    }
1310    Ok(outcome)
1311}
1312
1313struct FailureOutput {
1314    file: fs::File,
1315    line: Vec<u8>,
1316    discarded: bool,
1317}
1318
1319impl FailureOutput {
1320    fn new(file: fs::File) -> Self {
1321        Self {
1322            file,
1323            line: Vec::new(),
1324            discarded: false,
1325        }
1326    }
1327
1328    fn failed(&mut self) -> std::io::Result<bool> {
1329        use std::io::Read as _;
1330        const MAX_LINE: usize = 8 * 1024;
1331        let mut chunk = [0; MAX_LINE];
1332        let read = self.file.read(&mut chunk)?;
1333        for part in chunk[..read].split_inclusive(|byte| *byte == b'\n') {
1334            self.discarded |= self.line.len() + part.len() > MAX_LINE;
1335            if !self.discarded {
1336                self.line.extend_from_slice(part);
1337            }
1338            if part.ends_with(b"\n") {
1339                if !self.discarded
1340                    && is_failure_line(String::from_utf8_lossy(&self.line).trim_end())
1341                {
1342                    return Ok(true);
1343                }
1344                self.discarded = false;
1345                self.line.clear();
1346            }
1347        }
1348        Ok(false)
1349    }
1350}
1351
1352fn kill_test_group(id: u32) {
1353    #[cfg(any(target_os = "linux", target_os = "macos"))]
1354    {
1355        unsafe extern "C" {
1356            fn killpg(group: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
1357        }
1358        const SIGKILL: std::ffi::c_int = 9;
1359        if let Ok(group) = std::ffi::c_int::try_from(id) {
1360            // SAFETY: the argument is the child PID used to create its own test group.
1361            // SIGKILL is 9 on Linux and macOS.
1362            unsafe { killpg(group, SIGKILL) };
1363        }
1364    }
1365    #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
1366    let _ = Command::new("kill")
1367        .args(["-KILL", "--", &format!("-{id}")])
1368        .stdout(Stdio::null())
1369        .stderr(Stdio::null())
1370        .status();
1371    #[cfg(not(unix))]
1372    let _ = id;
1373}
1374
1375/// Keeps diagnostics on disk so a descendant holding stdout open cannot hold up the driver.
1376fn run_baseline(
1377    bin: &TestBinary,
1378    env: &[(&str, &str)],
1379    timeout: Duration,
1380    path: &Path,
1381    timing_only: bool,
1382) -> Result<bool> {
1383    use std::io::{Read, Seek, SeekFrom};
1384
1385    let mut suffix = 0;
1386    let (path, mut log) = loop {
1387        let candidate = if suffix == 0 {
1388            path.to_path_buf()
1389        } else {
1390            path.with_extension(format!("{suffix}.log"))
1391        };
1392        match fs::OpenOptions::new()
1393            .create_new(true)
1394            .read(true)
1395            .write(true)
1396            .open(&candidate)
1397        {
1398            Ok(log) => break (candidate, log),
1399            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
1400            Err(err) => {
1401                return Err(err)
1402                    .with_context(|| format!("creating baseline log {}", candidate.display()));
1403            }
1404        }
1405    };
1406    let result =
1407        run_binary(bin, None, env, timeout, RunOutput::Capture(&log), 1).with_context(|| {
1408            format!(
1409                "running baseline for `{}`; output: {}",
1410                bin.name,
1411                path.display()
1412            )
1413        })?;
1414    if result == Outcome::Pass || (timing_only && result == Outcome::Timeout) {
1415        drop(log);
1416        fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
1417        return Ok(result == Outcome::Pass);
1418    }
1419    let reason = match result {
1420        Outcome::Pass => unreachable!("pass handled above"),
1421        Outcome::Fail => "do not pass on the unmutated code",
1422        Outcome::Timeout => "timed out on the unmutated code",
1423        Outcome::Unable => "could not be evaluated on the unmutated code",
1424    };
1425    const LIMIT: u64 = 16 * 1024;
1426    log.seek(SeekFrom::Start(log.metadata()?.len().saturating_sub(LIMIT)))?;
1427    let mut tail = Vec::new();
1428    log.take(LIMIT).read_to_end(&mut tail)?;
1429    bail!(
1430        "the tests in `{}` {reason}; full output: {}\n{}",
1431        bin.name,
1432        path.display(),
1433        String::from_utf8_lossy(&tail).trim_end()
1434    );
1435}
1436
1437/// The directory of the marks in a working directory: made if it is not there, used if
1438/// it is one. Anything else of that name (a file, a link) is somebody's, in a directory
1439/// that was given to work in before it was this tool's: it is left alone and said.
1440fn marks_dir(work: &Path) -> Result<PathBuf> {
1441    work_directory(work, "marks")
1442}
1443
1444fn work_directory(work: &Path, name: &str) -> Result<PathBuf> {
1445    let path = work.join(name);
1446    match fs::symlink_metadata(&path) {
1447        Ok(found) if found.is_dir() => {}
1448        Ok(_) => bail!(
1449            "{} is in the way: the working directory needs a directory of that name, and \
1450             this is not one. Move it, or choose another --work-dir",
1451            path.display()
1452        ),
1453        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1454            fs::create_dir(&path).with_context(|| format!("creating {}", path.display()))?
1455        }
1456        Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
1457    }
1458    Ok(path)
1459}
1460
1461/// Makes the file by which a run says that it gave up: there for the run, and gone when
1462/// the run could not go on as its mutant. The runtime only has to take it away, which
1463/// it can do on a full disk too. The exit status would say the same, but only that of
1464/// the tests themselves: a program a test started gives its status to the test, which
1465/// fails for it.
1466///
1467/// The file is new: one of the same name that is there already is left as it is, and
1468/// another name is tried.
1469fn reserve_mark(dir: &Path, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
1470    // The tests run in a directory of their own, and so does what they start: a place
1471    // given from here (`TMPDIR=.`) has to be the same place there.
1472    let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
1473    loop {
1474        let mark = dir.join(format!(
1475            "tmt-unable-{}-{}",
1476            std::process::id(),
1477            runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
1478        ));
1479        match fs::OpenOptions::new()
1480            .write(true)
1481            .create_new(true)
1482            .open(&mark)
1483        {
1484            Ok(_) => return Ok(mark),
1485            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
1486            // If it cannot be made, nothing could be told from the run.
1487            Err(err) => {
1488                return Err(err).with_context(|| format!("creating {}", mark.display()));
1489            }
1490        }
1491    }
1492}
1493
1494/// Takes the mark away after the run and says whether the run had given up (the mark
1495/// was gone). Anything else that keeps it from being taken away leaves the question
1496/// open, and is an error rather than an answer.
1497fn release_mark(mark: &Path) -> Result<bool> {
1498    match fs::remove_file(mark) {
1499        Ok(()) => Ok(false),
1500        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
1501        Err(err) => Err(err).with_context(|| {
1502            format!(
1503                "removing {}: cannot tell whether the tests ran the mutant to the end",
1504                mark.display()
1505            )
1506        }),
1507    }
1508}
1509
1510/// A line of libtest output that reports a failed test.
1511fn is_failure_line(line: &str) -> bool {
1512    line.starts_with("test ") && line.ends_with(" ... FAILED")
1513}
1514
1515/// The lines to analyse, from `--since` and `--lines`; `None` for everything. File names
1516/// are relative to the workspace root.
1517fn requested_scope(
1518    options: &Options,
1519    workspace: &Path,
1520    package_dir: &Path,
1521    copy: &Path,
1522) -> Result<Option<Scope>> {
1523    if options.since.is_none() && options.lines.is_empty() {
1524        return Ok(None);
1525    }
1526    // `--lines` names files the way the report does: relative to the package.
1527    let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
1528    let lines: Vec<String> = options
1529        .lines
1530        .iter()
1531        .map(|spec| prefix.join(spec).to_string_lossy().into_owned())
1532        .collect();
1533    let mut scope = Scope::parse_lines(&lines)?;
1534    if let Some(revision) = &options.since {
1535        let git = |args: &[&str]| -> Result<String> {
1536            let output = Command::new("git")
1537                .arg("-C")
1538                .arg(workspace)
1539                .args(args)
1540                .output()
1541                .context("running git")?;
1542            if !output.status.success() {
1543                bail!(
1544                    "git {} failed: {}",
1545                    args.join(" "),
1546                    String::from_utf8_lossy(&output.stderr).trim()
1547                );
1548            }
1549            Ok(String::from_utf8_lossy(&output.stdout).into_owned())
1550        };
1551        // `--relative` gives paths from the workspace root even inside a larger repository.
1552        scope.merge(Scope::from_diff(&git(&[
1553            "diff",
1554            "-U0",
1555            "--no-color",
1556            "--no-ext-diff",
1557            "--relative",
1558            "--src-prefix=a/",
1559            "--dst-prefix=b/",
1560            revision,
1561            "--",
1562        ])?));
1563        for file in git(&["ls-files", "--others", "--exclude-standard"])?.lines() {
1564            scope.add_whole_file(file);
1565        }
1566    }
1567    Ok(Some(scope))
1568}
1569
1570/// The sites to disable for one compile error, from the most to the least specific guess:
1571/// the innermost site at a primary span, at a secondary span, any site on the line of a
1572/// primary span, and finally every site of the file.
1573fn blame_error(
1574    error: &CompileError,
1575    files: &[SourceFile],
1576    copy: &Path,
1577    disabled: &HashSet<u32>,
1578) -> Vec<u32> {
1579    let enabled = |id: u32| !disabled.contains(&id);
1580    let file_of = |span: &ErrorSpan| {
1581        let path = copy.join(&span.file);
1582        files.iter().find(|f| f.path == path)
1583    };
1584    let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
1585        let mut ids = vec![];
1586        for span in spans {
1587            if let Some(file) = file_of(span) {
1588                let rendered = file.rendered.as_ref().expect("rendered before building");
1589                // Inside the text of a probe, that probe is the one that does not fit.
1590                match rendered
1591                    .inserted_by(span.byte_start)
1592                    .filter(|id| enabled(*id))
1593                {
1594                    Some(id) => ids.push(id),
1595                    None => ids.extend(instrument::blame(
1596                        &file.sites,
1597                        &enabled,
1598                        rendered.to_original(span.byte_start),
1599                    )),
1600                }
1601            }
1602        }
1603        ids
1604    };
1605    let widen = |lines: usize| -> Vec<u32> {
1606        let mut ids = vec![];
1607        for span in &error.primary {
1608            if let Some(file) = file_of(span) {
1609                ids.extend(
1610                    file.sites
1611                        .iter()
1612                        .filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
1613                        .map(|s| s.id),
1614                );
1615            }
1616        }
1617        ids
1618    };
1619    [
1620        innermost(&error.primary),
1621        innermost(&error.secondary),
1622        widen(0),
1623        widen(NEARBY_LINES),
1624        widen(usize::MAX),
1625    ]
1626    .into_iter()
1627    .find(|ids| !ids.is_empty())
1628    .unwrap_or_default()
1629}
1630
1631/// Range of `D = lhs - rhs` that the operand types allow, when one side is a literal.
1632fn domain_of(
1633    literal: LiteralSide,
1634    bounds: Option<&crate::trace::TypeBounds>,
1635) -> Option<(i128, i128)> {
1636    let bounds = bounds?;
1637    match literal {
1638        LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
1639        LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
1640        LiteralSide::None => None,
1641    }
1642}
1643
1644struct Session {
1645    progress: bool,
1646    package_dir: PathBuf,
1647    binaries: Vec<TestBinary>,
1648}
1649
1650/// One mutant and the tests it has to face, per test binary.
1651struct Job {
1652    site: u32,
1653    mutation: Mutation,
1654    /// `(index of the binary, tests to run or None for all of them)`.
1655    tests: Vec<(usize, Option<Vec<String>>)>,
1656}
1657
1658#[derive(Debug, Clone, PartialEq)]
1659struct JobResult {
1660    /// The tests the mutant passed, when it passed all of them.
1661    survived: Option<Vec<String>>,
1662    timed_out: bool,
1663    /// The mutant could not be run as what it is: neither found out nor passed.
1664    unable: bool,
1665}
1666
1667impl JobResult {
1668    fn progress_outcome(&self) -> progress::Outcome {
1669        if self.unable {
1670            progress::Outcome::Unable
1671        } else if self.timed_out {
1672            progress::Outcome::TimedOut
1673        } else if self.survived.is_some() {
1674            progress::Outcome::Survived
1675        } else {
1676            progress::Outcome::Failed
1677        }
1678    }
1679}
1680
1681/// The tests of one binary whose observations satisfy `pick`.
1682fn tests_where<T>(
1683    per_test: Option<&BTreeMap<String, T>>,
1684    pick: impl Fn(&T) -> bool,
1685) -> BTreeSet<String> {
1686    per_test
1687        .into_iter()
1688        .flatten()
1689        .filter(|(_, obs)| pick(obs))
1690        .map(|(test, _)| test.clone())
1691        .collect()
1692}
1693
1694type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
1695type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
1696
1697/// A predicted survivor.
1698struct PlannedGap {
1699    finding: Finding,
1700    /// Mutations to confirm the prediction with.
1701    survivors: Vec<Mutation>,
1702    /// The gap says nothing more than "the expression in this byte range had one value in
1703    /// every test". If that expression is a site of its own that already says so, the
1704    /// gap is not reported a second time.
1705    constant_expr: Option<(usize, usize)>,
1706}
1707
1708/// The byte range of an operand without the parentheses and spaces around it.
1709fn core_range(start: usize, text: &str) -> (usize, usize) {
1710    let (mut from, mut to) = (0, text.len());
1711    loop {
1712        let inner = &text[from..to];
1713        let trimmed = inner.trim();
1714        from += inner.len() - inner.trim_start().len();
1715        to = from + trimmed.len();
1716        let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
1717            // The first parenthesis must be the one the last closes: `(a) && (b)` is not wrapped.
1718            let mut depth = 0usize;
1719            trimmed.char_indices().all(|(i, c)| {
1720                match c {
1721                    '(' => depth += 1,
1722                    ')' => depth -= 1,
1723                    _ => {}
1724                }
1725                depth > 0 || i == trimmed.len() - 1
1726            })
1727        };
1728        if !wrapped {
1729            return (start + from, start + to);
1730        }
1731        from += 1;
1732        to -= 1;
1733    }
1734}
1735
1736/// What the planner decided for one site.
1737struct SitePlan<'a> {
1738    /// Predicted survivors: the finding to report and the mutations to confirm it with.
1739    gaps: Vec<PlannedGap>,
1740    /// The comparison cannot have another outcome within its operand types. A function
1741    /// or condition built on it is constant for a reason no test can change.
1742    cannot_differ: bool,
1743    /// The expression had a single value in every test.
1744    constant: bool,
1745    /// Mutations some test observes differently.
1746    run: Vec<Mutation>,
1747    /// Tests of a binary whose execution the mutation can change.
1748    infected: InfectedTests<'a>,
1749    /// Tests of a binary that execute the site at all.
1750    reaching: ReachingTests<'a>,
1751}
1752
1753enum Planned<'a> {
1754    Unreached,
1755    /// Reached, and its mutant cannot be run as a probe here: said, not passed over.
1756    NotEvaluated,
1757    /// Reached, but nothing to mutate (operands that are not numbers).
1758    Nothing,
1759    Plan(SitePlan<'a>),
1760}
1761
1762/// A predicted survivor with the jobs that confirm it and the expression it calls constant.
1763type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
1764
1765/// A site with its jobs: indices into the job list.
1766struct SiteWork<'a> {
1767    file: &'a str,
1768    site: &'a Site,
1769    gaps: Vec<ConfirmedGap>,
1770    constant: bool,
1771    cannot_differ: bool,
1772    runs: Vec<(Mutation, usize)>,
1773}
1774
1775impl Session {
1776    fn note(&self, text: &str) {
1777        if self.progress {
1778            eprintln!("tmt: {text}");
1779        }
1780    }
1781
1782    fn merged<T: Default + Copy>(
1783        &self,
1784        select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
1785        merge: impl Fn(&mut T, &T),
1786    ) -> T {
1787        let mut all = T::default();
1788        for obs in self
1789            .binaries
1790            .iter()
1791            .filter_map(|b| select(&b.trace))
1792            .flat_map(|t| t.values())
1793        {
1794            merge(&mut all, obs);
1795        }
1796        all
1797    }
1798
1799    fn plan<'a>(&'a self, file: &str, site: &'a Site, verify: bool) -> Planned<'a> {
1800        let id = site.id;
1801        let reach_plan = |mutation: Mutation| SitePlan {
1802            gaps: vec![],
1803            constant: false,
1804            cannot_differ: false,
1805            run: vec![mutation],
1806            infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
1807            reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
1808        };
1809        let reached = self
1810            .binaries
1811            .iter()
1812            .any(|b| b.trace.reach.contains_key(&id));
1813        let opaque = self
1814            .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
1815            .opaque;
1816        Planned::Plan(match &site.kind {
1817            SiteKind::Stmt
1818            | SiteKind::Neg { .. }
1819            | SiteKind::Field { .. }
1820            | SiteKind::Body { .. }
1821                if reached =>
1822            {
1823                reach_plan(Mutation::Delete)
1824            }
1825            SiteKind::Stmt
1826            | SiteKind::Neg { .. }
1827            | SiteKind::Field { .. }
1828            | SiteKind::Body { .. } => return Planned::Unreached,
1829            SiteKind::Guard { can_be_false } => {
1830                let can_be_false = *can_be_false;
1831                let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
1832                let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
1833                let guard_plan = plan::plan_return(&merged);
1834                if guard_plan.unreached {
1835                    return Planned::Unreached;
1836                }
1837                let gaps = guard_plan
1838                    .always
1839                    .filter(|always| allowed(&Mutation::Const(*always)))
1840                    .map(|always| PlannedGap {
1841                        finding: report::guard_gap_finding(file, site, always, verify),
1842                        survivors: vec![Mutation::Const(always)],
1843                        // The guard is the condition it consists of.
1844                        constant_expr: Some((site.start, site.end)),
1845                    })
1846                    .into_iter()
1847                    .collect();
1848                SitePlan {
1849                    constant: false,
1850                    cannot_differ: false,
1851                    gaps,
1852                    run: guard_plan.run.into_iter().filter(allowed).collect(),
1853                    infected: Box::new(move |bin, m| {
1854                        tests_where(bin.trace.returns.get(&id), |obs| match m {
1855                            Mutation::Const(value) => obs.infected_by_const(value),
1856                            _ => obs.reached(),
1857                        })
1858                    }),
1859                    reaching: Box::new(move |bin| {
1860                        tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
1861                    }),
1862                }
1863            }
1864            SiteKind::Arm { .. } if reached => reach_plan(Mutation::Delete),
1865            SiteKind::Arm { .. } => return Planned::Unreached,
1866            SiteKind::Not { .. } if reached => reach_plan(Mutation::DropNot),
1867            // `a..=b` with `b` the largest value of its type is no range the probe could
1868            // return in place of `a..b`: the mutant would run as the original and pass.
1869            SiteKind::Range { .. }
1870                if reached
1871                    && self
1872                        .binaries
1873                        .iter()
1874                        .any(|b| b.trace.ranges_at_top.contains(&id)) =>
1875            {
1876                return Planned::NotEvaluated;
1877            }
1878            SiteKind::Range { .. } if reached => reach_plan(Mutation::RangeEnd),
1879            // `!` on an integer or a user type is not negation of a condition, and a range
1880            // of something other than integers has no "one more".
1881            SiteKind::Not { .. } | SiteKind::Range { .. } if opaque => return Planned::Nothing,
1882            SiteKind::Not { .. } | SiteKind::Range { .. } => return Planned::Unreached,
1883            SiteKind::Cmp { op, literal, .. } => {
1884                let op = *op;
1885                let mut merged = Obs::default();
1886                for bin in &self.binaries {
1887                    merged.merge(&bin.trace.merged(id));
1888                }
1889                let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
1890                let cmp_plan = plan::plan_cmp(op, &merged, domain_of(*literal, bounds));
1891                let mut gaps = vec![];
1892                let mut constant = false;
1893                match &cmp_plan.gap {
1894                    Some(plan::InputGap::Unreached) => return Planned::Unreached,
1895                    Some(gap) => {
1896                        constant = matches!(gap, plan::InputGap::OneSided { .. });
1897                        if let Some(finding) =
1898                            report::input_gap_finding(file, site, gap, &merged, verify)
1899                        {
1900                            gaps.push(PlannedGap {
1901                                finding,
1902                                survivors: gap.survivors(),
1903                                constant_expr: None,
1904                            });
1905                        }
1906                    }
1907                    None => {}
1908                }
1909                SitePlan {
1910                    gaps,
1911                    constant,
1912                    cannot_differ: cmp_plan.cannot_differ,
1913                    run: cmp_plan.run,
1914                    infected: Box::new(move |bin, m| {
1915                        tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
1916                    }),
1917                    reaching: Box::new(move |bin| {
1918                        tests_where(bin.trace.cmp.get(&id), Obs::reached)
1919                    }),
1920                }
1921            }
1922            SiteKind::Logic {
1923                and,
1924                lhs,
1925                rhs,
1926                gap: op_gap,
1927            } => {
1928                let and = *and;
1929                let lhs_range = core_range(site.start, lhs);
1930                let rhs_range = core_range(op_gap.1, rhs);
1931                let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
1932                let logic_plan = plan::plan_logic(and, &merged);
1933                if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
1934                    return Planned::Unreached;
1935                }
1936                let gaps: Vec<_> = logic_plan
1937                    .gaps
1938                    .iter()
1939                    .filter_map(|gap| {
1940                        // "The operand never decides" is the same statement as "the operand
1941                        // had one value whenever it was evaluated".
1942                        let (mutation, operand) = match gap {
1943                            plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
1944                            _ => (Mutation::LogicDropLhs, lhs_range),
1945                        };
1946                        Some(PlannedGap {
1947                            finding: report::logic_gap_finding(file, site, *gap, verify)?,
1948                            survivors: vec![mutation],
1949                            constant_expr: Some(operand),
1950                        })
1951                    })
1952                    .collect();
1953                SitePlan {
1954                    constant: merged.constant_value(and).is_some(),
1955                    cannot_differ: false,
1956                    gaps,
1957                    run: logic_plan.run,
1958                    infected: Box::new(move |bin, m| {
1959                        tests_where(bin.trace.logic.get(&id), |obs| {
1960                            plan::logic_infects(and, m, obs)
1961                        })
1962                    }),
1963                    reaching: Box::new(move |bin| {
1964                        tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
1965                    }),
1966                }
1967            }
1968            SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
1969                // `max` / `min` are recorded like an operator and its swap: they agree
1970                // exactly when the operands are equal.
1971                let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
1972                let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
1973                    SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
1974                    SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
1975                        (Mutation::ArithSwap, merged),
1976                        (Mutation::ArithSwap2, merged.second()),
1977                    ],
1978                    _ => vec![(Mutation::ArithSwap, merged)],
1979                };
1980                let (mut gaps, mut run) = (vec![], vec![]);
1981                for (mutation, seen) in mutations {
1982                    match plan::plan_arith(&seen) {
1983                        plan::ArithPlan::Unreached => return Planned::Unreached,
1984                        // Not numbers (`String + &str`, `Duration + Duration`): nothing to mutate.
1985                        plan::ArithPlan::Opaque => return Planned::Nothing,
1986                        plan::ArithPlan::NeverDiffers => {
1987                            let finding = if mutation == Mutation::MinMax {
1988                                report::min_max_gap_finding(file, site, verify)
1989                            } else {
1990                                report::arith_gap_finding(file, site, mutation, verify)
1991                            };
1992                            gaps.extend(finding.map(|finding| PlannedGap {
1993                                finding,
1994                                survivors: vec![mutation],
1995                                constant_expr: None,
1996                            }));
1997                        }
1998                        plan::ArithPlan::Run => run.push(mutation),
1999                    }
2000                }
2001                SitePlan {
2002                    gaps,
2003                    constant: false,
2004                    cannot_differ: false,
2005                    run,
2006                    infected: Box::new(move |bin, m| {
2007                        tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
2008                    }),
2009                    reaching: Box::new(move |bin| {
2010                        tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
2011                    }),
2012                }
2013            }
2014            SiteKind::Return {
2015                sole_expr, option, ..
2016            } => {
2017                let sole_expr = *sole_expr;
2018                let is_option = option.is_some();
2019                let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
2020                let return_plan = if is_option {
2021                    plan::plan_option_return(&merged)
2022                } else {
2023                    plan::plan_return(&merged)
2024                };
2025                if return_plan.unreached {
2026                    return Planned::Unreached;
2027                }
2028                let gaps: Vec<_> = return_plan
2029                    .always
2030                    .and_then(|always| {
2031                        Some(PlannedGap {
2032                            finding: report::return_gap_finding(file, site, always, verify)?,
2033                            survivors: vec![Mutation::Const(always)],
2034                            // A body that is one expression returns that expression's value.
2035                            constant_expr: sole_expr,
2036                        })
2037                    })
2038                    .into_iter()
2039                    .collect();
2040                SitePlan {
2041                    constant: false,
2042                    cannot_differ: false,
2043                    gaps,
2044                    run: return_plan.run,
2045                    infected: Box::new(move |bin, m| {
2046                        tests_where(bin.trace.returns.get(&id), |obs| match m {
2047                            Mutation::Const(value) => obs.infected_by_const(value),
2048                            _ => obs.reached(),
2049                        })
2050                    }),
2051                    reaching: Box::new(move |bin| {
2052                        tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
2053                    }),
2054                }
2055            }
2056        })
2057    }
2058
2059    fn job(
2060        &self,
2061        site: u32,
2062        mutation: Mutation,
2063        tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
2064    ) -> Job {
2065        let tests = self
2066            .binaries
2067            .iter()
2068            .enumerate()
2069            .filter_map(|(index, bin)| {
2070                let tests = tests_of(bin);
2071                if tests.is_empty() {
2072                    return None;
2073                }
2074                let filter = match bin.runner {
2075                    Runner::Exe(_) => test_filter(&tests, &bin.tests),
2076                    Runner::Doc { .. } | Runner::Isolated { .. } => None,
2077                };
2078                Some((index, filter))
2079            })
2080            .collect();
2081        Job {
2082            site,
2083            mutation,
2084            tests,
2085        }
2086    }
2087
2088    /// Runs one mutant against its tests, stopping at the first test that fails.
2089    /// Runs one mutant while `sharing` jobs run at the same time.
2090    fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
2091        let spec = format!("{}:{}", job.site, job.mutation.encode());
2092        let mut passed = vec![];
2093        // One failure is enough: the quick binaries first.
2094        let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
2095        tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
2096        for (index, filter) in tests {
2097            let bin = &self.binaries[*index];
2098            let outcome = run_binary(
2099                bin,
2100                filter.as_deref(),
2101                &[("TMT_MUTANT", &spec)],
2102                mutant_timeout(bin.baseline),
2103                RunOutput::FirstFailure,
2104                sharing,
2105            )?;
2106            if outcome != Outcome::Pass {
2107                return Ok(JobResult {
2108                    survived: None,
2109                    timed_out: outcome == Outcome::Timeout,
2110                    unable: outcome == Outcome::Unable,
2111                });
2112            }
2113            match filter {
2114                Some(names) => passed.extend(names.iter().cloned()),
2115                None if matches!(bin.runner, Runner::Isolated { .. }) => {
2116                    passed.push(bin.name.clone())
2117                }
2118                None => passed.push(format!("all tests of `{}`", bin.name)),
2119            }
2120        }
2121        Ok(JobResult {
2122            survived: Some(passed),
2123            timed_out: false,
2124            unable: false,
2125        })
2126    }
2127
2128    /// Runs a surviving mutant once more with tracing on, and returns what it changed in
2129    /// each test compared with the original run.
2130    fn trace_job(
2131        &self,
2132        job: &Job,
2133        scratch: &Path,
2134        sharing: usize,
2135    ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
2136        let spec = format!("{}:{}", job.site, job.mutation.encode());
2137        let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
2138        for (index, filter) in &job.tests {
2139            let bin = &self.binaries[*index];
2140            let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
2141            let _ = fs::remove_file(&path);
2142            let trace_env = path.to_string_lossy().into_owned();
2143            let outcome = run_binary(
2144                bin,
2145                filter.as_deref(),
2146                &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
2147                mutant_timeout(bin.traced),
2148                RunOutput::Quiet,
2149                sharing,
2150            )?;
2151            let text = fs::read_to_string(&path).unwrap_or_default();
2152            let _ = fs::remove_file(&path);
2153            if outcome != Outcome::Pass {
2154                continue; // not the run we saw before: say nothing rather than guess
2155            }
2156            let mutated = Trace::parse(&text);
2157            let ran: Option<BTreeSet<String>> =
2158                filter.as_ref().map(|names| names.iter().cloned().collect());
2159            for (test, found) in propagation::changes(&bin.trace, &mutated, ran.as_ref(), job.site)
2160            {
2161                all.entry(test).or_default().extend(found);
2162            }
2163        }
2164        Ok(all)
2165    }
2166
2167    /// Runs every job exactly once on `workers` threads (formal/tla/JobPool.tla) and
2168    /// returns the results in job order.
2169    /// Runs the mutants, `workers` at a time. A mutant that ran out of time while others
2170    /// were running may only have been slowed down by them: it gets a second run on its
2171    /// own, and that one counts.
2172    fn run_jobs(&self, jobs: &[Job], workers: usize, label: &str) -> Result<Vec<JobResult>> {
2173        let sharing = workers.clamp(1, jobs.len().max(1));
2174        progress::track(self.progress, label, jobs.len(), |progress| {
2175            let mut results = run_pool(jobs.len(), workers, |index| {
2176                let result = self.run_job(&jobs[index], sharing)?;
2177                if !(sharing > 1 && result.timed_out) {
2178                    progress.complete(result.progress_outcome());
2179                }
2180                Ok(result)
2181            })?;
2182            if sharing > 1 {
2183                for (job, result) in jobs.iter().zip(&mut results) {
2184                    if result.timed_out {
2185                        *result = self.run_job(job, 1)?;
2186                        progress.complete(result.progress_outcome());
2187                    }
2188                }
2189            }
2190            Ok(results)
2191        })
2192    }
2193}
2194
2195/// Calls `work(i)` once for every `i < count`, on up to `workers` threads, and returns the
2196/// results in index order. The first error wins.
2197fn run_pool<T: Send>(
2198    count: usize,
2199    workers: usize,
2200    work: impl Fn(usize) -> Result<T> + Sync,
2201) -> Result<Vec<T>> {
2202    let next = std::sync::atomic::AtomicUsize::new(0);
2203    let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
2204        let handles: Vec<_> = (0..workers.clamp(1, count.max(1)))
2205            .map(|_| {
2206                scope.spawn(|| {
2207                    let mut mine = vec![];
2208                    loop {
2209                        // Claiming is one atomic step: no two workers get the same index.
2210                        let index = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2211                        if index >= count {
2212                            return mine;
2213                        }
2214                        mine.push((index, work(index)));
2215                    }
2216                })
2217            })
2218            .collect();
2219        handles
2220            .into_iter()
2221            .map(|h| h.join().expect("worker panicked"))
2222            .collect()
2223    });
2224    let mut slots: Vec<Option<T>> = (0..count).map(|_| None).collect();
2225    for (index, result) in done.into_iter().flatten() {
2226        slots[index] = Some(result?);
2227    }
2228    Ok(slots
2229        .into_iter()
2230        .map(|slot| slot.expect("every job ran"))
2231        .collect())
2232}
2233
2234pub fn run(options: &Options) -> Result<Report> {
2235    let selection = &options.test_selection;
2236    if options.doc && selection.enabled() {
2237        bail!("--doc cannot be combined with isolated test selection");
2238    }
2239    let note = |text: &str| {
2240        if options.progress {
2241            eprintln!("tmt: {text}");
2242        }
2243    };
2244    let dir = options
2245        .dir
2246        .canonicalize()
2247        .with_context(|| format!("no such directory: {}", options.dir.display()))?;
2248
2249    // 1. Locate the package.
2250    let output = Command::new("cargo")
2251        .args(["metadata", "--no-deps", "--format-version", "1"])
2252        .args(options.cargo.flags())
2253        .current_dir(&dir)
2254        .output()
2255        .context("running cargo metadata")?;
2256    if !output.status.success() {
2257        bail!(
2258            "cargo metadata failed:\n{}",
2259            String::from_utf8_lossy(&output.stderr)
2260        );
2261    }
2262    let metadata: Metadata =
2263        serde_json::from_slice(&output.stdout).context("parsing cargo metadata")?;
2264    let package = match &options.package {
2265        Some(name) => metadata.packages.iter().find(|p| &p.name == name),
2266        None => metadata
2267            .packages
2268            .iter()
2269            .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
2270            .or(match &metadata.packages[..] {
2271                [only] => Some(only),
2272                _ => None,
2273            }),
2274    }
2275    .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
2276    // The packages whose tests are built and run: the analysed one, and on request others
2277    // of the workspace that use it.
2278    let mut test_packages: Vec<&Package> = vec![package];
2279    for name in &options.also_test {
2280        let other = metadata
2281            .packages
2282            .iter()
2283            .find(|p| &p.name == name)
2284            .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
2285        if !test_packages.iter().any(|p| p.name == other.name) {
2286            test_packages.push(other);
2287        }
2288    }
2289    if options.dependents {
2290        for name in dependents_of(&package.name, &metadata.packages) {
2291            if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
2292                && !test_packages.iter().any(|p| p.name == other.name)
2293            {
2294                test_packages.push(other);
2295            }
2296        }
2297    }
2298    let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
2299    let root_target = package
2300        .targets
2301        .iter()
2302        .find(|t| is_kind(t, &["lib", "rlib", "cdylib", "staticlib", "dylib"]))
2303        .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
2304        .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
2305
2306    // 2. Copy the workspace.
2307    let workspace = metadata.workspace_root.canonicalize()?;
2308    let work = match &options.work_dir {
2309        Some(dir) => {
2310            fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
2311            dir.canonicalize()?
2312        }
2313        None => metadata.target_directory.join("tmt"),
2314    };
2315    // The copy is brought up to date on every run, and files that are no longer wanted
2316    // are deleted from it. Make sure it is ours to delete from.
2317    if workspace.starts_with(&work) {
2318        bail!(
2319            "the work directory {} contains the workspace; choose a directory of its own",
2320            work.display()
2321        );
2322    }
2323    fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
2324    let work = work.canonicalize()?;
2325    let copy = work.join("src");
2326    let marker = work.join(WORK_MARKER);
2327    if copy.exists() && !marker.exists() {
2328        bail!(
2329            "{} exists and was not created by tmt; refusing to delete it. \
2330                 Choose another --work-dir or remove it yourself.",
2331            copy.display()
2332        );
2333    }
2334    fs::write(
2335        &marker,
2336        "Working directory of tmt (targeted-mutation). Safe to delete.\n",
2337    )?;
2338    let _lock = WorkLock::take(&work)?;
2339    let target_dir = metadata.target_directory.clone();
2340    let forbidden = |path: &Path| {
2341        path == target_dir
2342            || path == work
2343            || path.file_name().is_some_and(|n| n == ".git")
2344            || (path.parent() == Some(workspace.as_path())
2345                && path.file_name().is_some_and(|n| n == "target"))
2346    };
2347    let skip =
2348        |path: &Path| forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules");
2349    let state = WorkCopy::open(&work, &copy);
2350    work_directory(&work, "src")?;
2351    let visible = if options.all_files {
2352        None
2353    } else {
2354        git_visible_files(&workspace)?
2355    };
2356    match visible {
2357        // Only what git would not ignore: build output, caches, local notes and secrets
2358        // that are kept out of the repository stay out of the copy too.
2359        Some(files) => {
2360            let copied = copy_git_visible(&workspace, &copy, files, &workspace, &skip, &state)?;
2361            note(&format!(
2362                "copied {copied} files (ignored files are left out)"
2363            ));
2364        }
2365        None => copy_tree(&workspace, &copy, &workspace, &skip, &state)?,
2366    }
2367    for relative in &options.copy_fixtures {
2368        use std::path::Component;
2369        let relative = relative
2370            .components()
2371            .filter(|c| *c != Component::CurDir)
2372            .collect::<PathBuf>();
2373        if relative.as_os_str().is_empty()
2374            || relative
2375                .components()
2376                .any(|c| !matches!(c, Component::Normal(_)))
2377        {
2378            bail!(
2379                "--copy-fixture must name a file or directory inside the workspace: {}",
2380                relative.display()
2381            );
2382        }
2383        copy_fixture_entry(
2384            &workspace.join(&relative),
2385            &copy.join(&relative),
2386            &workspace,
2387            &forbidden,
2388            &state,
2389            &mut BTreeSet::new(),
2390        )?;
2391    }
2392    prune(&copy, &state)?;
2393    if options.git_index {
2394        git_index::snapshot(&workspace, &copy)?;
2395    }
2396    // Relative path dependencies that leave the workspace would point nowhere from the copy.
2397    let mut manifests: Vec<&Path> = metadata
2398        .packages
2399        .iter()
2400        .map(|p| p.manifest_path.as_path())
2401        .collect();
2402    let root_manifest = metadata.workspace_root.join("Cargo.toml");
2403    manifests.push(&root_manifest);
2404    for manifest in manifests {
2405        let Ok(canonical) = manifest.canonicalize() else {
2406            continue;
2407        };
2408        let (Some(manifest_dir), Ok(relative)) =
2409            (canonical.parent(), canonical.strip_prefix(&workspace))
2410        else {
2411            continue;
2412        };
2413        let text = fs::read_to_string(&canonical)?;
2414        if let Some(rewritten) =
2415            absolutize_path_dependencies(&text, manifest_dir, &workspace, &copy)?
2416        {
2417            state.write(&copy.join(relative), &rewritten)?;
2418        }
2419    }
2420
2421    let in_copy = |path: &Path| -> Result<PathBuf> {
2422        let canonical = path.canonicalize()?;
2423        let relative = canonical
2424            .strip_prefix(&workspace)
2425            .with_context(|| format!("{} is outside the workspace", path.display()))?;
2426        Ok(copy.join(relative))
2427    };
2428    let package_dir = in_copy(
2429        package
2430            .manifest_path
2431            .parent()
2432            .expect("manifest has a parent"),
2433    )?;
2434    let root_file = in_copy(&root_target.src_path)?;
2435    let source_dir = root_file
2436        .parent()
2437        .expect("source file has a parent")
2438        .to_path_buf();
2439
2440    // 3. Find the sites.
2441    let mut other_roots = HashSet::new();
2442    let mut other_dirs = HashSet::new();
2443    for target in &package.targets {
2444        if target.src_path == root_target.src_path {
2445            continue;
2446        }
2447        let path = in_copy(&target.src_path)?;
2448        if let Some(parent) = path.parent().filter(|p| *p != source_dir) {
2449            other_dirs.insert(parent.to_path_buf());
2450        }
2451        other_roots.insert(path);
2452    }
2453    let mut paths = vec![];
2454    rust_files(
2455        &source_dir,
2456        &|p| {
2457            other_roots.contains(p)
2458                || other_dirs.contains(p)
2459                || p.file_name().is_some_and(|n| n == "target")
2460        },
2461        &mut paths,
2462    )?;
2463    let scope = requested_scope(options, &workspace, &package_dir, &copy)?;
2464    let mut skipped = vec![];
2465    let mut files = vec![];
2466    let mut test_only = HashSet::new();
2467    let mut next_id = 0u32;
2468    for path in paths {
2469        let Some(original) = state.original(&path, &workspace)? else {
2470            continue; // left by an earlier run; gone or rewritten before the build
2471        };
2472        let display = path
2473            .strip_prefix(&package_dir)
2474            .unwrap_or(&path)
2475            .display()
2476            .to_string();
2477        match instrument::discover(&original, next_id) {
2478            Ok(found) => {
2479                next_id += found.sites.len() as u32;
2480                for module in &found.test_modules {
2481                    test_only.extend(module_paths(&path, module));
2482                }
2483                let places = found
2484                    .sites
2485                    .iter()
2486                    .chain(&found.rebuild_sites)
2487                    .map(|site| {
2488                        let at = report::location("", site);
2489                        (at.line, at.column, at.code)
2490                    })
2491                    .collect();
2492                files.push(SourceFile {
2493                    display,
2494                    path,
2495                    original,
2496                    places,
2497                    sites: found.sites,
2498                    rebuild_sites: found.rebuild_sites,
2499                    rendered: None,
2500                });
2501            }
2502            Err(err) => {
2503                let relative = path.strip_prefix(&copy).unwrap_or(&path).to_string_lossy();
2504                if scope
2505                    .as_ref()
2506                    .is_none_or(|scope| scope.touches(&relative, 1, usize::MAX))
2507                {
2508                    let diagnostic = format!("{err:#}");
2509                    note(&format!("skipping {display}: {diagnostic}"));
2510                    skipped.push(report::SkippedSite::new(
2511                        report::Location {
2512                            file: display,
2513                            line: 1,
2514                            column: 1,
2515                            ..Default::default()
2516                        },
2517                        &original,
2518                        original.len(),
2519                        report::SkipReason::UnparseableSource,
2520                        Some(diagnostic),
2521                    ));
2522                }
2523            }
2524        }
2525    }
2526    files.retain(|f| !f.path.ancestors().any(|a| test_only.contains(a)));
2527
2528    // Only the requested lines, if any were requested.
2529    if let Some(scope) = &scope {
2530        for file in &mut files {
2531            let relative = file
2532                .path
2533                .strip_prefix(&copy)
2534                .unwrap_or(&file.path)
2535                .to_string_lossy()
2536                .into_owned();
2537            let original = &file.original;
2538            let in_scope = |site: &Site| {
2539                scope.touches(&relative, scope::line_of(original, site.start), scope::line_of(original, site.end))
2540                    // A function is in scope by its signature line too.
2541                    || scope.touches(&relative, site.line, site.line)
2542            };
2543            file.sites.retain(in_scope);
2544            file.rebuild_sites.retain(in_scope);
2545        }
2546        files.retain(|f| !f.sites.is_empty() || !f.rebuild_sites.is_empty() || f.path == root_file);
2547    }
2548    let total_sites: usize = files
2549        .iter()
2550        .map(|f| f.sites.len() + f.rebuild_sites.len())
2551        .sum();
2552    note(&format!("{} sites in {} files", total_sites, files.len()));
2553    if options.source_only {
2554        for file in &mut files {
2555            file.rebuild_sites.append(&mut file.sites);
2556        }
2557    }
2558
2559    let mut report = Report {
2560        package: package.name.clone(),
2561        sites: total_sites,
2562        analysis: report::Analysis {
2563            package_path: repository_prefix(
2564                package.manifest_path.parent().unwrap_or(Path::new(".")),
2565            ),
2566            since: options.since.clone(),
2567            lines: options.lines.clone(),
2568            tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
2569            cargo: options.cargo.clone(),
2570            opt_level: options.opt_level,
2571            rebuild: options.rebuild || options.source_only,
2572            verified: options.verify && !options.source_only,
2573            doc_tests: options.doc,
2574            source_only: options.source_only,
2575            test_selection: None,
2576            git_index: options.git_index,
2577            copy_fixtures: options.copy_fixtures.clone(),
2578        },
2579        skipped,
2580        ..Report::default()
2581    };
2582    if scope.is_some() && total_sites == 0 {
2583        // Restore files changed by a previous run before reporting a selection with no work.
2584        state.settle(&workspace)?;
2585        if let Some(path) = &options.baseline {
2586            crate::baseline::load(path)?;
2587        }
2588        if let Some(path) = &options.write_baseline {
2589            crate::baseline::write(path, &[])?;
2590        }
2591        report.record_evaluation();
2592        return Ok(report);
2593    }
2594
2595    let root_source = state
2596        .original(&root_file, &workspace)?
2597        .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
2598    let root_suffix = if options.source_only {
2599        String::new()
2600    } else {
2601        state.write(
2602            &source_dir.join(format!("{RUNTIME_MOD}.rs")),
2603            crate::RUNTIME_SOURCE,
2604        )?;
2605        let std_alias = format!("extern crate std as {STD_ALIAS};");
2606        if root_source.contains(&std_alias) {
2607            format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
2608        } else {
2609            format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
2610        }
2611    };
2612
2613    // 4. Build, disabling the sites whose probe does not compile (formal/tla/RepairLoop.tla).
2614    let mut disabled: HashSet<u32> = HashSet::new();
2615    let mut repairs = BTreeMap::new();
2616    let build_target = work_directory(&work, "target")?;
2617    let target_flags = test_build_flags(
2618        &test_packages,
2619        &selection.targets,
2620        &workspace,
2621        &options.cargo,
2622    );
2623    let build_scope = if target_flags.is_some() {
2624        report::TestBuildScope::SelectedTargets
2625    } else {
2626        report::TestBuildScope::PackageWide
2627    };
2628    let build_note = if !selection.targets.is_empty() && target_flags.is_none() {
2629        "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
2630    } else {
2631        ""
2632    };
2633    if !build_note.is_empty() {
2634        note(build_note.trim_end());
2635    }
2636    let cargo_build = || {
2637        let mut command = Command::new("cargo");
2638        isolate_copy_command(&mut command, &work);
2639        command
2640            .args(["test", "--no-run", "--message-format=json"])
2641            .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
2642            .args(target_flags.as_deref().unwrap_or_default())
2643            .args(options.cargo.flags())
2644            .current_dir(&copy)
2645            .env("CARGO_TARGET_DIR", &build_target)
2646            .env("CARGO_BUILD_BUILD_DIR", &build_target)
2647            .envs(profile_env(options.opt_level))
2648            .stderr(Stdio::piped())
2649            .output()
2650            .context("running cargo test --no-run")
2651    };
2652    let mut rounds = 0;
2653    let build = loop {
2654        for file in &mut files {
2655            let rendered =
2656                instrument::render(&file.original, &file.sites, &|id| !disabled.contains(&id));
2657            let mut text = rendered.text.clone();
2658            if file.path == root_file {
2659                text.push_str(&root_suffix);
2660            }
2661            state.write(&file.path, &text)?;
2662            file.rendered = Some(rendered);
2663        }
2664        if !files.iter().any(|f| f.path == root_file) {
2665            state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
2666        }
2667        if rounds == 0 {
2668            state.settle(&workspace)?;
2669        }
2670        note(if rounds == 0 {
2671            "building the instrumented crate"
2672        } else {
2673            "rebuilding without the sites that failed to compile"
2674        });
2675        let output = cargo_build()?;
2676        let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
2677        let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
2678        if output.status.success() {
2679            break build;
2680        }
2681        if build.errors.is_empty() {
2682            bail!(
2683                "the build failed:\n{build_note}{}",
2684                String::from_utf8_lossy(&output.stderr)
2685            );
2686        }
2687        rounds += 1;
2688        let before = disabled.len();
2689        let mut unexplained = vec![];
2690        let mut blamed_now: HashSet<u32> = HashSet::new();
2691        for error in &build.errors {
2692            let blamed = blame_error(error, &files, &copy, &disabled);
2693            if std::env::var_os("TMT_DEBUG").is_some() {
2694                eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
2695            }
2696            if blamed.is_empty() {
2697                unexplained.push(error);
2698            }
2699            for id in blamed {
2700                repairs
2701                    .entry(id)
2702                    .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
2703                blamed_now.insert(id);
2704            }
2705        }
2706        disabled.extend(blamed_now);
2707        if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
2708            let shown = unexplained
2709                .first()
2710                .copied()
2711                .or(build.errors.first())
2712                .map_or("", |e| e.rendered.as_str());
2713            bail!(
2714                "the crate does not build after instrumentation, and the error is not at a probe.\n\
2715                 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{shown}"
2716            );
2717        }
2718    };
2719    if build.test_binaries.is_empty() {
2720        bail!("{build_note}`{}` has no test binaries", package.name);
2721    }
2722
2723    // 5. Trace run: what does each test observe?
2724    let mut session = Session {
2725        progress: options.progress,
2726        package_dir,
2727        binaries: vec![],
2728    };
2729    let wrapper = selection
2730        .wrapper
2731        .as_ref()
2732        .map(|path| {
2733            if path.is_absolute()
2734                || path
2735                    .components()
2736                    .any(|c| matches!(c, std::path::Component::ParentDir))
2737            {
2738                bail!(
2739                    "--test-wrapper must be a path inside the workspace: {}",
2740                    path.display()
2741                );
2742            }
2743            let copied = copy.join(path);
2744            if !copied.is_file() {
2745                bail!(
2746                    "test wrapper is missing from the work copy: {}",
2747                    copied.display()
2748                );
2749            }
2750            Ok(copied)
2751        })
2752        .transpose()?;
2753    let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
2754    for (name, exe, owner, kind) in build.test_binaries {
2755        if !selection.targets.is_empty() && !selection.targets.contains(&name) {
2756            continue;
2757        }
2758        let owner_package = test_packages
2759            .iter()
2760            .find(|p| p.name == owner)
2761            .expect("binaries are filtered by these packages");
2762        let cwd = in_copy(
2763            owner_package
2764                .manifest_path
2765                .parent()
2766                .expect("manifest has a parent"),
2767        )?;
2768        if selection.enabled() {
2769            let all = list_tests(&exe, &cwd, &work, false, true)?;
2770            let ignored = list_tests(&exe, &cwd, &work, true, true)?;
2771            for test in all {
2772                let was_ignored = ignored.contains(&test);
2773                if (was_ignored && !selection.include_ignored)
2774                    || (!selection.include.is_empty() && !selection.include.contains(&test))
2775                    || selection.exclude.contains(&test)
2776                {
2777                    continue;
2778                }
2779                runners.push((
2780                    format!("{owner}::{}::{name}::{test}", kind.join("+")),
2781                    Runner::Isolated {
2782                        exe: exe.clone(),
2783                        test,
2784                        ignored: was_ignored,
2785                        wrapper: wrapper.clone(),
2786                    },
2787                    cwd.clone(),
2788                ));
2789            }
2790            continue;
2791        }
2792        // Tests of other packages are named after their package.
2793        let name = if owner == package.name {
2794            name
2795        } else {
2796            format!("{owner}::{name}")
2797        };
2798        runners.push((name, Runner::Exe(exe), cwd));
2799    }
2800    if selection.enabled() && runners.is_empty() {
2801        bail!("{build_note}no tests matched the requested selection");
2802    }
2803    let selected_tests = selection.enabled().then(|| report::TestSelection {
2804        build_scope,
2805        wrapper: selection
2806            .wrapper
2807            .as_ref()
2808            .map(|path| path.display().to_string()),
2809        tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
2810    });
2811    if options.doc && is_kind(root_target, &["lib", "rlib", "proc-macro"]) {
2812        let doc = Runner::Doc {
2813            copy: copy.clone(),
2814            target_dir: build_target.clone(),
2815            package: package.name.clone(),
2816            opt_level: options.opt_level,
2817            flags: options.cargo.flags(),
2818        };
2819        runners.push(("doc tests".to_string(), doc, session.package_dir.clone()));
2820    }
2821    // The marks by which a run says that it gave up are made where nothing else makes
2822    // files: the working directory is this analysis's alone while it is locked. A
2823    // directory shared with others (the temporary one, between containers that count
2824    // their processes alike) could hand one run's mark to another.
2825    let marks = marks_dir(&work)?;
2826    for (index, (name, runner, cwd)) in runners.into_iter().enumerate() {
2827        let trace_path = work.join(format!("trace-{index}.tsv"));
2828        let _ = fs::remove_file(&trace_path);
2829        let mut bin = TestBinary {
2830            name,
2831            cwd,
2832            marks: marks.clone(),
2833            git_ceiling: work.clone(),
2834            tests: BTreeSet::new(),
2835            runner,
2836            baseline: Duration::ZERO,
2837            traced: Duration::ZERO,
2838            trace: Trace::default(),
2839        };
2840        session.note(&format!("tracing `{}`", bin.name));
2841        let started = Instant::now();
2842        let trace_env = trace_path.to_string_lossy().into_owned();
2843        let trace = [("TMT_TRACE", trace_env.as_str())];
2844        run_baseline(
2845            &bin,
2846            if options.source_only { &[] } else { &trace },
2847            Duration::from_secs(3600),
2848            &work.join(format!("baseline-{index}.log")),
2849            false,
2850        )?;
2851        bin.traced = started.elapsed();
2852        bin.baseline = bin.traced;
2853        // Recording slows code in loops down a lot, and the time limit of every mutant
2854        // is a multiple of this: where it matters, time the tests as the mutants run them.
2855        if !options.source_only && bin.traced > SLOW_TRACE {
2856            let started = Instant::now();
2857            if run_baseline(
2858                &bin,
2859                &[],
2860                bin.traced,
2861                &work.join(format!("baseline-{index}-untraced.log")),
2862                true,
2863            )? {
2864                bin.baseline = started.elapsed();
2865            }
2866        }
2867        // No file means no probe was reached. Anything else unreadable or malformed means
2868        // the evidence is incomplete, and conclusions drawn from it would be wrong.
2869        let text = match fs::read_to_string(&trace_path) {
2870            Ok(text) => text,
2871            Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
2872            Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
2873        };
2874        bin.trace = Trace::parse(&text);
2875        if bin.trace.malformed_lines > 0 {
2876            bail!(
2877                "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
2878                bin.name,
2879                bin.trace.malformed_lines
2880            );
2881        }
2882        if let Runner::Exe(exe) = &bin.runner {
2883            bin.tests = list_tests(exe, &bin.cwd, &work, false, false)?;
2884        }
2885        session.binaries.push(bin);
2886    }
2887
2888    // 6. Plan every site, run the mutants, and put the findings together.
2889    report.analysis.test_selection = selected_tests;
2890    for file in &files {
2891        for site in &file.sites {
2892            if disabled.contains(&site.id) {
2893                let fallback = options.rebuild
2894                    && !matches!(site.kind, SiteKind::Body { .. })
2895                    && !instrument::source_mutants(site).is_empty();
2896                match site.kind {
2897                    SiteKind::Body { .. } => report.unviable_mutants += 1,
2898                    _ if fallback => {}
2899                    _ => report.skipped_sites += 1,
2900                }
2901                report.skipped.push(report::SkippedSite::new(
2902                    report::location(&file.display, site),
2903                    &file.original,
2904                    site.end,
2905                    if fallback {
2906                        report::SkipReason::ProbeReplacedBySourceRebuild
2907                    } else {
2908                        report::SkipReason::ProbeCompileError
2909                    },
2910                    repairs.get(&site.id).cloned(),
2911                ));
2912            }
2913        }
2914        if !options.rebuild && !options.source_only {
2915            report.skipped.extend(file.rebuild_sites.iter().map(|site| {
2916                report::SkippedSite::new(
2917                    report::location(&file.display, site),
2918                    &file.original,
2919                    site.end,
2920                    report::SkipReason::RequiresSourceRebuild,
2921                    None,
2922                )
2923            }));
2924        }
2925    }
2926    let scratch = work.clone();
2927    let mut jobs: Vec<Job> = vec![];
2928    // Sites whose mutant could not be run as a probe for what it is. With `--rebuild`
2929    // they are built from the source instead; without, they are counted.
2930    let mut not_evaluated: HashSet<u32> = HashSet::new();
2931    let mut work: Vec<SiteWork> = vec![];
2932    // `(index of the finding, job of its first surviving mutant)`.
2933    let mut effect_jobs: Vec<(usize, usize)> = vec![];
2934    for file in &files {
2935        for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2936            let plan = match session.plan(&file.display, site, options.verify) {
2937                Planned::Unreached => {
2938                    // A function is one place, however many sites it is.
2939                    let at = report::location(&file.display, site);
2940                    if report.unreached.last() != Some(&at) {
2941                        report.unreached.push(at);
2942                    }
2943                    continue;
2944                }
2945                Planned::Nothing => continue,
2946                Planned::NotEvaluated => {
2947                    not_evaluated.insert(site.id);
2948                    continue;
2949                }
2950                Planned::Plan(plan) => plan,
2951            };
2952            let mut add =
2953                |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2954                    jobs.push(session.job(site.id, mutation, tests_of));
2955                    jobs.len() - 1
2956                };
2957            let gaps = plan
2958                .gaps
2959                .into_iter()
2960                .map(
2961                    |PlannedGap {
2962                         finding,
2963                         survivors,
2964                         constant_expr,
2965                     }| {
2966                        // The trace says no test can notice. Confirm by running every test
2967                        // that reaches the site against the listed survivors.
2968                        let confirm = if options.verify {
2969                            survivors
2970                                .into_iter()
2971                                .map(|m| add(m, &*plan.reaching))
2972                                .collect()
2973                        } else {
2974                            vec![]
2975                        };
2976                        (finding, confirm, constant_expr)
2977                    },
2978                )
2979                .collect();
2980            let infected = &plan.infected;
2981            let runs = plan
2982                .run
2983                .iter()
2984                .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2985                .collect();
2986            work.push(SiteWork {
2987                file: &file.display,
2988                site,
2989                gaps,
2990                constant: plan.constant,
2991                cannot_differ: plan.cannot_differ,
2992                runs,
2993            });
2994        }
2995    }
2996    session.note(&format!(
2997        "running {} mutants on {} thread(s)",
2998        jobs.len(),
2999        options.jobs.max(1)
3000    ));
3001    let mut results = session.run_jobs(&jobs, options.jobs, "mutants")?;
3002
3003    // 6b. On request, check what the run rests on: that the tests chosen for a mutant
3004    // are the ones that could fail with it, and that the tests do the same twice.
3005    if let Some(wanted) = options.audit {
3006        let survivors: Vec<usize> = (0..jobs.len())
3007            .filter(|job| results[*job].survived.is_some())
3008            .collect();
3009        let chosen: Vec<usize> = spread(survivors.len(), wanted)
3010            .into_iter()
3011            .map(|nth| survivors[nth])
3012            .collect();
3013        session.note(&format!(
3014            "audit: running {} of {} surviving mutants against all tests",
3015            chosen.len(),
3016            survivors.len()
3017        ));
3018        let against_all: Vec<Job> = chosen
3019            .iter()
3020            .map(|job| Job {
3021                site: jobs[*job].site,
3022                mutation: jobs[*job].mutation,
3023                tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3024            })
3025            .collect();
3026        let mut audit = report::Audit {
3027            sampled: chosen.len(),
3028            survivors: survivors.len(),
3029            ..report::Audit::default()
3030        };
3031        for (job, again) in
3032            chosen
3033                .iter()
3034                .zip(session.run_jobs(&against_all, options.jobs, "audit mutants")?)
3035        {
3036            if again.survived.is_none() {
3037                // The verdict of all tests is the one that counts.
3038                results[*job] = again;
3039                let site = files
3040                    .iter()
3041                    .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
3042                if let Some((file, site)) = site {
3043                    audit
3044                        .disagreements
3045                        .push(report::location(&file.display, site));
3046                }
3047            }
3048        }
3049        session.note("audit: recording the tests once more");
3050        for (index, bin) in session.binaries.iter().enumerate() {
3051            let path = scratch.join(format!("trace-{index}-audit.tsv"));
3052            let _ = fs::remove_file(&path);
3053            let trace_env = path.to_string_lossy().into_owned();
3054            let limit = Duration::from_secs(3600);
3055            let outcome = run_binary(
3056                bin,
3057                None,
3058                &[("TMT_TRACE", &trace_env)],
3059                limit,
3060                RunOutput::Quiet,
3061                1,
3062            )?;
3063            let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
3064            let _ = fs::remove_file(&path);
3065            let records = bin.trace.differences(&again);
3066            if outcome != Outcome::Pass || records > 0 {
3067                audit.trace_differences.push(report::TraceDifference {
3068                    binary: bin.name.clone(),
3069                    records,
3070                });
3071            }
3072        }
3073        report.audit = Some(audit);
3074    }
3075    let unable = results.iter().filter(|r| r.unable).count();
3076    not_evaluated.extend(
3077        jobs.iter()
3078            .zip(&results)
3079            .filter(|(_, result)| result.unable)
3080            .map(|(job, _)| job.site),
3081    );
3082    if !options.rebuild {
3083        report.mutants_not_evaluated = not_evaluated.len();
3084    }
3085    report.mutants_run = results.len() - unable;
3086    report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
3087    report.mutants_timed_out = results.iter().filter(|r| r.timed_out).count();
3088
3089    // Expressions known to be constant in the tests: comparisons with a confirmed
3090    // one-sided gap or that cannot differ at all, and `&&` / `||` with a single value.
3091    let confirmed = |w: &SiteWork| {
3092        w.gaps
3093            .iter()
3094            .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
3095    };
3096    let constants: BTreeSet<(&str, usize, usize)> = work
3097        .iter()
3098        .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
3099        .map(|w| (w.file, w.site.start, w.site.end))
3100        .collect();
3101    for item in &work {
3102        let at = report::location(item.file, item.site);
3103        for (finding, confirm, constant_expr) in &item.gaps {
3104            // Already said by the site of the expression itself (or, for a comparison that
3105            // cannot differ, not worth saying at all).
3106            let repeats = constant_expr
3107                .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
3108            if confirm.iter().any(|j| results[*j].survived.is_none()) {
3109                report.unstable.push(at.clone());
3110            } else if !repeats {
3111                report.findings.push(finding.clone());
3112            }
3113        }
3114        // A body that is one expression, constant in the tests: replacing the body by
3115        // that constant was said at the expression (or cannot be told apart at all).
3116        if let SiteKind::Body {
3117            sole_expr: Some((start, end)),
3118            ..
3119        } = item.site.kind
3120            && constants.contains(&(item.file, start, end))
3121        {
3122            continue;
3123        }
3124        let mut survivors = vec![];
3125        let mut passing_tests = BTreeSet::new();
3126        for (mutation, job) in &item.runs {
3127            if let Some(tests) = &results[*job].survived {
3128                survivors.push(report::describe(item.site, *mutation));
3129                passing_tests.extend(tests.iter().cloned());
3130            }
3131        }
3132        if !survivors.is_empty() {
3133            // The first survivor is traced below to see what it changes.
3134            let first = item
3135                .runs
3136                .iter()
3137                .find(|(_, job)| results[*job].survived.is_some());
3138            effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
3139            report.findings.push(Finding::AssertionGap {
3140                at,
3141                survivors,
3142                tests: passing_tests.into_iter().collect(),
3143                effects: vec![],
3144                effects_of: None,
3145            });
3146        }
3147    }
3148
3149    // 7. What do the surviving mutants change in the tests that let them through?
3150    if options.effects && !effect_jobs.is_empty() {
3151        session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
3152        let sites: BTreeMap<u32, (&str, &Site)> = files
3153            .iter()
3154            .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
3155            .collect();
3156        let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
3157            session.trace_job(
3158                &jobs[effect_jobs[index].1],
3159                &scratch,
3160                options.jobs.clamp(1, effect_jobs.len()),
3161            )
3162        })?;
3163        for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
3164            // What happens inside the mutated code itself is not an effect of it: deleting
3165            // a statement trivially stops the expressions in it from running.
3166            if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
3167                for found in changes.values_mut() {
3168                    found.retain(|change| {
3169                        sites.get(&change.site()).is_none_or(|(file, site)| {
3170                            file != mutated_file
3171                                || site.end <= mutated.start
3172                                || mutated.end <= site.start
3173                        })
3174                    });
3175                }
3176                changes.retain(|_, found| !found.is_empty());
3177            }
3178            if let Finding::AssertionGap {
3179                effects,
3180                effects_of,
3181                ..
3182            } = &mut report.findings[*finding]
3183            {
3184                *effects = describe_effects(&changes, &sites);
3185                *effects_of = sites
3186                    .get(&jobs[*job].site)
3187                    .map(|(_, site)| report::describe(site, jobs[*job].mutation));
3188            }
3189        }
3190    }
3191
3192    // 7b. What a probe cannot be put in is mutated in the source, built and run: code in
3193    // a `const fn`, and the sites whose probe did not compile.
3194    // The last of the four: for an audit, the job that ran the same mutant as a probe.
3195    let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
3196    for file in &files {
3197        // Tried again as the source says them: what did not compile as a probe, and
3198        // what a probe could not be (a range that ends at the top of its type).
3199        let retried = file.sites.iter().filter(|site| {
3200            (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
3201                || not_evaluated.contains(&site.id)
3202        });
3203        for site in file.rebuild_sites.iter().chain(retried) {
3204            built.extend(
3205                instrument::source_mutants(site)
3206                    .into_iter()
3207                    .chain(
3208                        options
3209                            .source_only
3210                            .then(|| instrument::source_boundary_mutant(site))
3211                            .flatten(),
3212                    )
3213                    .map(|mutant| (file, site, mutant, None)),
3214            );
3215        }
3216    }
3217    if !options.rebuild && !options.source_only {
3218        report.mutants_not_built = built.len();
3219        built.clear();
3220    }
3221    // An audit also builds some of the mutants that were run as probes, from the source
3222    // as a person would write them, to see whether a probe and the real thing agree.
3223    if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
3224        let mut twins = vec![];
3225        for file in &files {
3226            for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
3227                // Only integers are known to always have an order.
3228                let integers = session.binaries.iter().all(|bin| {
3229                    let seen = bin.trace.merged(site.id);
3230                    !seen.reached() || seen.valued()
3231                });
3232                let job_of = |mutation: Mutation| {
3233                    jobs.iter()
3234                        .position(|job| job.site == site.id && job.mutation == mutation)
3235                };
3236                let mut compared = vec![];
3237                for mutant in instrument::source_mutants(site) {
3238                    // The first of the mutations that are this change and that was run.
3239                    let job = mutations_like(site, &mutant, integers)
3240                        .into_iter()
3241                        .find_map(job_of);
3242                    if let Some(job) = job {
3243                        compared.push(job);
3244                        twins.push((file, site, mutant, Some(job)));
3245                    }
3246                }
3247                // A negated comparison that no mutant of the source stands for (on
3248                // floats `<` is not "not `>=`") is compared with the negation written out.
3249                if let (SiteKind::Cmp { op, .. }, Some(job)) =
3250                    (&site.kind, job_of(Mutation::Negate))
3251                    && !compared.contains(&job)
3252                {
3253                    let negated = instrument::SourceMutant {
3254                        start: site.start,
3255                        end: site.end,
3256                        replacement: format!("!({})", site.text),
3257                        what: op.symbol().to_string(),
3258                        into: "!".to_string(),
3259                    };
3260                    twins.push((file, site, negated, Some(job)));
3261                }
3262            }
3263        }
3264        let chosen = spread(twins.len(), wanted);
3265        audit.rebuilt = chosen.len();
3266        let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
3267        built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
3268    }
3269    if !built.is_empty() {
3270        session.note(&format!(
3271            "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
3272            built.len()
3273        ));
3274        let instrumented = |file: &SourceFile, text: &str| {
3275            if file.path == root_file {
3276                format!("{text}{root_suffix}")
3277            } else {
3278                text.to_string()
3279            }
3280        };
3281        // All tests are run against each of them; the quick ones first, since one
3282        // failure is enough.
3283        let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
3284        by_speed.sort_by_key(|bin| bin.baseline);
3285        let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
3286        progress::track(
3287            options.progress,
3288            "source mutants",
3289            built.len(),
3290            |progress| -> Result<()> {
3291                for (file, site, mutant, twin) in &built {
3292                    let mutated = format!(
3293                        "{}{}{}",
3294                        &file.original[..mutant.start],
3295                        mutant.replacement,
3296                        &file.original[mutant.end..]
3297                    );
3298                    // `None`: it does not build. Otherwise what stopped it, if anything did.
3299                    let attempt = || -> Result<Option<Outcome>> {
3300                        state.write(&file.path, &instrumented(file, &mutated))?;
3301                        if !cargo_build()?.status.success() {
3302                            return Ok(None);
3303                        }
3304                        for bin in &by_speed {
3305                            let outcome = run_binary(
3306                                bin,
3307                                None,
3308                                &[],
3309                                mutant_timeout(bin.baseline),
3310                                RunOutput::FirstFailure,
3311                                1,
3312                            )?;
3313                            if outcome != Outcome::Pass {
3314                                return Ok(Some(outcome));
3315                            }
3316                        }
3317                        Ok(Some(Outcome::Pass))
3318                    };
3319                    let attempted = attempt();
3320                    // The file as it was, before another one is changed and whatever went wrong.
3321                    let rendered = file.rendered.as_ref().expect("rendered before building");
3322                    state.write(&file.path, &instrumented(file, &rendered.text))?;
3323                    let outcome = attempted?;
3324                    progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
3325                    if let Some(job) = twin {
3326                        // Only compared: the probe's run is the one that is counted and reported.
3327                        let as_probe = results[*job].survived.is_some();
3328                        let Some(audit) = report.audit.as_mut() else {
3329                            continue;
3330                        };
3331                        // What does not build, and what the probe could not be, says nothing.
3332                        let comparable = outcome.filter(|_| !results[*job].unable);
3333                        match comparable {
3334                            Some(_) => audit.compared += 1,
3335                            None => audit.not_compared += 1,
3336                        }
3337                        if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
3338                            let verdict = |passes: bool| if passes { "passes" } else { "fails" };
3339                            audit.source_disagreements.push(report::SourceDisagreement {
3340                                at: report::location(&file.display, site),
3341                                mutant: report::describe(site, mutation_of(site, mutant)),
3342                                as_probe: verdict(as_probe).to_string(),
3343                                built: verdict(!as_probe).to_string(),
3344                            });
3345                        }
3346                        continue;
3347                    }
3348                    match outcome {
3349                        None => report.unviable_mutants += 1,
3350                        Some(outcome) => {
3351                            report.mutants_run += 1;
3352                            report.mutants_killed += (outcome != Outcome::Pass) as usize;
3353                            report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3354                        }
3355                    }
3356                    let survived = outcome == Some(Outcome::Pass);
3357                    if survived {
3358                        let at = report::location(&file.display, site);
3359                        let text = report::describe(site, mutation_of(site, mutant));
3360                        match survivors.last_mut() {
3361                            Some((last, texts)) if *last == at => texts.push(text),
3362                            _ => survivors.push((at, vec![text])),
3363                        }
3364                    }
3365                }
3366                Ok(())
3367            },
3368        )?;
3369        report.findings.extend(
3370            survivors
3371                .into_iter()
3372                .map(|(at, survivors)| Finding::Survivor { at, survivors }),
3373        );
3374    }
3375
3376    report.record_evaluation();
3377    report.sort_findings();
3378    let places: Vec<FilePlaces> = files
3379        .iter()
3380        .map(|file| FilePlaces {
3381            display: &file.display,
3382            source: &file.original,
3383            places: &file.places,
3384        })
3385        .collect();
3386    name_findings(&mut report.findings, &places);
3387
3388    // 8. Findings the user has already dealt with.
3389    let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
3390        .iter()
3391        .map(|f| {
3392            (
3393                f.display.as_str(),
3394                crate::baseline::ignored_lines(&f.original),
3395            )
3396        })
3397        .collect();
3398    let known = match &options.baseline {
3399        Some(path) => Some(crate::baseline::load(path)?),
3400        None => None,
3401    };
3402    let location = |finding: &Finding| (finding.at().file.clone(), finding.at().line);
3403    let before = report.findings.len();
3404    report.findings.retain(|finding| {
3405        let (file, line) = location(finding);
3406        !ignored
3407            .get(file.as_str())
3408            .is_some_and(|lines| lines.contains_key(&line))
3409    });
3410    if let Some(path) = &options.write_baseline {
3411        crate::baseline::write(path, &report.findings)?;
3412    }
3413    report
3414        .findings
3415        .retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
3416    report.suppressed = before - report.findings.len();
3417    Ok(report)
3418}
3419
3420/// Where a directory is in its git repository: `crates/core/`, or nothing at the top
3421/// and outside of any. The files of a report are named from the package; this in front
3422/// of them names them from the repository, as a code-scanning service wants them.
3423fn repository_prefix(dir: &Path) -> String {
3424    let shown = Command::new("git")
3425        .arg("-C")
3426        .arg(dir)
3427        .args(["rev-parse", "--show-prefix"])
3428        .stderr(Stdio::null())
3429        .output();
3430    match shown {
3431        Ok(output) if output.status.success() => {
3432            String::from_utf8_lossy(&output.stdout).trim().to_string()
3433        }
3434        _ => String::new(),
3435    }
3436}
3437
3438/// `wanted` of the numbers below `count`, spread evenly and the same every time; all of
3439/// them where there are no more.
3440fn spread(count: usize, wanted: usize) -> Vec<usize> {
3441    let wanted = wanted.min(count);
3442    (0..wanted).map(|nth| nth * count / wanted).collect()
3443}
3444
3445/// What naming the findings of a file needs to know of it.
3446struct FilePlaces<'a> {
3447    display: &'a str,
3448    source: &'a str,
3449    /// Every site of the file as (line, column, code), whatever part of it was analysed.
3450    places: &'a [(usize, usize, String)],
3451}
3452
3453/// Gives every finding the item it is in and its name (`report::finding_id`). Which of
3454/// several places with the same code in one item a finding is at is counted over the
3455/// sites of the file, not over the findings: a finding keeps its number when the one
3456/// before it is closed.
3457fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
3458    for file in files {
3459        let items = instrument::named_items(file.source);
3460        let item_at = |line: usize, column: usize| -> String {
3461            instrument::offset_of(file.source, line, column)
3462                .map_or("", |offset| instrument::enclosing_item(&items, offset))
3463                .to_string()
3464        };
3465        // Every place of the file a finding can be at: where, in which item, on which code.
3466        let places: BTreeSet<(String, &str, usize, usize)> = file
3467            .places
3468            .iter()
3469            .map(|(line, column, code)| (item_at(*line, *column), code.as_str(), *line, *column))
3470            .collect();
3471        for finding in findings.iter_mut() {
3472            let kind = finding.kind();
3473            let at = finding.at_mut();
3474            if at.file != file.display {
3475                continue;
3476            }
3477            at.item = item_at(at.line, at.column);
3478            let nth = places
3479                .iter()
3480                .filter(|(item, code, line, column)| {
3481                    *item == at.item && *code == at.code && (*line, *column) < (at.line, at.column)
3482                })
3483                .count();
3484            at.id = report::finding_id(kind, at, nth);
3485        }
3486    }
3487}
3488
3489/// The mutation that a change of the source text is, to describe it in the same words.
3490fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
3491    match &site.kind {
3492        SiteKind::Cmp { .. } => plan::CmpOp::ALL
3493            .into_iter()
3494            .find(|op| op.symbol() == mutant.into)
3495            .map_or(Mutation::Negate, Mutation::Op),
3496        SiteKind::Arith { op, .. } => {
3497            if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
3498                Mutation::ArithSwap
3499            } else {
3500                Mutation::ArithSwap2
3501            }
3502        }
3503        SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
3504        SiteKind::Logic { .. } => Mutation::LogicSwap,
3505        SiteKind::Not { .. } => Mutation::DropNot,
3506        SiteKind::Range { .. } => Mutation::RangeEnd,
3507        // The other kinds have one mutant of the source: a statement, an arm, a field or
3508        // a minus that is not there, a body that is another.
3509        _ => Mutation::Delete,
3510    }
3511}
3512
3513/// The mutations a probe may have run that are the same change as a mutant of the source,
3514/// its own name first. A comparison is planned in other words than it is written in:
3515/// `a != b` for `a == b` is run as the negation, and on integers `a <= b` for `a < b` as
3516/// the bound moved by one.
3517///
3518/// `integers`: the operands are integers, which always have an order. For anything
3519/// else (a float can be NaN) the negation of `>=` is true where `<` is false, and is
3520/// not the same change.
3521fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
3522    let mut all = vec![mutation_of(site, mutant)];
3523    if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
3524        let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
3525        if into == op.negated() && (integers || !an_order_is_needed) {
3526            all.push(Mutation::Negate);
3527        }
3528        match (op, into) {
3529            (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
3530                all.push(Mutation::Shift(1))
3531            }
3532            (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
3533                all.push(Mutation::Shift(-1))
3534            }
3535            _ => {}
3536        }
3537    }
3538    all
3539}
3540
3541/// The changes a surviving mutant causes, as up to three sentences. Changes that many
3542/// tests share are mentioned once.
3543fn describe_effects(
3544    changes: &BTreeMap<String, BTreeSet<Change>>,
3545    sites: &BTreeMap<u32, (&str, &Site)>,
3546) -> Vec<String> {
3547    let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
3548    for (test, found) in changes {
3549        for change in found {
3550            by_change.entry(change).or_default().push(test);
3551        }
3552    }
3553    if by_change.is_empty() {
3554        return vec![
3555            "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs".to_string(),
3556        ];
3557    }
3558    let mut out = vec![];
3559    for (change, tests) in by_change.iter().take(3) {
3560        let Some((file, site)) = sites.get(&change.site()) else {
3561            continue;
3562        };
3563        let code = report::location(file, site).code;
3564        let at = format!("{file}:{}", site.line);
3565        let who = match tests[..] {
3566            ["?"] => "a test".to_string(),
3567            [one] => format!("`{one}`"),
3568            [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
3569            [] => continue,
3570        };
3571        out.push(match change {
3572            Change::Returns { value, .. } => {
3573                format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
3574            }
3575            Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
3576            Change::NoLongerRuns { .. } => {
3577                format!("with the mutant, {who} no longer runs `{code}` ({at})")
3578            }
3579            Change::NewOutcome { .. } => {
3580                format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
3581            }
3582        });
3583    }
3584    if by_change.len() > 3 {
3585        out.push(format!("(and {} more such changes)", by_change.len() - 3));
3586    }
3587    out
3588}
3589
3590#[cfg(test)]
3591mod tests {
3592    use super::*;
3593    use crate::trace::UNKNOWN_TEST;
3594
3595    #[test]
3596    fn test_build_scope_uses_only_known_local_features() {
3597        let package = Package {
3598            name: "pkg".to_owned(),
3599            dependencies: vec![],
3600            features: BTreeMap::from([
3601                ("default".to_owned(), vec!["alias".to_owned()]),
3602                (
3603                    "alias".to_owned(),
3604                    vec!["extra".to_owned(), "dep/extra".to_owned()],
3605                ),
3606                ("extra".to_owned(), vec![]),
3607                ("separate".to_owned(), vec![]),
3608            ]),
3609            manifest_path: PathBuf::from("workspace/pkg/Cargo.toml"),
3610            targets: vec![],
3611        };
3612        let enabled = |workspace: &str, features: &str, no_default_features, all_features| {
3613            package.enabled_local_features(
3614                Path::new(workspace),
3615                &CargoConfig {
3616                    features: vec![features.to_owned()],
3617                    no_default_features,
3618                    all_features,
3619                    locked: false,
3620                },
3621            )
3622        };
3623        let root = "workspace/pkg";
3624        assert_eq!(
3625            enabled(root, "", false, false),
3626            BTreeSet::from(["default", "alias", "extra"])
3627        );
3628        assert_eq!(
3629            enabled(root, "", true, true),
3630            BTreeSet::from(["default", "alias", "extra", "separate"])
3631        );
3632        assert_eq!(
3633            enabled(root, "alias, separate", true, false),
3634            BTreeSet::from(["alias", "extra", "separate"])
3635        );
3636        assert_eq!(
3637            enabled("workspace", "extra other/separate", true, false),
3638            BTreeSet::new()
3639        );
3640        assert_eq!(
3641            enabled("workspace", "pkg/extra other/separate", true, false),
3642            BTreeSet::from(["extra"])
3643        );
3644    }
3645
3646    #[test]
3647    fn test_build_scope_preserves_cargo_target_eligibility() {
3648        let target = |name, kind, test, required_features: &[&str]| {
3649            serde_json::from_value(serde_json::json!({
3650                "name": name, "kind": [kind], "test": test, "src_path": "ignored.rs",
3651                "required-features": required_features,
3652            }))
3653            .unwrap()
3654        };
3655        let package = |name: &str, targets| Package {
3656            name: name.to_owned(),
3657            dependencies: vec![],
3658            targets,
3659            manifest_path: PathBuf::new(),
3660            features: BTreeMap::from([("extra".to_owned(), vec![])]),
3661        };
3662        let first = package(
3663            "first",
3664            vec![
3665                target("first", "proc-macro", true, &[]),
3666                target("name", "bin", true, &[]),
3667                target("name", "example", true, &[]),
3668                target("name", "bench", true, &[]),
3669                target("name", "test", true, &[]),
3670                target("conditional", "test", true, &["extra"]),
3671                target("dependency_feature", "test", true, &["dep/extra"]),
3672                target("disabled", "test", false, &[]),
3673                target("glob[a]", "test", true, &[]),
3674                target("--leading-dash", "test", true, &[]),
3675                target("build-script-build", "custom-build", false, &[]),
3676            ],
3677        );
3678        let second = package(
3679            "second",
3680            vec![
3681                target("second", "staticlib", true, &[]),
3682                target("name", "test", false, &[]),
3683            ],
3684        );
3685        let flags = |packages: &[&Package], names: &[&str], all| {
3686            test_build_flags(
3687                packages,
3688                &names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
3689                Path::new("workspace"),
3690                &CargoConfig {
3691                    all_features: all,
3692                    ..CargoConfig::default()
3693                },
3694            )
3695        };
3696        assert_eq!(
3697            flags(&[&first], &["name", "first", "unknown"], false).unwrap(),
3698            [
3699                "--bench=name",
3700                "--bin=name",
3701                "--example=name",
3702                "--lib",
3703                "--test=name"
3704            ]
3705        );
3706        assert_eq!(flags(&[&first], &[], false), None);
3707        assert_eq!(flags(&[&first], &["unknown", "disabled"], false), None);
3708        assert_eq!(flags(&[&first], &["glob[a]"], false), None);
3709        assert_eq!(
3710            flags(&[&first], &["--leading-dash"], false).unwrap(),
3711            ["--test=--leading-dash"]
3712        );
3713        assert_eq!(flags(&[&first], &["name", "conditional"], false), None);
3714        assert_eq!(flags(&[&first], &["dependency_feature"], true), None);
3715        assert_eq!(
3716            flags(&[&first], &["conditional"], true).unwrap(),
3717            ["--test=conditional"]
3718        );
3719        assert_eq!(flags(&[&first, &second], &["name"], false), None);
3720        assert_eq!(flags(&[&first, &second], &["first"], false), None);
3721        assert_eq!(
3722            flags(&[&first, &second], &["first", "second"], false).unwrap(),
3723            ["--lib"]
3724        );
3725    }
3726
3727    #[test]
3728    fn parses_cargo_json_messages() {
3729        let stdout = concat!(
3730            r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
3731            "\n",
3732            r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
3733            "\n",
3734            r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
3735            "\n",
3736            r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
3737            "\n",
3738            r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
3739            "\n",
3740            r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
3741            "\n",
3742            r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
3743            "\n",
3744            "not json\n",
3745            r#"{"reason":"build-finished","success":false}"#,
3746            "\n",
3747        );
3748        let out = parse_build_output(stdout, &["p", "other"]);
3749        assert_eq!(
3750            out.test_binaries,
3751            [(
3752                "p".to_string(),
3753                PathBuf::from("/t/p-abc"),
3754                "p".to_string(),
3755                vec!["lib".to_string()]
3756            )]
3757        );
3758        // With several packages each binary is attributed to its own.
3759        let both = parse_build_output(stdout, &["dep", "p"]);
3760        let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
3761        assert_eq!(owners, ["p", "dep"]);
3762        assert_eq!(
3763            out.errors,
3764            [CompileError {
3765                primary: vec![ErrorSpan {
3766                    file: "src/lib.rs".into(),
3767                    byte_start: 40,
3768                    line: 3
3769                }],
3770                secondary: vec![ErrorSpan {
3771                    file: "src/lib.rs".into(),
3772                    byte_start: 2,
3773                    line: 1
3774                }],
3775                rendered: "E0308".into(),
3776            }]
3777        );
3778    }
3779
3780    #[test]
3781    fn package_ids_are_matched_by_name() {
3782        assert!(is_package(
3783            "path+file:///w/target/tmt/src#eligibility@0.0.0",
3784            "eligibility"
3785        ));
3786        assert!(is_package(
3787            "path+file:///w/eligibility#0.1.0",
3788            "eligibility"
3789        ));
3790        assert!(is_package(
3791            "eligibility 0.1.0 (path+file:///w)",
3792            "eligibility"
3793        ));
3794        assert!(!is_package(
3795            "path+file:///w/eligibility#other@0.1.0",
3796            "eligibility-core"
3797        ));
3798        assert!(!is_package(
3799            "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
3800            "eligibility"
3801        ));
3802    }
3803
3804    #[test]
3805    fn test_filter_falls_back_to_the_whole_binary() {
3806        let set = |names: &[&str]| {
3807            names
3808                .iter()
3809                .map(|n| n.to_string())
3810                .collect::<BTreeSet<String>>()
3811        };
3812        let known = set(&["tests::a", "tests::b", "tests::c"]);
3813        assert_eq!(
3814            test_filter(&set(&["tests::a", "tests::b"]), &known),
3815            Some(vec!["tests::a".to_string(), "tests::b".to_string()])
3816        );
3817        // Observed outside any test thread.
3818        assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
3819        // Observed on a thread the test named itself: not a test of this binary.
3820        assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
3821        assert_eq!(test_filter(&set(&["worker"]), &known), None);
3822
3823        let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
3824        assert_eq!(test_filter(&many, &many), None);
3825        let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
3826        assert!(test_filter(&limit, &limit).is_some());
3827    }
3828
3829    #[test]
3830    fn libtest_listing() {
3831        let listing =
3832            "tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
3833        assert_eq!(
3834            parse_test_list(listing).into_iter().collect::<Vec<_>>(),
3835            ["tests::a", "tests::nested::b"]
3836        );
3837    }
3838
3839    #[test]
3840    fn domains_from_type_bounds() {
3841        let u8s = crate::trace::TypeBounds {
3842            lhs: (0, 255),
3843            rhs: (0, 255),
3844        };
3845        assert_eq!(
3846            domain_of(LiteralSide::Rhs(18), Some(&u8s)),
3847            Some((-18, 237))
3848        );
3849        assert_eq!(
3850            domain_of(LiteralSide::Lhs(18), Some(&u8s)),
3851            Some((-237, 18))
3852        );
3853        assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
3854        assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
3855        let wide = crate::trace::TypeBounds {
3856            lhs: (i128::MIN, 0),
3857            rhs: (0, 0),
3858        };
3859        assert_eq!(
3860            domain_of(LiteralSide::Rhs(1), Some(&wide)),
3861            None,
3862            "overflow is not a domain"
3863        );
3864    }
3865
3866    #[test]
3867    fn out_of_line_module_locations() {
3868        let tests = instrument::TestModule {
3869            name: "tests".into(),
3870            path: None,
3871        };
3872        assert_eq!(
3873            module_paths(Path::new("src/lib.rs"), &tests),
3874            [PathBuf::from("src/tests.rs"), PathBuf::from("src/tests")]
3875        );
3876        assert_eq!(
3877            module_paths(Path::new("src/store.rs"), &tests),
3878            [
3879                PathBuf::from("src/store/tests.rs"),
3880                PathBuf::from("src/store/tests")
3881            ]
3882        );
3883        assert_eq!(
3884            module_paths(Path::new("src/store/mod.rs"), &tests),
3885            [
3886                PathBuf::from("src/store/tests.rs"),
3887                PathBuf::from("src/store/tests")
3888            ]
3889        );
3890        let with_path = instrument::TestModule {
3891            name: "rt".into(),
3892            path: Some("runtime/rt.rs".into()),
3893        };
3894        assert_eq!(
3895            module_paths(Path::new("src/lib.rs"), &with_path),
3896            [PathBuf::from("src/runtime/rt.rs")]
3897        );
3898    }
3899
3900    #[test]
3901    fn path_dependencies_outside_the_workspace_become_absolute() {
3902        let manifest = r#"[package]
3903name = "app"
3904
3905[dependencies]
3906serde = "1"
3907core = { path = "../core" }          # inside the workspace: kept
3908outside = { path = "../../outside", version = "1" }
3909
3910[dev-dependencies.helper]
3911path = "../../../far/helper"
3912
3913[target.'cfg(unix)'.dependencies]
3914unix-only = { path = "../../unix" }
3915
3916[patch.crates-io]
3917serde = { path = "../../serde-fork" }
3918"#;
3919        let out = absolutize_path_dependencies(
3920            manifest,
3921            Path::new("/w/ws/app"),
3922            Path::new("/w/ws"),
3923            Path::new("/copy"),
3924        )
3925        .unwrap()
3926        .expect("something to rewrite");
3927        assert!(
3928            out.contains(r#"core = { path = "../core" }          # inside the workspace: kept"#),
3929            "{out}"
3930        );
3931        assert!(
3932            out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
3933            "{out}"
3934        );
3935        assert!(out.contains("path = \"/far/helper\""), "{out}");
3936        assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
3937        assert!(
3938            out.contains(r#"serde = { path = "/w/serde-fork" }"#),
3939            "{out}"
3940        );
3941        assert!(out.contains("serde = \"1\""), "{out}");
3942
3943        let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
3944        assert_eq!(
3945            absolutize_path_dependencies(
3946                inside,
3947                Path::new("/w/ws/app"),
3948                Path::new("/w/ws"),
3949                Path::new("/copy")
3950            )
3951            .unwrap(),
3952            None
3953        );
3954        let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
3955        let out = absolutize_path_dependencies(
3956            ws,
3957            Path::new("/w/ws"),
3958            Path::new("/w/ws"),
3959            Path::new("/copy"),
3960        )
3961        .unwrap()
3962        .unwrap();
3963        assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
3964        assert!(
3965            absolutize_path_dependencies(
3966                "not [ toml",
3967                Path::new("/w"),
3968                Path::new("/w"),
3969                Path::new("/copy")
3970            )
3971            .is_err()
3972        );
3973        assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
3974        // An absolute path into the workspace has to follow the code into the copy.
3975        let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
3976        let out = absolutize_path_dependencies(
3977            absolute,
3978            Path::new("/w/ws/app"),
3979            Path::new("/w/ws"),
3980            Path::new("/copy"),
3981        )
3982        .unwrap()
3983        .unwrap();
3984        assert!(
3985            out.contains(r#"helper = { path = "/copy/helper" }"#),
3986            "{out}"
3987        );
3988    }
3989
3990    #[test]
3991    fn pool_runs_every_job_once_and_keeps_the_order() {
3992        use std::sync::atomic::{AtomicUsize, Ordering};
3993        for workers in [0, 1, 2, 3, 8, 100] {
3994            for count in [0, 1, 2, 7, 50] {
3995                let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
3996                let results = run_pool(count, workers, |i| {
3997                    calls[i].fetch_add(1, Ordering::SeqCst);
3998                    std::thread::yield_now();
3999                    Ok(i * 10)
4000                })
4001                .unwrap();
4002                assert_eq!(
4003                    results,
4004                    (0..count).map(|i| i * 10).collect::<Vec<_>>(),
4005                    "workers={workers}"
4006                );
4007                assert!(
4008                    calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
4009                    "workers={workers} count={count}"
4010                );
4011            }
4012        }
4013        let failed = run_pool(5, 3, |i| {
4014            if i == 3 {
4015                Err(anyhow!("job {i} broke"))
4016            } else {
4017                Ok(i)
4018            }
4019        });
4020        assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
4021    }
4022
4023    #[test]
4024    fn operand_ranges_ignore_wrapping_parentheses() {
4025        assert_eq!(core_range(10, "a > 0"), (10, 15));
4026        assert_eq!(core_range(10, "(a > 0)"), (11, 16));
4027        assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
4028        // Two groups, not one wrapper.
4029        assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
4030        assert_eq!(core_range(0, "f(a)"), (0, 4));
4031        assert_eq!(core_range(3, "()"), (4, 4));
4032        // Text that is not balanced is left as it is.
4033        assert_eq!(core_range(0, "(a"), (0, 2));
4034        assert_eq!(core_range(0, "a)"), (0, 2));
4035        assert_eq!(core_range(0, ")"), (0, 1));
4036    }
4037
4038    #[test]
4039    fn pool_never_uses_more_threads_than_asked() {
4040        for workers in [1, 2] {
4041            let seen = std::sync::Mutex::new(HashSet::new());
4042            run_pool(6, workers, |_| {
4043                seen.lock().unwrap().insert(std::thread::current().id());
4044                // Long enough for an idle extra thread to take the next job.
4045                std::thread::sleep(Duration::from_millis(30));
4046                Ok(())
4047            })
4048            .unwrap();
4049            assert_eq!(seen.lock().unwrap().len(), workers);
4050        }
4051    }
4052
4053    #[test]
4054    fn workspace_dependents() {
4055        let package = |name: &str, deps: &[&str]| Package {
4056            name: name.to_string(),
4057            features: BTreeMap::new(),
4058            dependencies: deps
4059                .iter()
4060                .map(|d| Dependency {
4061                    name: d.to_string(),
4062                })
4063                .collect(),
4064            manifest_path: PathBuf::new(),
4065            targets: vec![],
4066        };
4067        let packages = [
4068            package("core", &["serde"]),
4069            package("mid", &["core"]),
4070            package("app", &["mid", "other"]),
4071            package("other", &[]),
4072            package("cycle", &["app", "core"]),
4073        ];
4074        assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
4075        assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
4076        assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
4077        assert!(dependents_of("app", &packages) == ["cycle"]);
4078        assert!(dependents_of("nobody", &packages).is_empty());
4079        // A package is not its own dependent, whatever depends on what.
4080        let mutual = [package("x", &["y"]), package("y", &["x"])];
4081        assert_eq!(dependents_of("x", &mutual), ["y"]);
4082    }
4083
4084    #[test]
4085    fn failure_lines_of_libtest() {
4086        assert!(is_failure_line("test tests::a ... FAILED"));
4087        assert!(is_failure_line(
4088            "test src/lib.rs - double (line 3) ... FAILED"
4089        ));
4090        assert!(!is_failure_line("test tests::a ... ok"));
4091        assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
4092        assert!(!is_failure_line("my output says ... FAILED"));
4093        assert!(!is_failure_line(
4094            "test tests::a ... FAILED (but printed by the test)"
4095        ));
4096    }
4097
4098    #[test]
4099    fn effects_in_words() {
4100        let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
4101        let mut found = instrument::discover(source, 0).unwrap().sites;
4102        found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
4103        for (id, site) in found.iter_mut().enumerate() {
4104            site.id = id as u32;
4105        }
4106        let sites: BTreeMap<u32, (&str, &Site)> =
4107            found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
4108        let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
4109        assert_eq!(
4110            texts,
4111            ["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
4112        );
4113
4114        let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
4115        let mut changes = BTreeMap::new();
4116        changes.insert(
4117            "tests::a".to_string(),
4118            set(&[
4119                Change::Returns {
4120                    site: 0,
4121                    value: true,
4122                },
4123                Change::NowRuns { site: 1 },
4124            ]),
4125        );
4126        changes.insert(
4127            "tests::b".to_string(),
4128            set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
4129        );
4130        changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
4131        assert_eq!(
4132            describe_effects(&changes, &sites),
4133            [
4134                "with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
4135                "with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
4136                "with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
4137                "(and 1 more such changes)",
4138            ]
4139        );
4140        // What is not listed is counted.
4141        let mut many = BTreeMap::new();
4142        many.insert(
4143            "tests::a".to_string(),
4144            set(&[
4145                Change::NowRuns { site: 0 },
4146                Change::NowRuns { site: 1 },
4147                Change::NowRuns { site: 2 },
4148                Change::NoLongerRuns { site: 0 },
4149                Change::NoLongerRuns { site: 1 },
4150                Change::NoLongerRuns { site: 2 },
4151            ]),
4152        );
4153        assert_eq!(
4154            describe_effects(&many, &sites).last().map(String::as_str),
4155            Some("(and 3 more such changes)")
4156        );
4157        // Up to three changes are all listed, with nothing after them.
4158        let mut few = BTreeMap::new();
4159        few.insert(
4160            "tests::a".to_string(),
4161            set(&[
4162                Change::NowRuns { site: 1 },
4163                Change::NewOutcome { site: 2 },
4164                Change::Returns {
4165                    site: 0,
4166                    value: false,
4167                },
4168            ]),
4169        );
4170        assert_eq!(
4171            describe_effects(&few, &sites),
4172            [
4173                "with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
4174                "with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
4175                "with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
4176            ]
4177        );
4178        assert_eq!(
4179            describe_effects(&BTreeMap::new(), &sites),
4180            [
4181                "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs"
4182            ]
4183        );
4184    }
4185
4186    #[test]
4187    fn mutant_timeout_scales_with_the_baseline() {
4188        assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
4189        assert_eq!(
4190            mutant_timeout(Duration::from_secs(2)),
4191            Duration::from_secs(15)
4192        );
4193    }
4194    /// A scratch directory of its own for one test.
4195    fn scratch(name: &str) -> PathBuf {
4196        let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
4197        let _ = fs::remove_dir_all(&dir);
4198        fs::create_dir_all(dir.join("ws/src")).unwrap();
4199        fs::create_dir_all(dir.join("work/src")).unwrap();
4200        dir.canonicalize().unwrap()
4201    }
4202
4203    #[cfg(unix)]
4204    #[test]
4205    fn a_descendant_cannot_keep_the_completed_runner_output_open() {
4206        use std::os::unix::fs::PermissionsExt as _;
4207
4208        let dir = scratch("descendant-output");
4209        let work = dir.join("work");
4210        let exe = work.join("runner");
4211        fs::write(&exe, "#!/bin/sh\nsleep 8 &\nexit 0\n").unwrap();
4212        fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
4213        let bin = TestBinary {
4214            name: "runner".into(),
4215            cwd: work.join("src"),
4216            marks: marks_dir(&work).unwrap(),
4217            git_ceiling: work,
4218            tests: BTreeSet::new(),
4219            runner: Runner::Exe(exe),
4220            baseline: Duration::ZERO,
4221            traced: Duration::ZERO,
4222            trace: Trace::default(),
4223        };
4224        let started = Instant::now();
4225        assert_eq!(
4226            run_binary(
4227                &bin,
4228                None,
4229                &[],
4230                Duration::from_secs(2),
4231                RunOutput::FirstFailure,
4232                1
4233            )
4234            .unwrap(),
4235            Outcome::Pass
4236        );
4237        assert!(
4238            started.elapsed() < Duration::from_secs(6),
4239            "a descendant held the output pipe open"
4240        );
4241        fs::remove_dir_all(dir).unwrap();
4242    }
4243
4244    #[cfg(unix)]
4245    #[test]
4246    fn a_detached_descendant_does_not_hold_the_runner_open() {
4247        let dir = scratch("detached-output");
4248        let work = dir.join("work");
4249        let source = work.join("runner.rs");
4250        let exe = work.join("runner");
4251        fs::write(
4252            &source,
4253            r#"
4254use std::os::unix::process::CommandExt;
4255fn main() {
4256    let child = std::process::Command::new("sleep").arg("8").process_group(0).spawn().unwrap();
4257    std::fs::write("child.pid", child.id().to_string()).unwrap();
4258}
4259"#,
4260        )
4261        .unwrap();
4262        let output = Command::new("rustc")
4263            .arg(&source)
4264            .arg("-o")
4265            .arg(&exe)
4266            .output()
4267            .unwrap();
4268        assert!(
4269            output.status.success(),
4270            "{}",
4271            String::from_utf8_lossy(&output.stderr)
4272        );
4273        let bin = TestBinary {
4274            name: "runner".into(),
4275            cwd: work.join("src"),
4276            marks: marks_dir(&work).unwrap(),
4277            git_ceiling: work,
4278            tests: BTreeSet::new(),
4279            runner: Runner::Exe(exe),
4280            baseline: Duration::ZERO,
4281            traced: Duration::ZERO,
4282            trace: Trace::default(),
4283        };
4284        let started = Instant::now();
4285        let outcome = run_binary(
4286            &bin,
4287            None,
4288            &[],
4289            Duration::from_secs(2),
4290            RunOutput::FirstFailure,
4291            1,
4292        );
4293        let elapsed = started.elapsed();
4294        // This test alone owns the separate child group.
4295        let pid = fs::read_to_string(bin.cwd.join("child.pid"))
4296            .unwrap()
4297            .parse()
4298            .unwrap();
4299        kill_test_group(pid);
4300        fs::remove_dir_all(dir).unwrap();
4301        assert_eq!(outcome.unwrap(), Outcome::Pass);
4302        assert!(
4303            elapsed < Duration::from_secs(6),
4304            "a detached descendant held the output pipe open"
4305        );
4306    }
4307
4308    fn set_modified(path: &Path, time: std::time::SystemTime) {
4309        fs::File::options()
4310            .write(true)
4311            .open(path)
4312            .unwrap()
4313            .set_modified(time)
4314            .unwrap();
4315    }
4316
4317    fn modified(path: &Path) -> std::time::SystemTime {
4318        fs::metadata(path).unwrap().modified().unwrap()
4319    }
4320
4321    /// What a run does to the working copy up to the build. `write` stands for the
4322    /// instrumentation of the files in `selected`.
4323    fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
4324        let (workspace, work) = (dir.join("ws"), dir.join("work"));
4325        let copy = work.join("src");
4326        let state = WorkCopy::open(&work, &copy);
4327        copy_tree(&workspace, &copy, &workspace, &|_| false, &state).unwrap();
4328        prune(&copy, &state).unwrap();
4329        for name in selected {
4330            let path = copy.join(name);
4331            let original = state.original(&path, &workspace).unwrap().unwrap();
4332            assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
4333            if write {
4334                state
4335                    .write(&path, &format!("instrumented {original}"))
4336                    .unwrap();
4337            } else {
4338                state.record(&path).unwrap(); // interrupted before the write
4339            }
4340        }
4341        if write {
4342            state.settle(&workspace).unwrap();
4343        }
4344        state
4345    }
4346
4347    /// Rows generated by `pict formal/pict/workcopy.pict /o:3 /e:formal/pict/workcopy.seed.tsv`.
4348    #[test]
4349    fn work_copy_table() {
4350        let table = include_str!("../tests/data/workcopy.pict.tsv");
4351        let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
4352        let mut rows = 0;
4353        for (index, line) in table.lines().skip(1).enumerate() {
4354            let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
4355                panic!("bad row: {line}");
4356            };
4357            let dir = scratch(&format!("copy-table-{index}"));
4358            let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
4359            let log = dir.join("work").join(WRITTEN_LOG);
4360            fs::write(&file, "v1").unwrap();
4361            set_modified(&file, hour_ago);
4362            match earlier {
4363                "none" => {}
4364                "plain" => drop(copy_run(&dir, &[], true)),
4365                "written" => drop(copy_run(&dir, &["src/a.rs"], true)),
4366                "logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
4367                _ => panic!("{line}"),
4368            }
4369            if copied.exists() {
4370                set_modified(&copied, hour_ago);
4371            }
4372            let before = fs::read_to_string(&copied).ok();
4373            match source {
4374                "same" => {}
4375                "edited" => fs::write(&file, "version 2").unwrap(),
4376                "deleted" => fs::remove_file(&file).unwrap(),
4377                _ => panic!("{line}"),
4378            }
4379            let selected = selected == "yes";
4380            copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
4381
4382            let wanted = match (source, selected) {
4383                ("deleted", _) => None,
4384                ("same", true) => Some("instrumented v1".to_string()),
4385                ("same", false) => Some("v1".to_string()),
4386                (_, true) => Some("instrumented version 2".to_string()),
4387                (_, false) => Some("version 2".to_string()),
4388            };
4389            assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
4390            assert_eq!(
4391                fs::read_to_string(&log).unwrap_or_default(),
4392                if selected { "src/a.rs\n" } else { "" },
4393                "{line}"
4394            );
4395            // What did not change was not written again, apart from the copy an
4396            // interrupted run left under a log entry.
4397            if before == wanted && wanted.is_some() && earlier != "logged_only" {
4398                assert_eq!(modified(&copied), hour_ago, "{line}");
4399            }
4400            // What did change looks new to cargo, although its source is an hour old:
4401            // a copy that kept the time of its source would not be rebuilt.
4402            if before != wanted && wanted.is_some() {
4403                assert!(
4404                    modified(&copied) > hour_ago + Duration::from_secs(1800),
4405                    "{line}"
4406                );
4407            }
4408            // A further run that instruments nothing leaves a plain copy.
4409            copy_run(&dir, &[], true);
4410            assert_eq!(
4411                fs::read_to_string(&copied).ok(),
4412                fs::read_to_string(&file).ok(),
4413                "{line}"
4414            );
4415            assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
4416            fs::remove_dir_all(&dir).unwrap();
4417            rows += 1;
4418        }
4419        assert_eq!(rows, 20);
4420    }
4421
4422    #[test]
4423    fn work_copy_keeps_modification_times() {
4424        let dir = scratch("copy-times");
4425        let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
4426        let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
4427        for name in names {
4428            fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
4429            set_modified(&dir.join("ws").join(name), hour_ago);
4430        }
4431        let copy = dir.join("work/src");
4432        let runtime = copy.join("src/__tmt_rt.rs");
4433        let run = || {
4434            let state = copy_run(&dir, &[], false);
4435            for name in ["src/lib.rs", "src/edited.rs"] {
4436                let original = state.original(&copy.join(name), &dir.join("ws")).unwrap();
4437                state
4438                    .write(&copy.join(name), &format!("probe {}", original.unwrap()))
4439                    .unwrap();
4440            }
4441            // A file of the tool's own, with no source: not taken for one to instrument.
4442            assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
4443                if runtime.exists() { Some(None) } else { None }
4444            });
4445            state.write(&runtime, "runtime").unwrap();
4446            state.settle(&dir.join("ws")).unwrap();
4447        };
4448        run();
4449        for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
4450            set_modified(&name, hour_ago);
4451        }
4452        fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
4453        run();
4454        // Nothing but the edited file was touched: cargo has one file to look at.
4455        for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
4456            assert_eq!(modified(&copy.join(name)), hour_ago, "{name}");
4457        }
4458        assert_ne!(modified(&copy.join("src/edited.rs")), hour_ago);
4459        assert_eq!(
4460            fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
4461            "probe // edited since"
4462        );
4463        assert_eq!(
4464            fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
4465            "probe // src/lib.rs"
4466        );
4467        assert_eq!(
4468            fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
4469            "src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
4470        );
4471        // A source that was only touched is still what the copy holds: nothing to do.
4472        let later = hour_ago + Duration::from_secs(60);
4473        set_modified(&dir.join("ws/src/plain.rs"), later);
4474        run();
4475        assert_eq!(modified(&copy.join("src/plain.rs")), hour_ago);
4476        // Other bytes are copied, also where the size and the time of the source say
4477        // nothing (a file put back as it was long ago).
4478        let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
4479        fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
4480        set_modified(
4481            &dir.join("ws/src/plain.rs"),
4482            hour_ago - Duration::from_secs(60),
4483        );
4484        run();
4485        assert_eq!(
4486            fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
4487            plain.to_uppercase()
4488        );
4489        assert!(modified(&copy.join("src/plain.rs")) > later);
4490        fs::remove_dir_all(&dir).unwrap();
4491    }
4492
4493    #[test]
4494    fn work_copy_log_is_not_trusted() {
4495        let dir = scratch("copy-log");
4496        let (workspace, work) = (dir.join("ws"), dir.join("work"));
4497        let copy = work.join("src");
4498        let outside = dir.join("outside.txt");
4499        fs::write(&outside, "keep").unwrap();
4500        fs::write(workspace.join("src/a.rs"), "a").unwrap();
4501        // Entries that leave the copy are not entries.
4502        fs::write(
4503            work.join(WRITTEN_LOG),
4504            format!(
4505                "../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
4506                outside.display()
4507            ),
4508        )
4509        .unwrap();
4510        let state = WorkCopy::open(&work, &copy);
4511        assert_eq!(
4512            state.earlier,
4513            [copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
4514        );
4515        copy_tree(&workspace, &copy, &workspace, &|_| false, &state).unwrap();
4516        state.settle(&workspace).unwrap();
4517        assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
4518        assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
4519
4520        // Nothing is written outside the copy, and a name that would break the log is refused.
4521        let state = WorkCopy::open(&work, &copy);
4522        assert!(state.write(&outside, "x").is_err());
4523        assert!(state.write(&copy.join("src/a\nb.rs"), "x").is_err());
4524        assert!(!copy.join("src/a\nb.rs").exists());
4525        assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
4526        fs::remove_dir_all(&dir).unwrap();
4527    }
4528    #[test]
4529    fn work_copy_log_follows_every_write() {
4530        let dir = scratch("copy-log-order");
4531        let (workspace, work) = (dir.join("ws"), dir.join("work"));
4532        let copy = work.join("src");
4533        let log = work.join(WRITTEN_LOG);
4534        let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
4535        for name in &names {
4536            fs::write(workspace.join(name), "x").unwrap();
4537        }
4538        let state = copy_run(&dir, &[], false);
4539        // The entry is there before the file changes, once.
4540        state.record(&copy.join(&names[0])).unwrap();
4541        state.record(&copy.join(&names[0])).unwrap();
4542        assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
4543        assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
4544        for name in &names {
4545            state.write(&copy.join(name), "probe").unwrap();
4546        }
4547        state.settle(&workspace).unwrap();
4548        let mut sorted = names.to_vec();
4549        sorted.sort();
4550        assert_eq!(
4551            fs::read_to_string(&log).unwrap(),
4552            sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
4553        );
4554
4555        // After the log was trimmed, a later write is logged again.
4556        let state = copy_run(&dir, &[], false);
4557        state.settle(&workspace).unwrap();
4558        assert_eq!(fs::read_to_string(&log).unwrap(), "");
4559        state.write(&copy.join(&names[3]), "probe").unwrap();
4560        assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
4561        fs::remove_dir_all(&dir).unwrap();
4562    }
4563
4564    #[test]
4565    fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
4566        let dir = scratch("copy-sync");
4567        let (workspace, work) = (dir.join("ws"), dir.join("work"));
4568        let copy = work.join("src");
4569        let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
4570        for name in [
4571            "same",
4572            "longer",
4573            "newer",
4574            "was_dir",
4575            "was_link",
4576            "short_link",
4577            "twin_link",
4578            "shorter",
4579        ] {
4580            fs::write(workspace.join("src").join(name), "source").unwrap();
4581            set_modified(&workspace.join("src").join(name), hour_ago);
4582        }
4583        // A file that cannot be written to is copied like any other.
4584        let locked = workspace.join("src/locked");
4585        fs::write(&locked, "read only").unwrap();
4586        let mut permissions = fs::metadata(&locked).unwrap().permissions();
4587        permissions.set_readonly(true);
4588        fs::set_permissions(&locked, permissions).unwrap();
4589        fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
4590        // The same size and newer, and not the same: no copy of the source.
4591        fs::write(copy.join("src/same"), "SOURCE").unwrap();
4592        // A copy is one whatever its time says, and keeps that time (nothing to rebuild).
4593        fs::write(workspace.join("src/copied"), "as it is").unwrap();
4594        fs::write(copy.join("src/copied"), "as it is").unwrap();
4595        let long_ago = hour_ago - Duration::from_secs(7200);
4596        set_modified(&copy.join("src/copied"), long_ago);
4597        // A directory of the copy that has become a link is not walked into.
4598        let elsewhere = dir.join("elsewhere");
4599        fs::create_dir_all(&elsewhere).unwrap();
4600        std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
4601        fs::create_dir_all(workspace.join("linked/deep")).unwrap();
4602        fs::write(workspace.join("linked/deep/z"), "z").unwrap();
4603        fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
4604        fs::write(copy.join("src/newer"), "SOURCE").unwrap();
4605        set_modified(&copy.join("src/newer"), hour_ago - Duration::from_secs(60));
4606        // A link in the copy is replaced, not written through.
4607        let outside = dir.join("outside");
4608        fs::write(&outside, "keep").unwrap();
4609        std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
4610        // Not even one to a file that holds what the source holds.
4611        let twin = dir.join("twin");
4612        fs::write(&twin, "source").unwrap();
4613        std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
4614        // The beginning of the source is not the source.
4615        fs::write(copy.join("src/shorter"), "sour").unwrap();
4616        // Not even one whose own size and time would pass for the file's.
4617        std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
4618        // What the run does not want goes, with the directories it leaves empty.
4619        fs::create_dir_all(copy.join("old/deep")).unwrap();
4620        fs::write(copy.join("old/deep/x"), "x").unwrap();
4621        fs::create_dir_all(workspace.join("keep/deep")).unwrap();
4622        fs::write(workspace.join("keep/deep/y"), "y").unwrap();
4623
4624        copy_run(&dir, &[], true);
4625        let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
4626        assert_eq!(read("src/locked"), "read only");
4627        assert_eq!(read("src/copied"), "as it is");
4628        assert_eq!(
4629            fs::metadata(copy.join("src/copied"))
4630                .unwrap()
4631                .modified()
4632                .unwrap(),
4633            long_ago
4634        );
4635        assert_eq!(read("linked/deep/z"), "z");
4636        assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
4637        assert_eq!(
4638            fs::read_dir(&elsewhere).unwrap().count(),
4639            0,
4640            "nothing written through"
4641        );
4642        for name in [
4643            "src/same",
4644            "src/longer",
4645            "src/newer",
4646            "src/was_dir",
4647            "src/was_link",
4648            "src/short_link",
4649            "src/twin_link",
4650            "src/shorter",
4651        ] {
4652            assert_eq!(read(name), "source", "{name}");
4653            assert!(
4654                fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
4655                "{name}"
4656            );
4657        }
4658        assert!(
4659            fs::symlink_metadata(copy.join("src/was_link"))
4660                .unwrap()
4661                .is_file()
4662        );
4663        assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
4664        assert!(!copy.join("old").exists());
4665        assert_eq!(read("keep/deep/y"), "y");
4666        fs::remove_dir_all(&dir).unwrap();
4667    }
4668    #[test]
4669    fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
4670        let source = "impl S {\n    fn f(a: u8, b: u8) -> u8 {\n        let x = if a > b { 1 } else { 0 };\n        let y = if a > b { 2 } else { 0 };\n        x + y\n    }\n}\nfn g(a: u8, b: u8) -> bool {\n    a > b\n}\n";
4671        let found = instrument::discover(source, 0).unwrap();
4672        let all: Vec<(usize, usize, String)> = found
4673            .sites
4674            .iter()
4675            .map(|site| {
4676                let at = report::location("", site);
4677                (at.line, at.column, at.code)
4678            })
4679            .collect();
4680        let places = [FilePlaces {
4681            display: "src/lib.rs",
4682            source,
4683            places: &all,
4684        }];
4685        let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
4686            at: report::Location {
4687                file: file.to_string(),
4688                line,
4689                column,
4690                code: "a > b".to_string(),
4691                ..report::Location::default()
4692            },
4693            survivors: vec![],
4694            survivor_count: 0,
4695            add_tests: vec![],
4696            observed: None,
4697            verified: true,
4698        };
4699        let name = |finding: &Finding| {
4700            let at = finding.at();
4701            (at.item.clone(), at.id.clone())
4702        };
4703        // Only the second of the two in `f` is a finding: it is still the second.
4704        let mut findings = [
4705            gap(4, 20, "src/lib.rs"),
4706            gap(9, 5, "src/lib.rs"),
4707            gap(9, 5, "src/other.rs"),
4708        ];
4709        name_findings(&mut findings, &places);
4710        assert_eq!(
4711            name(&findings[0]),
4712            (
4713                "S::f".to_string(),
4714                "input_gap|src/lib.rs|S::f|a > b|1".to_string()
4715            )
4716        );
4717        assert_eq!(
4718            name(&findings[1]),
4719            (
4720                "g".to_string(),
4721                "input_gap|src/lib.rs|g|a > b|0".to_string()
4722            )
4723        );
4724        // A finding of a file that is not among the given ones is left without a name.
4725        assert_eq!(name(&findings[2]), (String::new(), String::new()));
4726    }
4727
4728    #[test]
4729    fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
4730        assert_eq!(spread(0, 3), Vec::<usize>::new());
4731        assert_eq!(spread(5, 0), Vec::<usize>::new());
4732        assert_eq!(spread(3, 3), [0, 1, 2]);
4733        assert_eq!(spread(3, 10), [0, 1, 2]);
4734        assert_eq!(spread(10, 1), [0]);
4735        assert_eq!(spread(10, 3), [0, 3, 6]);
4736        assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
4737        assert_eq!(spread(4, 3), [0, 1, 2]);
4738        assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
4739    }
4740
4741    #[test]
4742    fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
4743        // The runtime and the driver have to mean the same status.
4744        // The runtime ends a run it gives up as a failed one: the mark says which it was.
4745        assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
4746        let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
4747                      go(); \
4748                      let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
4749                      for _ in a..b {} for _ in a..=b {} \
4750                      O { on: x, ..base } }";
4751        let found = instrument::discover(source, 0).unwrap().sites;
4752        let mut seen = BTreeSet::new();
4753        for site in &found {
4754            for mutant in instrument::source_mutants(site) {
4755                let kind = format!("{:?}", site.kind);
4756                let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
4757                seen.insert((
4758                    kind,
4759                    mutant.into.clone(),
4760                    format!("{:?}", mutation_of(site, &mutant)),
4761                ));
4762            }
4763        }
4764        let expected = [
4765            ("Arith", "*", "ArithSwap2"),
4766            ("Arith", "-", "ArithSwap"),
4767            ("Arm", "Some(n) if n > 1", "Delete"),
4768            ("Body", "Default::default()", "Delete"),
4769            ("Cmp", "<", "Op(Lt)"),
4770            ("Cmp", "<=", "Op(Le)"),
4771            ("Cmp", "==", "Op(Eq)"),
4772            ("Cmp", ">", "Op(Gt)"),
4773            ("Cmp", ">=", "Op(Ge)"),
4774            ("Field", "on", "Delete"),
4775            ("Guard", "true", "Const(true)"),
4776            ("Logic", "&&", "LogicSwap"),
4777            ("Logic", "||", "LogicSwap"),
4778            ("Neg", "", "Delete"),
4779            ("Not", "", "DropNot"),
4780            ("Range", "..", "RangeEnd"),
4781            ("Range", "..=", "RangeEnd"),
4782        ];
4783        // A comparison is planned in other words than it is written in: the mutations
4784        // that are the same change, as an audit looks for them.
4785        let like = |source: &str, into: &str| -> Vec<Mutation> {
4786            let sites = instrument::discover(source, 0).unwrap().sites;
4787            let site = sites
4788                .iter()
4789                .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
4790                .unwrap();
4791            let mutant = instrument::source_mutants(site)
4792                .into_iter()
4793                .find(|mutant| mutant.into == into)
4794                .unwrap();
4795            mutations_like(site, &mutant, true)
4796        };
4797        use plan::CmpOp::*;
4798        for (op, into, expected) in [
4799            ("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
4800            ("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
4801            ("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
4802            (">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
4803            ("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
4804            (">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
4805            ("<", "==", vec![Mutation::Op(Eq)]),
4806            ("<", ">", vec![Mutation::Op(Gt)]),
4807            (">", "==", vec![Mutation::Op(Eq)]),
4808            (">", "<", vec![Mutation::Op(Lt)]),
4809        ] {
4810            let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
4811            assert_eq!(like(&source, into), expected, "{op} as {into}");
4812        }
4813        // Where the tests gave operands without an order, the negation of `>=` is not
4814        // `<`: only the operator itself is the same change. `!=` is still the negation.
4815        let unordered = |op: &str, into: &str| -> Vec<Mutation> {
4816            let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
4817            let sites = instrument::discover(&source, 0).unwrap().sites;
4818            let site = sites
4819                .iter()
4820                .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
4821                .unwrap();
4822            let mutant = instrument::source_mutants(site)
4823                .into_iter()
4824                .find(|mutant| mutant.into == into)
4825                .unwrap();
4826            mutations_like(site, &mutant, false)
4827        };
4828        assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
4829        assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
4830        assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
4831        // The moved bound is the operator it is taken for, at every distance.
4832        for d in -3..=3 {
4833            assert_eq!(
4834                plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
4835                Le.eval_d(d)
4836            );
4837            assert_eq!(
4838                plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
4839                Ge.eval_d(d)
4840            );
4841        }
4842        let seen: Vec<(&str, &str, &str)> = seen
4843            .iter()
4844            .map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
4845            .collect();
4846        assert_eq!(seen, expected);
4847    }
4848
4849    #[test]
4850    fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
4851        let dir = scratch("unable-mark");
4852        fs::create_dir_all(&dir).unwrap();
4853        let runs = std::sync::atomic::AtomicUsize::new(0);
4854        let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
4855        // A file of the name that would be next belongs to someone: it is not emptied,
4856        // and the mark gets another name.
4857        fs::write(name(0), "not ours").unwrap();
4858        fs::write(name(1), "nor this").unwrap();
4859        let mark = reserve_mark(&dir, &runs).unwrap();
4860        assert_eq!(mark, name(2));
4861        assert!(mark.is_absolute());
4862        assert_eq!(fs::read_to_string(&mark).unwrap(), "");
4863        assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
4864        assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
4865        // Still there after the run: the run went to its end, and the mark is taken away.
4866        assert!(!release_mark(&mark).unwrap());
4867        assert!(!mark.exists());
4868        // Gone: the run gave up.
4869        let mark = reserve_mark(&dir, &runs).unwrap();
4870        assert_eq!(mark, name(3));
4871        fs::remove_file(&mark).unwrap();
4872        assert!(release_mark(&mark).unwrap());
4873        // There, and not to be taken away (a directory is not a file to remove): neither
4874        // of the two, and said as an error. Whoever runs the tests, with whatever rights.
4875        let in_the_way = dir.join("a-directory");
4876        fs::create_dir_all(&in_the_way).unwrap();
4877        let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
4878        assert!(refused.contains("cannot tell whether"), "{refused}");
4879        assert!(refused.contains("a-directory"), "{refused}");
4880        assert!(in_the_way.is_dir());
4881        // A mark cannot be made in what is no directory, and that is not tried for ever.
4882        let unmade = format!("{:#}", reserve_mark(&name(0), &runs).unwrap_err());
4883        assert!(unmade.contains("creating"), "{unmade}");
4884        assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
4885        fs::remove_dir_all(&dir).unwrap();
4886    }
4887
4888    #[test]
4889    fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
4890        let dir = scratch("marks-dir");
4891        let work = dir.join("work");
4892        // Not there: made. There as a directory, with whatever is in it: used.
4893        assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
4894        assert!(work.join("marks").is_dir());
4895        fs::write(work.join("marks/left-over"), "x").unwrap();
4896        assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
4897        assert_eq!(
4898            fs::read_to_string(work.join("marks/left-over")).unwrap(),
4899            "x"
4900        );
4901        // A file of that name is somebody's: it stays, and the run does not start.
4902        let taken = dir.join("taken");
4903        fs::create_dir_all(&taken).unwrap();
4904        fs::write(taken.join("marks"), "grades of the class").unwrap();
4905        let said = format!("{:#}", marks_dir(&taken).unwrap_err());
4906        assert!(
4907            said.contains("is in the way") && said.contains("marks"),
4908            "{said}"
4909        );
4910        assert_eq!(
4911            fs::read_to_string(taken.join("marks")).unwrap(),
4912            "grades of the class"
4913        );
4914        // So is a link, whatever it points to: neither followed nor removed.
4915        #[cfg(unix)]
4916        {
4917            let linked = dir.join("linked");
4918            let elsewhere = dir.join("elsewhere");
4919            fs::create_dir_all(&linked).unwrap();
4920            fs::create_dir_all(&elsewhere).unwrap();
4921            std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
4922            assert!(marks_dir(&linked).is_err());
4923            assert!(
4924                fs::symlink_metadata(linked.join("marks"))
4925                    .unwrap()
4926                    .is_symlink()
4927            );
4928            assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
4929        }
4930        fs::remove_dir_all(&dir).unwrap();
4931    }
4932
4933    #[test]
4934    fn concurrent_runs_share_the_cores() {
4935        // Alone a binary has them all; four at a time have a quarter each.
4936        assert_eq!(test_threads(16, 1), 16);
4937        assert_eq!(test_threads(16, 4), 4);
4938        assert_eq!(test_threads(18, 4), 4);
4939        // Never fewer than two: a single thread is the main thread, without a name.
4940        assert_eq!(test_threads(16, 8), 2);
4941        assert_eq!(test_threads(16, 9), 2);
4942        assert_eq!(test_threads(4, 16), 2);
4943        assert_eq!(test_threads(1, 1), 2);
4944        assert_eq!(test_threads(8, 0), 8);
4945    }
4946
4947    #[test]
4948    fn cargo_is_told_the_same_everywhere() {
4949        assert!(CargoConfig::default().flags().is_empty());
4950        let some = CargoConfig {
4951            features: vec!["a".to_string(), "dep/b".to_string()],
4952            no_default_features: true,
4953            ..CargoConfig::default()
4954        };
4955        assert_eq!(
4956            some.flags(),
4957            ["--features", "a,dep/b", "--no-default-features"]
4958        );
4959        let all = CargoConfig {
4960            all_features: true,
4961            locked: true,
4962            ..CargoConfig::default()
4963        };
4964        assert_eq!(all.flags(), ["--all-features", "--locked"]);
4965    }
4966
4967    #[test]
4968    fn source_mutants_are_described_like_the_others() {
4969        let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
4970                      match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
4971        let found = instrument::discover(source, 0).unwrap().sites;
4972        let described: Vec<String> = found
4973            .iter()
4974            .flat_map(|site| {
4975                instrument::source_mutants(site)
4976                    .into_iter()
4977                    .map(|mutant| report::describe(site, mutation_of(site, &mutant)))
4978            })
4979            .collect();
4980        assert_eq!(
4981            described,
4982            [
4983                "the body of `f` replaced by `true`",
4984                "the body of `f` replaced by `false`",
4985                // The arm can be removed, which is its guard being `false`.
4986                "remove the arm `Some(n) if n > 1 => ..`",
4987                "the guard `n > 1` replaced by `true`",
4988                "`n == 1`",
4989                "`n < 1`",
4990                "`n >= 1`",
4991                "`!(a < b) && a + b == 0`",
4992                "`(a < b)`",
4993                "`a == b`",
4994                "`a > b`",
4995                "`a <= b`",
4996                "`a + b != 0`",
4997                "`a - b`",
4998                "`a * b`",
4999                "`-a * b == 1`",
5000                "`-a * b < 1`",
5001                "`-a * b >= 1`",
5002                "`-a / b`",
5003                "`-a + b`",
5004                "`a`",
5005            ]
5006        );
5007        // Without a catch-all arm the guard can be `false` in its own right.
5008        let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
5009        let found = instrument::discover(source, 0).unwrap().sites;
5010        let guard = found
5011            .iter()
5012            .find(|s| matches!(s.kind, SiteKind::Guard { .. }))
5013            .unwrap();
5014        let described: Vec<String> = instrument::source_mutants(guard)
5015            .iter()
5016            .map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
5017            .collect();
5018        assert_eq!(
5019            described,
5020            [
5021                "the guard `n > 1` replaced by `true`",
5022                "the guard `n > 1` replaced by `false`"
5023            ]
5024        );
5025    }
5026}