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