Skip to main content

targeted_mutation/
scope.rs

1//! Which lines of which files to analyse (`--since`, `--lines`).
2
3use std::collections::BTreeMap;
4
5use anyhow::{Result, bail};
6
7/// Line ranges per file. Paths are relative to the workspace root, with `/` separators.
8#[derive(Debug, Default, Clone, PartialEq, Eq)]
9pub struct Scope {
10    files: BTreeMap<String, Vec<(usize, usize)>>,
11}
12
13impl Scope {
14    /// Parses `FILE`, `FILE:LINE` or `FILE:FROM-TO` (1-based, inclusive).
15    pub fn parse_lines(specs: &[String]) -> Result<Scope> {
16        let mut scope = Scope::default();
17        for spec in specs {
18            if spec.starts_with(':') {
19                bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
20            }
21            let (file, range) = match spec.rsplit_once(':') {
22                Some((file, lines))
23                    // `file` is not empty: a spec that starts with `:` was refused above.
24                    if lines.starts_with(|c: char| c.is_ascii_digit()) =>
25                {
26                    let (from, to) = lines.split_once('-').unwrap_or((lines, lines));
27                    let parse = |text: &str| text.parse::<usize>().ok().filter(|n| *n > 0);
28                    match (parse(from), parse(to)) {
29                        (Some(from), Some(to)) if from <= to => (file, (from, to)),
30                        _ => bail!("not a line range: `{spec}` (expected FILE:FROM-TO)"),
31                    }
32                }
33                _ => (spec.as_str(), (1, usize::MAX)),
34            };
35            if file.is_empty() {
36                bail!("not a line range: `{spec}` (expected FILE:FROM-TO)");
37            }
38            scope.add(file, range);
39        }
40        Ok(scope)
41    }
42
43    /// Reads the output of `git diff -U0`: the lines each hunk adds or changes. A hunk that
44    /// only deletes marks the lines on either side of the deletion, because the code that
45    /// is left there now behaves differently.
46    pub fn from_diff(diff: &str) -> Scope {
47        let mut scope = Scope::default();
48        let mut file: Option<String> = None;
49        for line in diff.lines() {
50            if let Some(path) = line.strip_prefix("+++ ") {
51                // `+++ b/path`, or `+++ /dev/null` for a deleted file. Git quotes a path
52                // with bytes outside printable ASCII, and puts a tab after one with a space.
53                let path = match unquote(path) {
54                    Some(path) => path,
55                    None => path.strip_suffix('\t').unwrap_or(path).to_string(),
56                };
57                file = path.strip_prefix("b/").map(str::to_string);
58            } else if line.starts_with("@@ ")
59                && let Some(file) = &file
60                && let Some(added) = line.split(' ').find_map(|part| part.strip_prefix('+'))
61            {
62                let (start, count) = added.split_once(',').unwrap_or((added, "1"));
63                let (Ok(start), Ok(count)) = (start.parse::<usize>(), count.parse::<usize>())
64                else {
65                    continue;
66                };
67                let range = if count == 0 {
68                    // `+N,0`: lines were removed after line N.
69                    (start.max(1), start + 1)
70                } else {
71                    (start, start + count - 1)
72                };
73                scope.add(file, range);
74            }
75        }
76        scope
77    }
78
79    pub fn add(&mut self, file: &str, range: (usize, usize)) {
80        self.files
81            .entry(file.replace('\\', "/"))
82            .or_default()
83            .push(range);
84    }
85
86    pub fn add_whole_file(&mut self, file: &str) {
87        self.add(file, (1, usize::MAX));
88    }
89
90    pub fn merge(&mut self, other: Scope) {
91        for (file, ranges) in other.files {
92            self.files.entry(file).or_default().extend(ranges);
93        }
94    }
95
96    pub fn is_empty(&self) -> bool {
97        self.files.is_empty()
98    }
99
100    pub fn files(&self) -> impl Iterator<Item = &str> {
101        self.files.keys().map(String::as_str)
102    }
103
104    /// Whether lines `first..=last` of `file` touch the scope.
105    pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
106        let ranges = self.files.get(file).or_else(|| {
107            if file.contains('\\') {
108                self.files.get(&file.replace('\\', "/"))
109            } else {
110                None
111            }
112        });
113        ranges.is_some_and(|ranges| {
114            ranges
115                .iter()
116                .any(|(from, to)| first <= *to && *from <= last)
117        })
118    }
119}
120
121/// The path git wrote between double quotes (`"b/src/\344\276\241.rs"`): C escapes, and
122/// three octal digits for each byte that is not printable ASCII. `None` for text that is
123/// not quoted that way.
124fn unquote(text: &str) -> Option<String> {
125    let inner = text.strip_prefix('"')?.strip_suffix('"')?;
126    let mut bytes = Vec::with_capacity(inner.len());
127    let mut rest = inner.bytes();
128    while let Some(byte) = rest.next() {
129        if byte == b'"' {
130            return None;
131        }
132        if byte != b'\\' {
133            bytes.push(byte);
134            continue;
135        }
136        bytes.push(match rest.next()? {
137            b'a' => 7,
138            b'b' => 8,
139            b't' => b'\t',
140            b'n' => b'\n',
141            b'v' => 11,
142            b'f' => 12,
143            b'r' => b'\r',
144            b'"' => b'"',
145            b'\\' => b'\\',
146            first @ b'0'..=b'3' => {
147                let mut value = u32::from(first - b'0');
148                for _ in 0..2 {
149                    let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
150                    value = value * 8 + u32::from(digit - b'0');
151                }
152                u8::try_from(value).ok()?
153            }
154            _ => return None,
155        });
156    }
157    String::from_utf8(bytes).ok()
158}
159
160/// Byte offsets of the line starts in one source file.
161pub(crate) struct LineIndex(Vec<usize>);
162
163impl LineIndex {
164    pub(crate) fn new(source: &str) -> Self {
165        Self(
166            std::iter::once(0)
167                .chain(
168                    source
169                        .bytes()
170                        .enumerate()
171                        .filter(|&(_, byte)| byte == b'\n')
172                        .map(|(offset, _)| offset + 1),
173                )
174                .collect(),
175        )
176    }
177
178    pub(crate) fn line_of(&self, offset: usize) -> usize {
179        self.0.partition_point(|&start| start <= offset)
180    }
181
182    pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
183        let offset = if source.is_char_boundary(offset) {
184            offset
185        } else {
186            source.len()
187        };
188        let line = self.line_of(offset);
189        let column = source[self.0[line - 1]..offset].chars().count() + 1;
190        (line, column)
191    }
192
193    pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
194        // As in the unindexed lookup, out-of-range lines and columns clamp to EOF.
195        let start = self
196            .0
197            .get(line.checked_sub(1)?)
198            .copied()
199            .unwrap_or(source.len());
200        let column = column.checked_sub(1)?;
201        if column == 0 {
202            return Some(start);
203        }
204        let rest = &source[start..];
205        let capped = column.min(rest.len());
206        let within = if rest.as_bytes()[..capped].is_ascii() {
207            capped
208        } else {
209            rest.char_indices()
210                .nth(column)
211                .map_or(rest.len(), |(offset, _)| offset)
212        };
213        Some(start + within)
214    }
215}
216
217/// 1-based line of the byte at `offset`.
218pub fn line_of(source: &str, offset: usize) -> usize {
219    source.as_bytes()[..offset.min(source.len())]
220        .iter()
221        .filter(|b| **b == b'\n')
222        .count()
223        + 1
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    fn specs(list: &[&str]) -> Vec<String> {
231        list.iter().map(|s| s.to_string()).collect()
232    }
233
234    #[test]
235    fn line_specs() {
236        let scope =
237            Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
238        // Inside, on both boundaries, overlapping, and outside.
239        assert!(scope.touches("src/a.rs", 12, 13));
240        assert!(scope.touches("src/a.rs", 1, 10));
241        assert!(scope.touches("src/a.rs", 20, 25));
242        assert!(scope.touches("src/a.rs", 5, 40));
243        assert!(scope.touches("src/a.rs", 30, 30));
244        assert!(!scope.touches("src/a.rs", 1, 9));
245        assert!(!scope.touches("src/a.rs", 21, 29));
246        assert!(!scope.touches("src/a.rs", 31, 99));
247        assert!(scope.touches("src/b.rs", 7, 7));
248        assert!(!scope.touches("src/c.rs", 7, 7));
249        assert!(
250            scope.touches("src\\b.rs", 1, 1),
251            "separators are normalised"
252        );
253        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
254        assert!(!scope.is_empty());
255        assert!(Scope::default().is_empty());
256
257        for bad in [
258            "src/a.rs:0",
259            "src/a.rs:5-3",
260            "src/a.rs:4-3",
261            "src/a.rs:1-x",
262            ":3",
263            "src/a.rs:3-",
264        ] {
265            assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
266        }
267        // A Windows drive letter or a name with a colon is a file, not a range.
268        let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
269        assert!(odd.touches("dir:name/a.rs", 1, 1));
270    }
271
272    #[test]
273    fn diff_hunks() {
274        let diff = "\
275diff --git a/src/a.rs b/src/a.rs
276index 111..222 100644
277--- a/src/a.rs
278+++ b/src/a.rs
279@@ -10,2 +10,3 @@ fn changed() {
280-old
281-old
282+new
283+new
284+new
285@@ -30 +31 @@
286-x
287+y
288@@ -40,3 +40,0 @@ fn deleted_lines() {
289-gone
290-gone
291-gone
292@@ -0,0 +1,2 @@
293+top
294+top
295diff --git a/src/gone.rs b/src/gone.rs
296deleted file mode 100644
297--- a/src/gone.rs
298+++ /dev/null
299@@ -1,5 +0,0 @@
300-all
301diff --git a/src/new.rs b/src/new.rs
302new file mode 100644
303--- /dev/null
304+++ b/src/new.rs
305@@ -0,0 +1,4 @@
306+fresh
307";
308        let scope = Scope::from_diff(diff);
309        // Changed: 10..=12. Single line: 31. Pure deletion after line 40: 40 and 41.
310        for (line, expected) in [
311            (9, false),
312            (10, true),
313            (12, true),
314            (13, false),
315            (31, true),
316            (32, false),
317            (39, false),
318            (40, true),
319            (41, true),
320            (42, false),
321            (1, true),
322            (2, true),
323            (3, false),
324        ] {
325            assert_eq!(
326                scope.touches("src/a.rs", line, line),
327                expected,
328                "line {line}"
329            );
330        }
331        assert!(
332            !scope.touches("src/gone.rs", 1, 100),
333            "a deleted file has no lines left"
334        );
335        assert!(scope.touches("src/new.rs", 4, 4));
336        assert!(!scope.touches("src/new.rs", 5, 5));
337        assert_eq!(Scope::from_diff(""), Scope::default());
338    }
339
340    #[test]
341    fn paths_are_read_as_git_writes_them() {
342        // A path with a space is followed by a tab; one with other bytes is quoted, with
343        // the prefix inside the quotes and octal for what is not ASCII.
344        let diff = "\
345--- a/src/two words.rs\t
346+++ b/src/two words.rs\t
347@@ -3 +3 @@
348--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
349+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
350@@ -5 +5 @@
351--- \"a/src/a\\\"b\\\\c\\td e.rs\"
352+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
353@@ -7 +7 @@
354--- a/src/価格.rs
355+++ b/src/価格.rs
356@@ -9 +9 @@
357--- \"a/src/gone \\303\\251.rs\"
358+++ /dev/null
359@@ -1 +0,0 @@
360";
361        let scope = Scope::from_diff(diff);
362        assert_eq!(
363            scope.files().collect::<Vec<_>>(),
364            [
365                // Stored with `/`, as every path is (a Windows separator).
366                "src/a\"b/c\td e.rs",
367                "src/two words.rs",
368                "src/価格.rs"
369            ]
370        );
371        assert!(scope.touches("src/two words.rs", 3, 3));
372        // Quoted or not (`core.quotePath`), the same file.
373        assert!(scope.touches("src/価格.rs", 5, 5));
374        assert!(scope.touches("src/価格.rs", 9, 9));
375        assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
376    }
377
378    #[test]
379    fn a_quoted_path_is_what_its_escapes_spell() {
380        for (quoted, path) in [
381            (r#""plain""#, Some("plain")),
382            (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
383            (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
384            (r#""\343\201\202\101""#, Some("あA")),
385            // Not closed, an escape git does not write, octal cut short, bytes that
386            // are no text: nothing is guessed.
387            (r#""open"#, None),
388            (r#""a\qb""#, None),
389            (r#""\34""#, None),
390            (r#""\377""#, None),
391            (r#""a"b""#, None),
392            ("bare", None),
393        ] {
394            assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
395        }
396    }
397
398    #[test]
399    fn merging_and_whole_files() {
400        let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
401        let mut other = Scope::default();
402        other.add_whole_file("b.rs");
403        other.add("a.rs", (9, 9));
404        scope.merge(other);
405        assert!(
406            scope.touches("a.rs", 9, 9)
407                && scope.touches("a.rs", 2, 2)
408                && !scope.touches("a.rs", 5, 5)
409        );
410        assert!(scope.touches("b.rs", 12345, 12345));
411    }
412
413    #[test]
414    fn indexed_positions_match_the_previous_scans() {
415        for row in include_str!("../tests/data/source-positions.pict.tsv")
416            .lines()
417            .skip(1)
418        {
419            let fields: Vec<_> = row.split('\t').collect();
420            let [text, newline, ending, query] = fields.as_slice() else {
421                panic!("invalid fixture row {row}");
422            };
423            let word = if *text == "unicode" { "é🦀" } else { "xyz" };
424            let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
425            let source = match *ending {
426                "empty" => String::new(),
427                "newline" => format!("{word}{newline}{word}{newline}"),
428                "none" => format!("{word}{newline}{word}"),
429                _ => panic!("invalid ending in {row}"),
430            };
431            let lines = LineIndex::new(&source);
432            for offset in 0..=source.len() + 1 {
433                assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
434                let prefix = source.get(..offset).unwrap_or(&source);
435                let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
436                assert_eq!(
437                    lines.position(&source, offset),
438                    (line_of(prefix, prefix.len()), column),
439                    "{row}"
440                );
441            }
442            let (line, column) = match *query {
443                "first" => (1, 1),
444                "boundary" => (2, 2),
445                "beyond" => (20, 99),
446                "zero" => (1, 0),
447                _ => panic!("invalid query in {row}"),
448            };
449            assert_eq!(
450                lines.offset_of(&source, line, column),
451                crate::instrument::offset_of(&source, line, column),
452                "{row}"
453            );
454        }
455    }
456
457    #[test]
458    fn long_ascii_prefix_before_multibyte_columns() {
459        let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
460        let lines = LineIndex::new(&source);
461        for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
462            assert_eq!(
463                lines.offset_of(&source, 2, column),
464                crate::instrument::offset_of(&source, 2, column)
465            );
466        }
467    }
468
469    #[test]
470    fn lines_of_offsets() {
471        let source = "a\nbc\n\nd";
472        assert_eq!(
473            [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
474            [1, 1, 2, 2, 3, 4, 4, 4]
475        );
476    }
477}