targeted-mutation 0.4.1

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
//! Which lines of which files to analyse (`--since`, `--lines`).

use std::collections::BTreeMap;

use anyhow::{Result, bail};

/// Line ranges per file. Paths are relative to the workspace root, with `/` separators.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Scope {
    files: BTreeMap<String, Vec<(usize, usize)>>,
}

impl Scope {
    /// Parses `FILE`, `FILE:LINE` or `FILE:FROM-TO` (1-based, inclusive).
    pub fn parse_lines(specs: &[String]) -> Result<Scope> {
        let mut scope = Scope::default();
        for spec in specs {
            if spec.starts_with(':') {
                bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
            }
            let (file, range) = match spec.rsplit_once(':') {
                Some((file, lines))
                    // `file` is not empty: a spec that starts with `:` was refused above.
                    if lines.starts_with(|c: char| c.is_ascii_digit()) =>
                {
                    let (from, to) = lines.split_once('-').unwrap_or((lines, lines));
                    let parse = |text: &str| text.parse::<usize>().ok().filter(|n| *n > 0);
                    match (parse(from), parse(to)) {
                        (Some(from), Some(to)) if from <= to => (file, (from, to)),
                        _ => bail!("not a line range: `{spec}` (expected FILE:FROM-TO)"),
                    }
                }
                _ => (spec.as_str(), (1, usize::MAX)),
            };
            if file.is_empty() {
                bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
            }
            scope.add(file, range);
        }
        Ok(scope)
    }

    /// Reads the output of `git diff -U0`: the lines each hunk adds or changes. A hunk that
    /// only deletes marks the lines on either side of the deletion, because the code that
    /// is left there now behaves differently.
    pub fn from_diff(diff: &str) -> Scope {
        let mut scope = Scope::default();
        let mut file: Option<String> = None;
        for line in diff.lines() {
            if let Some(path) = line.strip_prefix("+++ ") {
                // `+++ b/path`, or `+++ /dev/null` for a deleted file. Git quotes a path
                // with bytes outside printable ASCII, and puts a tab after one with a space.
                let path = match unquote(path) {
                    Some(path) => path,
                    None => path.strip_suffix('\t').unwrap_or(path).to_string(),
                };
                file = path.strip_prefix("b/").map(str::to_string);
            } else if line.starts_with("@@ ")
                && let Some(file) = &file
                && let Some(added) = line.split(' ').find_map(|part| part.strip_prefix('+'))
            {
                let (start, count) = added.split_once(',').unwrap_or((added, "1"));
                let (Ok(start), Ok(count)) = (start.parse::<usize>(), count.parse::<usize>())
                else {
                    continue;
                };
                let range = if count == 0 {
                    // `+N,0`: lines were removed after line N.
                    (start.max(1), start + 1)
                } else {
                    (start, start + count - 1)
                };
                scope.add(file, range);
            }
        }
        scope
    }

    pub fn add(&mut self, file: &str, range: (usize, usize)) {
        self.files
            .entry(file.replace('\\', "/"))
            .or_default()
            .push(range);
    }

    pub fn add_whole_file(&mut self, file: &str) {
        self.add(file, (1, usize::MAX));
    }

    pub fn merge(&mut self, other: Scope) {
        for (file, ranges) in other.files {
            self.files.entry(file).or_default().extend(ranges);
        }
    }

    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    pub fn files(&self) -> impl Iterator<Item = &str> {
        self.files.keys().map(String::as_str)
    }

    /// Whether lines `first..=last` of `file` touch the scope.
    pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
        let ranges = self.files.get(file).or_else(|| {
            if file.contains('\\') {
                self.files.get(&file.replace('\\', "/"))
            } else {
                None
            }
        });
        ranges.is_some_and(|ranges| {
            ranges
                .iter()
                .any(|(from, to)| first <= *to && *from <= last)
        })
    }
}

/// The path git wrote between double quotes (`"b/src/\344\276\241.rs"`): C escapes, and
/// three octal digits for each byte that is not printable ASCII. `None` for text that is
/// not quoted that way.
fn unquote(text: &str) -> Option<String> {
    let inner = text.strip_prefix('"')?.strip_suffix('"')?;
    let mut bytes = Vec::with_capacity(inner.len());
    let mut rest = inner.bytes();
    while let Some(byte) = rest.next() {
        if byte == b'"' {
            return None;
        }
        if byte != b'\\' {
            bytes.push(byte);
            continue;
        }
        bytes.push(match rest.next()? {
            b'a' => 7,
            b'b' => 8,
            b't' => b'\t',
            b'n' => b'\n',
            b'v' => 11,
            b'f' => 12,
            b'r' => b'\r',
            b'"' => b'"',
            b'\\' => b'\\',
            first @ b'0'..=b'3' => {
                let mut value = u32::from(first - b'0');
                for _ in 0..2 {
                    let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
                    value = value * 8 + u32::from(digit - b'0');
                }
                u8::try_from(value).ok()?
            }
            _ => return None,
        });
    }
    String::from_utf8(bytes).ok()
}

/// Byte offsets of the line starts in one source file.
pub(crate) struct LineIndex(Vec<usize>);

impl LineIndex {
    pub(crate) fn new(source: &str) -> Self {
        Self(
            std::iter::once(0)
                .chain(
                    source
                        .bytes()
                        .enumerate()
                        .filter(|&(_, byte)| byte == b'\n')
                        .map(|(offset, _)| offset + 1),
                )
                .collect(),
        )
    }

    pub(crate) fn line_of(&self, offset: usize) -> usize {
        self.0.partition_point(|&start| start <= offset)
    }

    pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
        let offset = if source.is_char_boundary(offset) {
            offset
        } else {
            source.len()
        };
        let line = self.line_of(offset);
        let column = source[self.0[line - 1]..offset].chars().count() + 1;
        (line, column)
    }

    pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
        // As in the unindexed lookup, out-of-range lines and columns clamp to EOF.
        let start = self
            .0
            .get(line.checked_sub(1)?)
            .copied()
            .unwrap_or(source.len());
        let column = column.checked_sub(1)?;
        if column == 0 {
            return Some(start);
        }
        let rest = &source[start..];
        let capped = column.min(rest.len());
        let within = if rest.as_bytes()[..capped].is_ascii() {
            capped
        } else {
            rest.char_indices()
                .nth(column)
                .map_or(rest.len(), |(offset, _)| offset)
        };
        Some(start + within)
    }
}

/// 1-based line of the byte at `offset`.
pub fn line_of(source: &str, offset: usize) -> usize {
    source.as_bytes()[..offset.min(source.len())]
        .iter()
        .filter(|b| **b == b'\n')
        .count()
        + 1
}

#[cfg(test)]
mod tests {
    use super::*;

    fn specs(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn line_specs() {
        let scope =
            Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
        // Inside, on both boundaries, overlapping, and outside.
        assert!(scope.touches("src/a.rs", 12, 13));
        assert!(scope.touches("src/a.rs", 1, 10));
        assert!(scope.touches("src/a.rs", 20, 25));
        assert!(scope.touches("src/a.rs", 5, 40));
        assert!(scope.touches("src/a.rs", 30, 30));
        assert!(!scope.touches("src/a.rs", 1, 9));
        assert!(!scope.touches("src/a.rs", 21, 29));
        assert!(!scope.touches("src/a.rs", 31, 99));
        assert!(scope.touches("src/b.rs", 7, 7));
        assert!(!scope.touches("src/c.rs", 7, 7));
        assert!(
            scope.touches("src\\b.rs", 1, 1),
            "separators are normalised"
        );
        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
        assert!(!scope.is_empty());
        assert!(Scope::default().is_empty());

        for bad in [
            "src/a.rs:0",
            "src/a.rs:5-3",
            "src/a.rs:4-3",
            "src/a.rs:1-x",
            ":3",
            "src/a.rs:3-",
        ] {
            assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
        }
        // A Windows drive letter or a name with a colon is a file, not a range.
        let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
        assert!(odd.touches("dir:name/a.rs", 1, 1));
    }

    #[test]
    fn diff_hunks() {
        let diff = "\
diff --git a/src/a.rs b/src/a.rs
index 111..222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -10,2 +10,3 @@ fn changed() {
-old
-old
+new
+new
+new
@@ -30 +31 @@
-x
+y
@@ -40,3 +40,0 @@ fn deleted_lines() {
-gone
-gone
-gone
@@ -0,0 +1,2 @@
+top
+top
diff --git a/src/gone.rs b/src/gone.rs
deleted file mode 100644
--- a/src/gone.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-all
diff --git a/src/new.rs b/src/new.rs
new file mode 100644
--- /dev/null
+++ b/src/new.rs
@@ -0,0 +1,4 @@
+fresh
";
        let scope = Scope::from_diff(diff);
        // Changed: 10..=12. Single line: 31. Pure deletion after line 40: 40 and 41.
        for (line, expected) in [
            (9, false),
            (10, true),
            (12, true),
            (13, false),
            (31, true),
            (32, false),
            (39, false),
            (40, true),
            (41, true),
            (42, false),
            (1, true),
            (2, true),
            (3, false),
        ] {
            assert_eq!(
                scope.touches("src/a.rs", line, line),
                expected,
                "line {line}"
            );
        }
        assert!(
            !scope.touches("src/gone.rs", 1, 100),
            "a deleted file has no lines left"
        );
        assert!(scope.touches("src/new.rs", 4, 4));
        assert!(!scope.touches("src/new.rs", 5, 5));
        assert_eq!(Scope::from_diff(""), Scope::default());
    }

    #[test]
    fn paths_are_read_as_git_writes_them() {
        // A path with a space is followed by a tab; one with other bytes is quoted, with
        // the prefix inside the quotes and octal for what is not ASCII.
        let diff = "\
--- a/src/two words.rs\t
+++ b/src/two words.rs\t
@@ -3 +3 @@
--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
@@ -5 +5 @@
--- \"a/src/a\\\"b\\\\c\\td e.rs\"
+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
@@ -7 +7 @@
--- a/src/価格.rs
+++ b/src/価格.rs
@@ -9 +9 @@
--- \"a/src/gone \\303\\251.rs\"
+++ /dev/null
@@ -1 +0,0 @@
";
        let scope = Scope::from_diff(diff);
        assert_eq!(
            scope.files().collect::<Vec<_>>(),
            [
                // Stored with `/`, as every path is (a Windows separator).
                "src/a\"b/c\td e.rs",
                "src/two words.rs",
                "src/価格.rs"
            ]
        );
        assert!(scope.touches("src/two words.rs", 3, 3));
        // Quoted or not (`core.quotePath`), the same file.
        assert!(scope.touches("src/価格.rs", 5, 5));
        assert!(scope.touches("src/価格.rs", 9, 9));
        assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
    }

    #[test]
    fn a_quoted_path_is_what_its_escapes_spell() {
        for (quoted, path) in [
            (r#""plain""#, Some("plain")),
            (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
            (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
            (r#""\343\201\202\101""#, Some("あA")),
            // Not closed, an escape git does not write, octal cut short, bytes that
            // are no text: nothing is guessed.
            (r#""open"#, None),
            (r#""a\qb""#, None),
            (r#""\34""#, None),
            (r#""\377""#, None),
            (r#""a"b""#, None),
            ("bare", None),
        ] {
            assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
        }
    }

    #[test]
    fn merging_and_whole_files() {
        let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
        let mut other = Scope::default();
        other.add_whole_file("b.rs");
        other.add("a.rs", (9, 9));
        scope.merge(other);
        assert!(
            scope.touches("a.rs", 9, 9)
                && scope.touches("a.rs", 2, 2)
                && !scope.touches("a.rs", 5, 5)
        );
        assert!(scope.touches("b.rs", 12345, 12345));
    }

    #[test]
    fn indexed_positions_match_the_previous_scans() {
        for row in include_str!("../tests/data/source-positions.pict.tsv")
            .lines()
            .skip(1)
        {
            let fields: Vec<_> = row.split('\t').collect();
            let [text, newline, ending, query] = fields.as_slice() else {
                panic!("invalid fixture row {row}");
            };
            let word = if *text == "unicode" { "é🦀" } else { "xyz" };
            let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
            let source = match *ending {
                "empty" => String::new(),
                "newline" => format!("{word}{newline}{word}{newline}"),
                "none" => format!("{word}{newline}{word}"),
                _ => panic!("invalid ending in {row}"),
            };
            let lines = LineIndex::new(&source);
            for offset in 0..=source.len() + 1 {
                assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
                let prefix = source.get(..offset).unwrap_or(&source);
                let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
                assert_eq!(
                    lines.position(&source, offset),
                    (line_of(prefix, prefix.len()), column),
                    "{row}"
                );
            }
            let (line, column) = match *query {
                "first" => (1, 1),
                "boundary" => (2, 2),
                "beyond" => (20, 99),
                "zero" => (1, 0),
                _ => panic!("invalid query in {row}"),
            };
            assert_eq!(
                lines.offset_of(&source, line, column),
                crate::instrument::offset_of(&source, line, column),
                "{row}"
            );
        }
    }

    #[test]
    fn long_ascii_prefix_before_multibyte_columns() {
        let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
        let lines = LineIndex::new(&source);
        for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
            assert_eq!(
                lines.offset_of(&source, 2, column),
                crate::instrument::offset_of(&source, 2, column)
            );
        }
    }

    #[test]
    fn lines_of_offsets() {
        let source = "a\nbc\n\nd";
        assert_eq!(
            [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
            [1, 1, 2, 2, 3, 4, 4, 4]
        );
    }
}