targeted-mutation 0.7.0

Targeted mutation testing for Rust: find the wrong implementations your tests let through
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Cargo metadata, JSON build output parsing, dependency tracking, and built-source reachability.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result, bail};
use serde::Deserialize;

use crate::instrument::{self};
use crate::reverts;

use super::*;

#[derive(Deserialize)]
pub(super) struct Metadata {
    pub(super) packages: Vec<Package>,
    pub(super) workspace_root: PathBuf,
    pub(super) target_directory: PathBuf,
}

#[derive(Deserialize)]
pub(super) struct Package {
    pub(super) name: String,
    #[serde(default)]
    pub(super) dependencies: Vec<Dependency>,
    pub(super) features: BTreeMap<String, Vec<String>>,
    pub(super) manifest_path: PathBuf,
    pub(super) targets: Vec<Target>,
}

impl Package {
    /// Only count features we can establish without resolving the dependency graph.
    pub(super) fn enabled_local_features(
        &self,
        workspace: &Path,
        cargo: &CargoConfig,
    ) -> BTreeSet<&str> {
        if cargo.all_features {
            return self.features.keys().map(String::as_str).collect();
        }
        let mut pending = Vec::new();
        if !cargo.no_default_features {
            pending.push("default");
        }
        // With resolver 1, unqualified CLI features only apply to the current package.
        let at_workspace_root = self.manifest_path.parent() == Some(workspace);
        for feature in cargo
            .features
            .iter()
            .flat_map(|features| features.split(|c: char| c == ',' || c.is_whitespace()))
        {
            match feature.split_once('/') {
                Some((package, name)) if package == self.name => pending.push(name),
                None if at_workspace_root => pending.push(feature),
                _ => {}
            }
        }
        let mut enabled = BTreeSet::new();
        while let Some(feature) = pending.pop() {
            if let Some((name, activates)) = self.features.get_key_value(feature)
                && enabled.insert(name.as_str())
            {
                pending.extend(activates.iter().map(String::as_str));
            }
        }
        enabled
    }
}

#[derive(Deserialize)]
pub(super) struct Dependency {
    pub(super) name: String,
}

#[derive(Deserialize)]
pub(super) struct Target {
    pub(super) name: String,
    pub(super) kind: Vec<String>,
    pub(super) src_path: PathBuf,
    pub(super) test: bool,
    #[serde(default)]
    pub(super) doctest: bool,
    #[serde(default, rename = "required-features")]
    pub(super) required_features: Vec<String>,
}

impl Target {
    pub(super) fn is_production(&self) -> bool {
        matches!(self.test_build_arg(), Some(("--lib" | "--bin", _)))
    }

    /// The Cargo selector and its optional name. `--lib` selects every package's library.
    pub(super) fn test_build_arg(&self) -> Option<(&'static str, Option<&str>)> {
        match self.kind.first()?.as_str() {
            "lib" | "rlib" | "cdylib" | "dylib" | "staticlib" | "proc-macro" => {
                Some(("--lib", None))
            }
            "bin" => Some(("--bin", Some(&self.name))),
            "example" => Some(("--example", Some(&self.name))),
            "test" => Some(("--test", Some(&self.name))),
            "bench" => Some(("--bench", Some(&self.name))),
            _ => None,
        }
    }
}

/// Select only test targets that Cargo's flags can express without broadening the selection.
pub(super) fn test_build_flags(
    packages: &[&Package],
    names: &[String],
    workspace: &Path,
    cargo: &CargoConfig,
) -> Option<Vec<String>> {
    if names.is_empty() {
        return None;
    }
    let selected = |target: &Target| target.test && names.contains(&target.name);
    let mut selectors = BTreeSet::new();
    for package in packages {
        let enabled_features = package.enabled_local_features(workspace, cargo);
        for target in package.targets.iter().filter(|t| selected(t)) {
            let selector = target.test_build_arg()?;
            // Cargo skips gated targets in a default build but errors if named explicitly.
            if target
                .required_features
                .iter()
                .any(|feature| !enabled_features.contains(feature.as_str()))
                || selector
                    .1
                    .is_some_and(|name| name.contains(['*', '?', '[']))
            {
                return None;
            }
            selectors.insert(selector);
        }
    }
    // A selector applies to all the chosen packages and can override `test = false`.
    if selectors.is_empty()
        || packages.iter().flat_map(|p| &p.targets).any(|target| {
            !selected(target)
                && target
                    .test_build_arg()
                    .is_some_and(|selector| selectors.contains(&selector))
        })
    {
        return None;
    }
    Some(
        selectors
            .into_iter()
            .map(|(flag, name)| match name {
                Some(name) => format!("{flag}={name}"),
                None => flag.to_owned(),
            })
            .collect(),
    )
}

/// One line of `cargo --message-format=json`.
#[derive(Deserialize)]
pub(super) struct CargoMessage {
    pub(super) reason: String,
    pub(super) package_id: Option<String>,
    pub(super) target: Option<ArtifactTarget>,
    pub(super) profile: Option<Profile>,
    pub(super) executable: Option<PathBuf>,
    #[serde(default)]
    pub(super) filenames: Vec<PathBuf>,
    /// The features the target was built with; absent from what is not an artifact.
    pub(super) features: Option<Vec<String>>,
    pub(super) message: Option<Diagnostic>,
}

#[derive(Deserialize)]
pub(super) struct ArtifactTarget {
    pub(super) name: String,
    pub(super) kind: Vec<String>,
    pub(super) src_path: Option<PathBuf>,
}

#[derive(Deserialize)]
pub(super) struct Profile {
    pub(super) test: bool,
}

#[derive(Deserialize)]
pub(super) struct Diagnostic {
    pub(super) level: String,
    pub(super) rendered: Option<String>,
    pub(super) message: Option<String>,
    #[serde(default)]
    pub(super) spans: Vec<DiagnosticSpan>,
}

#[derive(Deserialize)]
pub(super) struct DiagnosticSpan {
    pub(super) file_name: String,
    pub(super) byte_start: usize,
    pub(super) line_start: usize,
    pub(super) is_primary: bool,
}

#[derive(Debug, PartialEq, Clone)]
pub(super) struct ErrorSpan {
    pub(super) file: String,
    pub(super) byte_start: usize,
    pub(super) line: usize,
}

/// One compiler error. The primary spans say where it was detected, the secondary ones
/// often point at the cause (for "possibly-uninitialized", at the guard we inserted).
#[derive(Debug, PartialEq)]
pub(super) struct CompileError {
    pub(super) primary: Vec<ErrorSpan>,
    pub(super) secondary: Vec<ErrorSpan>,
    pub(super) rendered: String,
}

#[derive(Debug, Default, PartialEq)]
pub(super) struct BuildOutput {
    /// `(target name, executable, package, target kind)` of the test binaries.
    pub(super) test_binaries: Vec<(String, PathBuf, String, Vec<String>)>,
    pub(super) errors: Vec<CompileError>,
    pub(super) diagnostics: Vec<String>,
    pub(super) build_scripts: Vec<serde_json::Value>,
    pub(super) artifacts: Vec<(PathBuf, Vec<PathBuf>)>,
    /// The features each root file was built with, as cargo reports them.
    pub(super) features: Vec<(PathBuf, Vec<String>)>,
}

/// What a build of changed source came to.
#[derive(Debug, PartialEq)]
pub(super) enum SourceBuild {
    Built,
    /// The compiler refused the code: the change is not a program.
    Refused,
    /// The build ended badly and the compiler said nothing against the code (it was
    /// killed, the disk is full, cargo could not get its lock): this says nothing about
    /// the change. With the end of what was said, for the user.
    Failed(String),
}

pub(super) fn source_build(output: &std::process::Output) -> SourceBuild {
    if output.status.success() {
        return SourceBuild::Built;
    }
    let refused = !parse_build_output(&String::from_utf8_lossy(&output.stdout), &[])
        .diagnostics
        .is_empty();
    if refused {
        return SourceBuild::Refused;
    }
    let said = String::from_utf8_lossy(&output.stderr);
    let last: Vec<&str> = said.lines().rev().take(3).collect();
    let last: Vec<&str> = last.into_iter().rev().collect();
    SourceBuild::Failed(format!("{} ({})", last.join(" / "), output.status))
}

/// The workspace packages that depend on `package`, directly or through others.
pub(super) fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
    let mut reverse = BTreeMap::<&str, Vec<&str>>::new();
    for other in packages {
        for dependency in &other.dependencies {
            reverse
                .entry(&dependency.name)
                .or_default()
                .push(&other.name);
        }
    }
    let mut found = BTreeSet::new();
    let mut frontier = vec![package];
    while let Some(current) = frontier.pop() {
        if let Some(next) = reverse.get(current) {
            for &other in next {
                if other != package && found.insert(other) {
                    frontier.push(other);
                }
            }
        }
    }
    found.into_iter().map(str::to_owned).collect()
}

/// Package ids embed the path, and the build runs in a copy, so compare by name.
/// Ids look like `path+file:///dir#name@1.0.0`, `path+file:///dir/name#1.0.0` or `name 1.0.0 (path+...)`.
pub(super) fn is_package(id: &str, name: &str) -> bool {
    let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
    fragment.split('@').next() == Some(name)
        || path.rsplit('/').next() == Some(name)
        || id.split(' ').next() == Some(name)
}

pub(super) fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
    let mut out = BuildOutput::default();
    for line in stdout.lines() {
        let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
            continue;
        };
        match msg.reason.as_str() {
            "compiler-artifact" => {
                let Some(target) = msg.target else { continue };
                if let Some(path) = target.src_path {
                    let root = normalize(&path);
                    if let Some(features) = msg.features {
                        out.features.push((root.clone(), features));
                    }
                    out.artifacts.push((root, msg.filenames));
                }
                if let (Some(exe), Some(profile), Some(id)) =
                    (msg.executable, msg.profile, msg.package_id.as_deref())
                    && profile.test
                    && let Some(package) = packages.iter().find(|name| is_package(id, name))
                {
                    out.test_binaries
                        .push((target.name, exe, package.to_string(), target.kind));
                }
            }
            "build-script-executed" => {
                if let Ok(script) = serde_json::from_str(line) {
                    out.build_scripts.push(script);
                }
            }
            "compiler-message" => {
                let Some(diag) = msg.message else { continue };
                if diag.level != "error" {
                    continue;
                }
                let rendered = diag.rendered.or(diag.message).unwrap_or_default();
                if !rendered.is_empty() && !out.diagnostics.contains(&rendered) {
                    out.diagnostics.push(rendered.clone());
                }
                let span = |s: &DiagnosticSpan| ErrorSpan {
                    file: s.file_name.clone(),
                    byte_start: s.byte_start,
                    line: s.line_start,
                };
                let error = CompileError {
                    primary: diag
                        .spans
                        .iter()
                        .filter(|s| s.is_primary)
                        .map(span)
                        .collect(),
                    secondary: diag
                        .spans
                        .iter()
                        .filter(|s| !s.is_primary)
                        .map(span)
                        .collect(),
                    rendered,
                };
                // "aborting due to N previous errors" and friends carry no location, and the
                // lib is compiled twice (plain and test), which reports everything twice.
                if !error.primary.is_empty() && !out.errors.contains(&error) {
                    out.errors.push(error);
                }
            }
            _ => {}
        }
    }
    out.test_binaries.sort_by(|left, right| {
        (&left.2, &left.3, &left.0, &left.1).cmp(&(&right.2, &right.3, &right.0, &right.1))
    });
    out
}

/// Cargo puts each rustc dep-info file beside an artifact with the crate's stem.
pub(super) fn dependency_file(artifact: &Path) -> Option<String> {
    let stem = artifact.file_stem()?.to_str()?;
    let unprefixed = match artifact.extension().and_then(|ext| ext.to_str()) {
        Some("a" | "so" | "dylib" | "rlib" | "rmeta") => stem.strip_prefix("lib"),
        _ => None,
    };
    unprefixed
        .and_then(|stem| fs::read_to_string(artifact.with_file_name(format!("{stem}.d"))).ok())
        .or_else(|| fs::read_to_string(artifact.with_extension("d")).ok())
}

pub(super) fn dep_inputs(text: &str, copy: &Path) -> BTreeSet<PathBuf> {
    // Rustc writes one empty rule per input. This avoids counting output
    // artifacts and excludes Cargo's transitive, promoted dependency file.
    text.lines()
        .filter_map(|line| line.strip_suffix(':'))
        .map(|name| name.replace("\\ ", " ").replace("\\#", "#"))
        .map(|name| normalize(&copy.join(name)))
        .collect()
}

pub(super) fn directory_entries(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
    fs::read_dir(path)
        .into_iter()
        .flatten()
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
}

pub(super) fn same_binary(a: &Path, b: &Path) -> Option<bool> {
    let (a, b) = (fs::File::open(a).ok()?, fs::File::open(b).ok()?);
    let (left, right) = (a.metadata().ok()?, b.metadata().ok()?);
    if !left.is_file() || !right.is_file() || left.len() != right.len() {
        return Some(false);
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if left.ino() == right.ino() && left.dev() == right.dev() {
            return Some(true);
        }
    }
    compare_streams(a, b).ok()
}

pub(super) fn compare_streams(
    a: impl std::io::Read,
    b: impl std::io::Read,
) -> std::io::Result<bool> {
    use std::io::{BufRead, BufReader, ErrorKind};
    const BUFFER_BYTES: usize = 64 * 1024;
    let mut a = BufReader::with_capacity(BUFFER_BYTES, a);
    let mut b = BufReader::with_capacity(BUFFER_BYTES, b);
    loop {
        let left = match a.fill_buf() {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            Err(error) => return Err(error),
        };
        let right = match b.fill_buf() {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            Err(error) => return Err(error),
        };
        let count = left.len().min(right.len());
        if count == 0 {
            return Ok(left.is_empty() && right.is_empty());
        }
        if left[..count] != right[..count] {
            return Ok(false);
        }
        a.consume(count);
        b.consume(count);
    }
}

pub(super) fn artifact_inputs(artifact: &Path, root: &Path, copy: &Path) -> BTreeSet<PathBuf> {
    let read = |binary: &Path| {
        dependency_file(binary)
            .map(|text| dep_inputs(&text, copy))
            .filter(|inputs| inputs.contains(root))
    };
    if let Some(inputs) = read(artifact) {
        return inputs;
    }
    // Cargo exposes binaries linked for integration tests at the top of the
    // profile. Match the actual rustc output beside its private dep-info file.
    let Some((profile, stem)) = artifact
        .parent()
        .zip(artifact.file_stem().and_then(|s| s.to_str()))
    else {
        return BTreeSet::new();
    };
    let crate_stem = stem.replace('-', "_");
    let hashed = format!("{crate_stem}-");
    let old = directory_entries(&profile.join("deps")).filter(|path| {
        path.extension() == artifact.extension()
            && path
                .file_stem()
                .and_then(|s| s.to_str())
                .is_some_and(|name| name.starts_with(&hashed))
    });
    let mut private_name = std::ffi::OsString::from(crate_stem);
    if let Some(extension) = artifact.extension() {
        private_name.push(".");
        private_name.push(extension);
    }
    let new = directory_entries(&profile.join("build"))
        .flat_map(|package| directory_entries(&package))
        .map(|unit| unit.join("out").join(&private_name));
    // A cached binary can have identical bytes and different inputs. Require
    // the source to be present in every matching compilation.
    old.chain(new)
        .filter_map(|path| {
            let inputs = read(&path)?;
            (same_binary(artifact, &path) == Some(true)).then_some(inputs)
        })
        .reduce(|left, right| left.intersection(&right).cloned().collect())
        .unwrap_or_default()
}

#[derive(Default)]
pub(super) struct BuiltSources {
    pub(super) files: BTreeMap<PathBuf, BTreeSet<PathBuf>>,
    /// The features a root file was built with, build by build (a host and a target
    /// build may differ). A root without an entry was built by a cargo that did not
    /// say, or with flags that may turn features on behind cargo's back.
    pub(super) features: BTreeMap<PathBuf, Vec<BTreeSet<String>>>,
}

/// The ranges that every build leaves out: those of one build that lie within a range
/// of each of the others. With no build, nothing is known to be left out.
pub(super) fn left_out_of_all(per_build: &[Vec<(usize, usize)>]) -> Vec<(usize, usize)> {
    let mut all: Vec<(usize, usize)> = per_build
        .iter()
        .flatten()
        .filter(|(from, to)| {
            per_build
                .iter()
                .all(|ranges| ranges.iter().any(|(start, end)| start <= from && to <= end))
        })
        .copied()
        .collect();
    all.sort_unstable();
    all.dedup();
    all
}

/// Whether a cargo configuration file that holds for a build in `dir` speaks of both a
/// `--cfg` flag and a feature (`rustflags = ["--cfg", 'feature="x"']`): read as text, so
/// rather once too often than once too rarely.
pub(super) fn configuration_names_a_feature(dir: &Path, cargo_home: Option<PathBuf>) -> bool {
    let home = cargo_home
        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")));
    dir.ancestors()
        .map(|dir| dir.join(".cargo"))
        .chain(home)
        .flat_map(|dir| [dir.join("config.toml"), dir.join("config")])
        .filter_map(|file| fs::read_to_string(file).ok())
        .any(|text| text.contains("--cfg") && text.contains("feature"))
}

/// Whether the compiler may be told of features that cargo does not report
/// (`RUSTFLAGS='--cfg feature="x"'`).
pub(super) fn features_from_flags(
    flags: impl IntoIterator<Item = Option<std::ffi::OsString>>,
) -> bool {
    flags.into_iter().flatten().any(|value| {
        // `--cfg feature="x"`, not `-C target-feature=+x`.
        let value = value.to_string_lossy();
        value.contains("cfg") && value.replace("target-feature", "").contains("feature")
    })
}

impl BuiltSources {
    /// `features_known` is false where something other than cargo's features may turn
    /// one on: nothing is then taken to be left out.
    pub(super) fn from_artifacts(
        artifacts: &[(PathBuf, Vec<PathBuf>)],
        features: &[(PathBuf, Vec<String>)],
        features_known: bool,
        copy: &Path,
    ) -> Self {
        let mut built = Self::default();
        for (root, features) in features.iter().filter(|_| features_known) {
            let set: BTreeSet<String> = features.iter().cloned().collect();
            let sets = built.features.entry(root.clone()).or_default();
            if !sets.contains(&set) {
                sets.push(set);
            }
        }
        for (root, artifacts) in artifacts {
            if !root.starts_with(copy) {
                continue;
            }
            let files = built.files.entry(root.clone()).or_default();
            files.insert(root.clone());
            if let Some(inputs) = artifacts
                .iter()
                .map(|file| artifact_inputs(file, root, copy))
                .find(|inputs| !inputs.is_empty())
            {
                files.extend(inputs);
            }
        }
        built
    }

    pub(super) fn contains(&self, source: &SourceFile) -> bool {
        source.owners.iter().any(|root| {
            self.files
                .get(root)
                .is_some_and(|files| files.contains(&source.path))
        })
    }

    /// The parts of a built file that no build of it compiled: code under a `cfg` that
    /// the features of every build that owns the file turn off. Nothing when one of
    /// those builds did not say its features.
    pub(super) fn left_out(&self, source: &SourceFile) -> Vec<(usize, usize)> {
        self.left_out_of(source, &source.original)
            .unwrap_or_default()
    }

    /// The feature sets of the builds that compiled the file. `None` when one of them
    /// did not say its features.
    pub(super) fn builds_of(&self, source: &SourceFile) -> Option<Vec<&BTreeSet<String>>> {
        let mut builds: Vec<&BTreeSet<String>> = vec![];
        for root in &source.owners {
            if !self
                .files
                .get(root)
                .is_some_and(|files| files.contains(&source.path))
            {
                continue;
            }
            builds.extend(self.features.get(root)?);
        }
        Some(builds)
    }

    /// The same for another text of the file. `None` when that is not Rust, or a build
    /// did not say its features: nothing is known then.
    pub(super) fn left_out_of(
        &self,
        source: &SourceFile,
        text: &str,
    ) -> Option<Vec<(usize, usize)>> {
        let builds = self.builds_of(source)?;
        let parsed = instrument::parse_source(text).ok()?;
        let per_build: Vec<Vec<(usize, usize)>> = builds
            .iter()
            .map(|features| instrument::inactive_ranges(text, &parsed, features))
            .collect();
        Some(left_out_of_all(&per_build))
    }

    /// Whether two texts of the file are the same program in every build of it: each
    /// build with what it leaves out of either, and the `cfg` attributes it settles as
    /// on, which are no part of what it builds. False when that is not known.
    pub(super) fn same_program(&self, source: &SourceFile, a: &str, b: &str) -> bool {
        let (Some(builds), Ok(parsed_a), Ok(parsed_b)) = (
            self.builds_of(source),
            instrument::parse_source(a),
            instrument::parse_source(b),
        ) else {
            return false;
        };
        let apart = |text: &str, parsed: &syn::File, features: &BTreeSet<String>| {
            let mut ranges = instrument::inactive_ranges(text, parsed, features);
            ranges.extend(instrument::settled_cfg_attributes(text, parsed, features));
            ranges
        };
        !builds.is_empty()
            && builds.iter().all(|features| {
                reverts::same_build(
                    a,
                    &apart(a, &parsed_a, features),
                    b,
                    &apart(b, &parsed_b, features),
                )
            })
    }
}

pub(super) fn cargo_metadata(dir: &Path, cargo: &CargoConfig) -> Result<Metadata> {
    let output = Command::new("cargo")
        .args(["metadata", "--no-deps", "--format-version", "1"])
        .args(cargo.flags())
        .current_dir(dir)
        .output()
        .context("running cargo metadata")?;
    if !output.status.success() {
        bail!(
            "cargo metadata failed:\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    serde_json::from_slice(&output.stdout).context("parsing cargo metadata")
}