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.
52                file = path.strip_prefix("b/").map(str::to_string);
53            } else if line.starts_with("@@ ")
54                && let Some(file) = &file
55                && let Some(added) = line.split(' ').find_map(|part| part.strip_prefix('+'))
56            {
57                let (start, count) = added.split_once(',').unwrap_or((added, "1"));
58                let (Ok(start), Ok(count)) = (start.parse::<usize>(), count.parse::<usize>())
59                else {
60                    continue;
61                };
62                let range = if count == 0 {
63                    // `+N,0`: lines were removed after line N.
64                    (start.max(1), start + 1)
65                } else {
66                    (start, start + count - 1)
67                };
68                scope.add(file, range);
69            }
70        }
71        scope
72    }
73
74    pub fn add(&mut self, file: &str, range: (usize, usize)) {
75        self.files
76            .entry(file.replace('\\', "/"))
77            .or_default()
78            .push(range);
79    }
80
81    pub fn add_whole_file(&mut self, file: &str) {
82        self.add(file, (1, usize::MAX));
83    }
84
85    pub fn merge(&mut self, other: Scope) {
86        for (file, ranges) in other.files {
87            self.files.entry(file).or_default().extend(ranges);
88        }
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.files.is_empty()
93    }
94
95    pub fn files(&self) -> impl Iterator<Item = &str> {
96        self.files.keys().map(String::as_str)
97    }
98
99    /// Whether lines `first..=last` of `file` touch the scope.
100    pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
101        let ranges = self.files.get(file).or_else(|| {
102            if file.contains('\\') {
103                self.files.get(&file.replace('\\', "/"))
104            } else {
105                None
106            }
107        });
108        ranges.is_some_and(|ranges| {
109            ranges
110                .iter()
111                .any(|(from, to)| first <= *to && *from <= last)
112        })
113    }
114}
115
116/// Byte offsets of the line starts in one source file.
117pub(crate) struct LineIndex(Vec<usize>);
118
119impl LineIndex {
120    pub(crate) fn new(source: &str) -> Self {
121        Self(
122            std::iter::once(0)
123                .chain(
124                    source
125                        .bytes()
126                        .enumerate()
127                        .filter(|&(_, byte)| byte == b'\n')
128                        .map(|(offset, _)| offset + 1),
129                )
130                .collect(),
131        )
132    }
133
134    pub(crate) fn line_of(&self, offset: usize) -> usize {
135        self.0.partition_point(|&start| start <= offset)
136    }
137
138    pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
139        let offset = if source.is_char_boundary(offset) {
140            offset
141        } else {
142            source.len()
143        };
144        let line = self.line_of(offset);
145        let column = source[self.0[line - 1]..offset].chars().count() + 1;
146        (line, column)
147    }
148
149    pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
150        // As in the unindexed lookup, out-of-range lines and columns clamp to EOF.
151        let start = self
152            .0
153            .get(line.checked_sub(1)?)
154            .copied()
155            .unwrap_or(source.len());
156        let column = column.checked_sub(1)?;
157        if column == 0 {
158            return Some(start);
159        }
160        let rest = &source[start..];
161        let capped = column.min(rest.len());
162        let within = if rest.as_bytes()[..capped].is_ascii() {
163            capped
164        } else {
165            rest.char_indices()
166                .nth(column)
167                .map_or(rest.len(), |(offset, _)| offset)
168        };
169        Some(start + within)
170    }
171}
172
173/// 1-based line of the byte at `offset`.
174pub fn line_of(source: &str, offset: usize) -> usize {
175    source.as_bytes()[..offset.min(source.len())]
176        .iter()
177        .filter(|b| **b == b'\n')
178        .count()
179        + 1
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    fn specs(list: &[&str]) -> Vec<String> {
187        list.iter().map(|s| s.to_string()).collect()
188    }
189
190    #[test]
191    fn line_specs() {
192        let scope =
193            Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
194        // Inside, on both boundaries, overlapping, and outside.
195        assert!(scope.touches("src/a.rs", 12, 13));
196        assert!(scope.touches("src/a.rs", 1, 10));
197        assert!(scope.touches("src/a.rs", 20, 25));
198        assert!(scope.touches("src/a.rs", 5, 40));
199        assert!(scope.touches("src/a.rs", 30, 30));
200        assert!(!scope.touches("src/a.rs", 1, 9));
201        assert!(!scope.touches("src/a.rs", 21, 29));
202        assert!(!scope.touches("src/a.rs", 31, 99));
203        assert!(scope.touches("src/b.rs", 7, 7));
204        assert!(!scope.touches("src/c.rs", 7, 7));
205        assert!(
206            scope.touches("src\\b.rs", 1, 1),
207            "separators are normalised"
208        );
209        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
210        assert!(!scope.is_empty());
211        assert!(Scope::default().is_empty());
212
213        for bad in [
214            "src/a.rs:0",
215            "src/a.rs:5-3",
216            "src/a.rs:4-3",
217            "src/a.rs:1-x",
218            ":3",
219            "src/a.rs:3-",
220        ] {
221            assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
222        }
223        // A Windows drive letter or a name with a colon is a file, not a range.
224        let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
225        assert!(odd.touches("dir:name/a.rs", 1, 1));
226    }
227
228    #[test]
229    fn diff_hunks() {
230        let diff = "\
231diff --git a/src/a.rs b/src/a.rs
232index 111..222 100644
233--- a/src/a.rs
234+++ b/src/a.rs
235@@ -10,2 +10,3 @@ fn changed() {
236-old
237-old
238+new
239+new
240+new
241@@ -30 +31 @@
242-x
243+y
244@@ -40,3 +40,0 @@ fn deleted_lines() {
245-gone
246-gone
247-gone
248@@ -0,0 +1,2 @@
249+top
250+top
251diff --git a/src/gone.rs b/src/gone.rs
252deleted file mode 100644
253--- a/src/gone.rs
254+++ /dev/null
255@@ -1,5 +0,0 @@
256-all
257diff --git a/src/new.rs b/src/new.rs
258new file mode 100644
259--- /dev/null
260+++ b/src/new.rs
261@@ -0,0 +1,4 @@
262+fresh
263";
264        let scope = Scope::from_diff(diff);
265        // Changed: 10..=12. Single line: 31. Pure deletion after line 40: 40 and 41.
266        for (line, expected) in [
267            (9, false),
268            (10, true),
269            (12, true),
270            (13, false),
271            (31, true),
272            (32, false),
273            (39, false),
274            (40, true),
275            (41, true),
276            (42, false),
277            (1, true),
278            (2, true),
279            (3, false),
280        ] {
281            assert_eq!(
282                scope.touches("src/a.rs", line, line),
283                expected,
284                "line {line}"
285            );
286        }
287        assert!(
288            !scope.touches("src/gone.rs", 1, 100),
289            "a deleted file has no lines left"
290        );
291        assert!(scope.touches("src/new.rs", 4, 4));
292        assert!(!scope.touches("src/new.rs", 5, 5));
293        assert_eq!(Scope::from_diff(""), Scope::default());
294    }
295
296    #[test]
297    fn merging_and_whole_files() {
298        let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
299        let mut other = Scope::default();
300        other.add_whole_file("b.rs");
301        other.add("a.rs", (9, 9));
302        scope.merge(other);
303        assert!(
304            scope.touches("a.rs", 9, 9)
305                && scope.touches("a.rs", 2, 2)
306                && !scope.touches("a.rs", 5, 5)
307        );
308        assert!(scope.touches("b.rs", 12345, 12345));
309    }
310
311    #[test]
312    fn indexed_positions_match_the_previous_scans() {
313        for row in include_str!("../tests/data/source-positions.pict.tsv")
314            .lines()
315            .skip(1)
316        {
317            let fields: Vec<_> = row.split('\t').collect();
318            let [text, newline, ending, query] = fields.as_slice() else {
319                panic!("invalid fixture row {row}");
320            };
321            let word = if *text == "unicode" { "é🦀" } else { "xyz" };
322            let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
323            let source = match *ending {
324                "empty" => String::new(),
325                "newline" => format!("{word}{newline}{word}{newline}"),
326                "none" => format!("{word}{newline}{word}"),
327                _ => panic!("invalid ending in {row}"),
328            };
329            let lines = LineIndex::new(&source);
330            for offset in 0..=source.len() + 1 {
331                assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
332                let prefix = source.get(..offset).unwrap_or(&source);
333                let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
334                assert_eq!(
335                    lines.position(&source, offset),
336                    (line_of(prefix, prefix.len()), column),
337                    "{row}"
338                );
339            }
340            let (line, column) = match *query {
341                "first" => (1, 1),
342                "boundary" => (2, 2),
343                "beyond" => (20, 99),
344                "zero" => (1, 0),
345                _ => panic!("invalid query in {row}"),
346            };
347            assert_eq!(
348                lines.offset_of(&source, line, column),
349                crate::instrument::offset_of(&source, line, column),
350                "{row}"
351            );
352        }
353    }
354
355    #[test]
356    fn long_ascii_prefix_before_multibyte_columns() {
357        let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
358        let lines = LineIndex::new(&source);
359        for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
360            assert_eq!(
361                lines.offset_of(&source, 2, column),
362                crate::instrument::offset_of(&source, 2, column)
363            );
364        }
365    }
366
367    #[test]
368    fn lines_of_offsets() {
369        let source = "a\nbc\n\nd";
370        assert_eq!(
371            [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
372            [1, 1, 2, 2, 3, 4, 4, 4]
373        );
374    }
375}