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        for hunk in hunks(diff) {
49            let range = if hunk.count == 0 {
50                // `+N,0`: lines were removed after line N.
51                (hunk.start.max(1), hunk.start + 1)
52            } else {
53                (hunk.start, hunk.start + hunk.count - 1)
54            };
55            scope.add(&hunk.file, range);
56        }
57        scope
58    }
59
60    pub fn add(&mut self, file: &str, range: (usize, usize)) {
61        self.files
62            .entry(file.replace('\\', "/"))
63            .or_default()
64            .push(range);
65    }
66
67    pub fn add_whole_file(&mut self, file: &str) {
68        self.add(file, (1, usize::MAX));
69    }
70
71    pub fn merge(&mut self, other: Scope) {
72        for (file, ranges) in other.files {
73            self.files.entry(file).or_default().extend(ranges);
74        }
75    }
76
77    pub fn is_empty(&self) -> bool {
78        self.files.is_empty()
79    }
80
81    pub fn files(&self) -> impl Iterator<Item = &str> {
82        self.files.keys().map(String::as_str)
83    }
84
85    /// Whether lines `first..=last` of `file` touch the scope.
86    pub fn touches(&self, file: &str, first: usize, last: usize) -> bool {
87        let ranges = self.files.get(file).or_else(|| {
88            if file.contains('\\') {
89                self.files.get(&file.replace('\\', "/"))
90            } else {
91                None
92            }
93        });
94        ranges.is_some_and(|ranges| {
95            ranges
96                .iter()
97                .any(|(from, to)| first <= *to && *from <= last)
98        })
99    }
100}
101
102/// One hunk of `git diff -U0`: where the new lines are, and the lines that were there.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Hunk {
105    /// Path relative to the workspace root, with `/` separators.
106    pub file: String,
107    /// The first new line (1-based); with no new lines, the line the old ones came after.
108    pub start: usize,
109    /// How many new lines there are.
110    pub count: usize,
111    /// The old lines, each with its line end (the last one without, if the old file
112    /// ended without one there).
113    pub old: String,
114}
115
116/// The hunks of the files that are still there. The lines of a hunk are counted as its
117/// header says, so a removed line that starts with `--` is not taken for a file header.
118pub fn hunks(diff: &str) -> Vec<Hunk> {
119    let mut found = Vec::new();
120    let mut file: Option<String> = None;
121    let mut lines = diff.split_inclusive('\n').peekable();
122    while let Some(line) = lines.next() {
123        let line = line.strip_suffix('\n').unwrap_or(line);
124        if let Some(path) = line.strip_prefix("+++ ") {
125            file = new_path(path);
126            continue;
127        }
128        let Some((old_count, start, count)) = hunk_header(line) else {
129            continue;
130        };
131        let mut old = String::new();
132        let (mut old_left, mut new_left) = (old_count, count);
133        while old_left + new_left > 0 {
134            let Some(body) = lines.next() else { break };
135            match body.as_bytes().first() {
136                Some(b'-') if old_left > 0 => {
137                    old.push_str(&body[1..]);
138                    old_left -= 1;
139                }
140                Some(b'+') if new_left > 0 => new_left -= 1,
141                Some(b' ') if old_left > 0 && new_left > 0 => {
142                    old.push_str(&body[1..]);
143                    old_left -= 1;
144                    new_left -= 1;
145                }
146                // `diff.suppressBlankEmpty=true` emits empty context lines without a leading space.
147                Some(b'\n' | b'\r') if old_left > 0 && new_left > 0 => {
148                    old.push_str(body);
149                    old_left -= 1;
150                    new_left -= 1;
151                }
152                _ => break,
153            }
154            if lines.peek().is_some_and(|next| next.starts_with('\\')) {
155                // `\ No newline at end of file`, about the line just read.
156                lines.next();
157                if body.starts_with('-') || body.starts_with(' ') {
158                    old.truncate(old.trim_end_matches(['\n', '\r']).len());
159                }
160            }
161        }
162        if let Some(file) = &file {
163            found.push(Hunk {
164                file: file.replace('\\', "/"),
165                start,
166                count,
167                old,
168            });
169        }
170    }
171    found
172}
173
174/// `@@ -a,b +c,d @@`: the count of old lines, the first new line and the count of new ones.
175fn hunk_header(line: &str) -> Option<(usize, usize, usize)> {
176    let mut parts = line.strip_prefix("@@ -")?.split(' ');
177    let pair = |text: &str| -> Option<(usize, usize)> {
178        let (start, count) = text.split_once(',').unwrap_or((text, "1"));
179        Some((start.parse().ok()?, count.parse().ok()?))
180    };
181    let (_, old_count) = pair(parts.next()?)?;
182    let (start, count) = pair(parts.next()?.strip_prefix('+')?)?;
183    Some((old_count, start, count))
184}
185
186/// The path of a `+++ ` line: `None` for `/dev/null`.
187fn new_path(path: &str) -> Option<String> {
188    // Git quotes a path with bytes outside printable ASCII, and puts a tab after one
189    // with a space.
190    // The tab also comes after the closing quote of a quoted path.
191    let path = path.strip_suffix('\t').unwrap_or(path);
192    let path = unquote(path).unwrap_or_else(|| path.to_string());
193    path.strip_prefix("b/").map(str::to_string)
194}
195
196/// Where the new lines of a hunk are in `text`, as a byte range: empty, at the place
197/// the old lines were, when the hunk has no new lines.
198pub fn range_of(text: &str, hunk: &Hunk) -> (usize, usize) {
199    // The offset where line `n` (1-based) starts; past the last line, the end.
200    let start_of = |line: usize| {
201        if line <= 1 {
202            return 0;
203        }
204        text.match_indices('\n')
205            .nth(line - 2)
206            .map_or(text.len(), |(at, _)| at + 1)
207    };
208    if hunk.count == 0 {
209        let at = start_of(hunk.start + 1);
210        (at, at)
211    } else {
212        (start_of(hunk.start), start_of(hunk.start + hunk.count))
213    }
214}
215
216/// `text` with the hunks undone: the old lines where the new ones are. The hunks are of
217/// this text and do not overlap. `None` when one of them does not fit the text.
218pub fn undo(text: &str, hunks: &[&Hunk]) -> Option<String> {
219    let mut ordered: Vec<&Hunk> = hunks.to_vec();
220    ordered.sort_by_key(|hunk| (hunk.start, hunk.count));
221    let mut out = String::with_capacity(text.len());
222    let mut done = 0;
223    for hunk in ordered {
224        let (from, to) = range_of(text, hunk);
225        if from < done || to > text.len() || (hunk.count > 0 && from == to) {
226            return None;
227        }
228        out.push_str(&text[done..from]);
229        // Old lines put after a last line that has no line end need one before them.
230        if from == to && from == text.len() && !text.is_empty() && !text.ends_with('\n') {
231            out.push('\n');
232        }
233        out.push_str(&hunk.old);
234        done = to;
235    }
236    out.push_str(&text[done..]);
237    Some(out)
238}
239
240/// The path git wrote between double quotes (`"b/src/\344\276\241.rs"`): C escapes, and
241/// three octal digits for each byte that is not printable ASCII. `None` for text that is
242/// not quoted that way.
243fn unquote(text: &str) -> Option<String> {
244    let inner = text.strip_prefix('"')?.strip_suffix('"')?;
245    let mut bytes = Vec::with_capacity(inner.len());
246    let mut rest = inner.bytes();
247    while let Some(byte) = rest.next() {
248        if byte == b'"' {
249            return None;
250        }
251        if byte != b'\\' {
252            bytes.push(byte);
253            continue;
254        }
255        bytes.push(match rest.next()? {
256            b'a' => 7,
257            b'b' => 8,
258            b't' => b'\t',
259            b'n' => b'\n',
260            b'v' => 11,
261            b'f' => 12,
262            b'r' => b'\r',
263            b'"' => b'"',
264            b'\\' => b'\\',
265            first @ b'0'..=b'3' => {
266                let mut value = u32::from(first - b'0');
267                for _ in 0..2 {
268                    let digit = rest.next().filter(|digit| (b'0'..=b'7').contains(digit))?;
269                    value = value * 8 + u32::from(digit - b'0');
270                }
271                u8::try_from(value).ok()?
272            }
273            _ => return None,
274        });
275    }
276    String::from_utf8(bytes).ok()
277}
278
279/// Byte offsets of the line starts in one source file.
280pub(crate) struct LineIndex(Vec<usize>);
281
282impl LineIndex {
283    pub(crate) fn new(source: &str) -> Self {
284        let bytes = source.as_bytes();
285        let mut starts = Vec::with_capacity(bytes.len() / 32 + 2);
286        starts.push(0);
287        push_newline_starts(bytes, &mut starts);
288        Self(starts)
289    }
290
291    pub(crate) fn line_of(&self, offset: usize) -> usize {
292        self.0.partition_point(|&start| start <= offset)
293    }
294
295    pub(crate) fn position(&self, source: &str, offset: usize) -> (usize, usize) {
296        let offset = if source.is_char_boundary(offset) {
297            offset
298        } else {
299            source.len()
300        };
301        let line = self.line_of(offset);
302        let column = source[self.0[line - 1]..offset].chars().count() + 1;
303        (line, column)
304    }
305
306    pub(crate) fn offset_of(&self, source: &str, line: usize, column: usize) -> Option<usize> {
307        // As in the unindexed lookup, out-of-range lines and columns clamp to EOF.
308        let start = self
309            .0
310            .get(line.checked_sub(1)?)
311            .copied()
312            .unwrap_or(source.len());
313        let column = column.checked_sub(1)?;
314        if column == 0 {
315            return Some(start);
316        }
317        let rest = &source[start..];
318        let capped = column.min(rest.len());
319        let within = if rest.as_bytes()[..capped].is_ascii() {
320            capped
321        } else {
322            rest.char_indices()
323                .nth(column)
324                .map_or(rest.len(), |(offset, _)| offset)
325        };
326        Some(start + within)
327    }
328}
329
330/// 1-based line of the byte at `offset`.
331pub fn line_of(source: &str, offset: usize) -> usize {
332    source.as_bytes()[..offset.min(source.len())]
333        .iter()
334        .filter(|b| **b == b'\n')
335        .count()
336        + 1
337}
338
339/// Appends `offset + 1` for every `b'\n'` byte in `bytes`, using NEON on `aarch64`
340/// and SSE2 on `x86_64` with a portable scalar tail/fallback.
341fn push_newline_starts(bytes: &[u8], out: &mut Vec<usize>) {
342    let mut i = 0usize;
343    let len = bytes.len();
344    #[cfg(target_arch = "aarch64")]
345    {
346        use std::arch::aarch64::*;
347        // SAFETY: NEON is mandatory on all aarch64 targets, and every load stays within `bytes[..len]`.
348        unsafe {
349            let nl = vdupq_n_u8(b'\n');
350            let bit_mask: uint8x16_t =
351                vld1q_u8([1u8, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128].as_ptr());
352            while i + 16 <= len {
353                let chunk = vld1q_u8(bytes.as_ptr().add(i));
354                let eq = vceqq_u8(chunk, nl);
355                if vmaxvq_u8(eq) != 0 {
356                    let masked = vandq_u8(eq, bit_mask);
357                    let lo = vaddv_u8(vget_low_u8(masked)) as u32;
358                    let hi = vaddv_u8(vget_high_u8(masked)) as u32;
359                    let mut bits = lo | (hi << 8);
360                    while bits != 0 {
361                        let tz = bits.trailing_zeros() as usize;
362                        out.push(i + tz + 1);
363                        bits &= bits - 1;
364                    }
365                }
366                i += 16;
367            }
368        }
369    }
370    #[cfg(target_arch = "x86_64")]
371    {
372        use std::arch::x86_64::*;
373        // SAFETY: SSE2 is mandatory on all x86_64 targets, and every load stays within `bytes[..len]`.
374        unsafe {
375            let nl = _mm_set1_epi8(b'\n' as i8);
376            while i + 16 <= len {
377                let chunk = _mm_loadu_si128(bytes.as_ptr().add(i).cast());
378                let eq = _mm_cmpeq_epi8(chunk, nl);
379                let mut bits = _mm_movemask_epi8(eq) as u32;
380                while bits != 0 {
381                    let tz = bits.trailing_zeros() as usize;
382                    out.push(i + tz + 1);
383                    bits &= bits - 1;
384                }
385                i += 16;
386            }
387        }
388    }
389    while i < len {
390        if bytes[i] == b'\n' {
391            out.push(i + 1);
392        }
393        i += 1;
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    fn specs(list: &[&str]) -> Vec<String> {
402        list.iter().map(|s| s.to_string()).collect()
403    }
404
405    #[test]
406    fn line_specs() {
407        let scope =
408            Scope::parse_lines(&specs(&["src/a.rs:10-20", "src/a.rs:30", "src/b.rs"])).unwrap();
409        // Inside, on both boundaries, overlapping, and outside.
410        assert!(scope.touches("src/a.rs", 12, 13));
411        assert!(scope.touches("src/a.rs", 1, 10));
412        assert!(scope.touches("src/a.rs", 20, 25));
413        assert!(scope.touches("src/a.rs", 5, 40));
414        assert!(scope.touches("src/a.rs", 30, 30));
415        assert!(!scope.touches("src/a.rs", 1, 9));
416        assert!(!scope.touches("src/a.rs", 21, 29));
417        assert!(!scope.touches("src/a.rs", 31, 99));
418        assert!(scope.touches("src/b.rs", 7, 7));
419        assert!(!scope.touches("src/c.rs", 7, 7));
420        assert!(
421            scope.touches("src\\b.rs", 1, 1),
422            "separators are normalised"
423        );
424        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs", "src/b.rs"]);
425        assert!(!scope.is_empty());
426        assert!(Scope::default().is_empty());
427
428        for bad in [
429            "src/a.rs:0",
430            "src/a.rs:5-3",
431            "src/a.rs:4-3",
432            "src/a.rs:1-x",
433            ":3",
434            "src/a.rs:3-",
435        ] {
436            assert!(Scope::parse_lines(&specs(&[bad])).is_err(), "{bad}");
437        }
438        // A Windows drive letter or a name with a colon is a file, not a range.
439        let odd = Scope::parse_lines(&specs(&["dir:name/a.rs"])).unwrap();
440        assert!(odd.touches("dir:name/a.rs", 1, 1));
441    }
442
443    #[test]
444    fn diff_hunks() {
445        let diff = "\
446diff --git a/src/a.rs b/src/a.rs
447index 111..222 100644
448--- a/src/a.rs
449+++ b/src/a.rs
450@@ -10,2 +10,3 @@ fn changed() {
451-old
452-old
453+new
454+new
455+new
456@@ -30 +31 @@
457-x
458+y
459@@ -40,3 +40,0 @@ fn deleted_lines() {
460-gone
461-gone
462-gone
463@@ -0,0 +1,2 @@
464+top
465+top
466diff --git a/src/gone.rs b/src/gone.rs
467deleted file mode 100644
468--- a/src/gone.rs
469+++ /dev/null
470@@ -1,5 +0,0 @@
471-all 1
472-all 2
473-all 3
474-all 4
475-all 5
476diff --git a/src/new.rs b/src/new.rs
477new file mode 100644
478--- /dev/null
479+++ b/src/new.rs
480@@ -0,0 +1,4 @@
481+fresh 1
482+fresh 2
483+fresh 3
484+fresh 4
485";
486        let scope = Scope::from_diff(diff);
487        // Changed: 10..=12. Single line: 31. Pure deletion after line 40: 40 and 41.
488        for (line, expected) in [
489            (9, false),
490            (10, true),
491            (12, true),
492            (13, false),
493            (31, true),
494            (32, false),
495            (39, false),
496            (40, true),
497            (41, true),
498            (42, false),
499            (1, true),
500            (2, true),
501            (3, false),
502        ] {
503            assert_eq!(
504                scope.touches("src/a.rs", line, line),
505                expected,
506                "line {line}"
507            );
508        }
509        assert!(
510            !scope.touches("src/gone.rs", 1, 100),
511            "a deleted file has no lines left"
512        );
513        assert!(scope.touches("src/new.rs", 4, 4));
514        assert!(!scope.touches("src/new.rs", 5, 5));
515        assert_eq!(Scope::from_diff(""), Scope::default());
516    }
517
518    #[test]
519    fn paths_are_read_as_git_writes_them() {
520        // A path with a space is followed by a tab; one with other bytes is quoted, with
521        // the prefix inside the quotes and octal for what is not ASCII.
522        let diff = "\
523--- a/src/two words.rs\t
524+++ b/src/two words.rs\t
525@@ -3 +3 @@
526-old
527+new
528--- \"a/src/\\344\\276\\241\\346\\240\\274.rs\"
529+++ \"b/src/\\344\\276\\241\\346\\240\\274.rs\"
530@@ -5 +5 @@
531-old
532+new
533--- \"a/src/a\\\"b\\\\c\\td e.rs\"
534+++ \"b/src/a\\\"b\\\\c\\td e.rs\"
535@@ -7 +7 @@
536-old
537+new
538--- a/src/価格.rs
539+++ b/src/価格.rs
540@@ -9 +9 @@
541-old
542+new
543--- \"a/src/gone \\303\\251.rs\"
544+++ /dev/null
545@@ -1 +0,0 @@
546-old
547--- \"a/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
548+++ \"b/src/\\344\\276\\241\\346\\240\\274 \\350\\241\\250.rs\"\t
549@@ -2 +2 @@
550-old
551+new
552";
553        let scope = Scope::from_diff(diff);
554        assert_eq!(
555            scope.files().collect::<Vec<_>>(),
556            [
557                // Stored with `/`, as every path is (a Windows separator).
558                "src/a\"b/c\td e.rs",
559                "src/two words.rs",
560                "src/価格 表.rs",
561                "src/価格.rs"
562            ]
563        );
564        // Quoted for its bytes and followed by a tab for its space.
565        assert!(scope.touches("src/価格 表.rs", 2, 2));
566        assert!(scope.touches("src/two words.rs", 3, 3));
567        // Quoted or not (`core.quotePath`), the same file.
568        assert!(scope.touches("src/価格.rs", 5, 5));
569        assert!(scope.touches("src/価格.rs", 9, 9));
570        assert!(scope.touches("src/a\"b\\c\td e.rs", 7, 7));
571    }
572
573    #[test]
574    fn a_quoted_path_is_what_its_escapes_spell() {
575        for (quoted, path) in [
576            (r#""plain""#, Some("plain")),
577            (r#""a\tb\nc\\d\"e""#, Some("a\tb\nc\\d\"e")),
578            (r#""\a\b\f\r\v""#, Some("\u{7}\u{8}\u{c}\r\u{b}")),
579            (r#""\343\201\202\101""#, Some("あA")),
580            // Not closed, an escape git does not write, octal cut short, bytes that
581            // are no text: nothing is guessed.
582            (r#""open"#, None),
583            (r#""a\qb""#, None),
584            (r#""\34""#, None),
585            (r#""\377""#, None),
586            (r#""a"b""#, None),
587            ("bare", None),
588        ] {
589            assert_eq!(unquote(quoted).as_deref(), path, "{quoted}");
590        }
591    }
592
593    /// The old and new text of one row of the table.
594    fn revert_case(row: &[&str]) -> (String, String) {
595        let [shape, position, old_newline, new_newline, hunks, dashes] = row else {
596            panic!("{row:?}")
597        };
598        let line = |name: &str| match *dashes {
599            "plain" => format!("{name}\n"),
600            _ => format!("-- {name}\n"),
601        };
602        let keep = |n: usize| format!("kept {n}\n");
603        let change = |old: &mut String, new: &mut String, tag: &str| match *shape {
604            "replace" => {
605                old.push_str(&line(&format!("old {tag}")));
606                new.push_str(&line(&format!("new {tag}")));
607            }
608            "add" => new.push_str(&line(&format!("new {tag}"))),
609            _ => old.push_str(&line(&format!("old {tag}"))),
610        };
611        let (mut old, mut new) = (String::new(), String::new());
612        let both = |old: &mut String, new: &mut String, text: String| {
613            old.push_str(&text);
614            new.push_str(&text);
615        };
616        let two = *hunks == "two";
617        match *position {
618            "first" => {
619                change(&mut old, &mut new, "a");
620                both(&mut old, &mut new, keep(1) + &keep(2));
621                if two {
622                    change(&mut old, &mut new, "b");
623                    both(&mut old, &mut new, keep(3));
624                }
625            }
626            "middle" => {
627                both(&mut old, &mut new, keep(1));
628                change(&mut old, &mut new, "a");
629                both(&mut old, &mut new, keep(2));
630            }
631            _ => {
632                if two {
633                    both(&mut old, &mut new, keep(0));
634                    change(&mut old, &mut new, "b");
635                }
636                both(&mut old, &mut new, keep(1) + &keep(2));
637                change(&mut old, &mut new, "a");
638            }
639        }
640        for (text, newline) in [(&mut old, old_newline), (&mut new, new_newline)] {
641            if *newline == "no" {
642                text.pop();
643            }
644        }
645        (old, new)
646    }
647
648    #[test]
649    fn undoing_the_hunks_of_a_diff_gives_the_old_text() {
650        let dir = std::env::temp_dir().join(format!("tmt-reverts-{}", std::process::id()));
651        std::fs::create_dir_all(&dir).unwrap();
652        let table = include_str!("../tests/data/reverts.pict.tsv");
653        let mut rows = 0;
654        for row in table.lines().skip(1) {
655            let row: Vec<&str> = row.split('\t').collect();
656            let (old, new) = revert_case(&row);
657            std::fs::write(dir.join("old"), &old).unwrap();
658            std::fs::write(dir.join("new"), &new).unwrap();
659            let output = std::process::Command::new("git")
660                .current_dir(&dir)
661                .args(["diff", "--no-index", "-U0", "--no-color", "--no-ext-diff"])
662                .args(["--src-prefix=a/", "--dst-prefix=b/", "old", "new"])
663                .output()
664                .unwrap();
665            let diff = String::from_utf8(output.stdout).unwrap();
666            let found = hunks(&diff);
667            // A line end that comes or goes at the end is a hunk of its own, or part of
668            // the one that changes the last line.
669            let changes = if row[4] == "two" { 2 } else { 1 };
670            assert!(
671                (changes..=changes + 1).contains(&found.len())
672                    || (found.len() == 1 && row[1] == "last"),
673                "{row:?}\n{diff}\n{found:?}"
674            );
675            assert!(found.iter().all(|hunk| hunk.file == "new"), "{found:?}");
676            let all: Vec<&Hunk> = found.iter().collect();
677            assert_eq!(
678                undo(&new, &all).as_deref(),
679                Some(old.as_str()),
680                "{row:?}\n{diff}"
681            );
682            // One hunk alone: the old lines there, the rest as it is now.
683            if let [first, second] = &found[..] {
684                let only_first = undo(&new, &[first]).unwrap();
685                let only_second = undo(&new, &[second]).unwrap();
686                assert_ne!(only_first, old, "{row:?}");
687                assert_ne!(only_first, new, "{row:?}");
688                assert_ne!(only_first, only_second, "{row:?}");
689            }
690            rows += 1;
691        }
692        std::fs::remove_dir_all(&dir).unwrap();
693        assert_eq!(rows, 23);
694    }
695
696    #[test]
697    fn a_hunk_that_does_not_fit_the_text_is_not_applied() {
698        let hunk = |start, count| Hunk {
699            file: "f".into(),
700            start,
701            count,
702            old: "old\n".into(),
703        };
704        assert_eq!(undo("a\nb\n", &[&hunk(2, 1)]).as_deref(), Some("a\nold\n"));
705        assert_eq!(
706            undo("a\nb\n", &[&hunk(0, 0)]).as_deref(),
707            Some("old\na\nb\n")
708        );
709        assert_eq!(
710            undo("a\nb\n", &[&hunk(2, 0)]).as_deref(),
711            Some("a\nb\nold\n")
712        );
713        assert_eq!(undo("a\nb", &[&hunk(2, 0)]).as_deref(), Some("a\nb\nold\n"));
714        // Lines the text does not have, and two hunks of the same lines.
715        assert_eq!(undo("a\nb\n", &[&hunk(3, 1)]), None);
716        assert_eq!(undo("a\nb\n", &[&hunk(1, 2), &hunk(2, 1)]), None);
717        assert_eq!(hunks("@@ nonsense @@\n@@ -1 +x @@\n"), []);
718        // A hunk before any file is of no file; one of a deleted file has no new lines.
719        assert_eq!(hunks("@@ -1 +1 @@\n-a\n+b\n"), []);
720        assert_eq!(hunks("--- a/f\n+++ /dev/null\n@@ -1 +0,0 @@\n-a\n"), []);
721    }
722
723    #[test]
724    fn merging_and_whole_files() {
725        let mut scope = Scope::parse_lines(&specs(&["a.rs:1-2"])).unwrap();
726        let mut other = Scope::default();
727        other.add_whole_file("b.rs");
728        other.add("a.rs", (9, 9));
729        scope.merge(other);
730        assert!(
731            scope.touches("a.rs", 9, 9)
732                && scope.touches("a.rs", 2, 2)
733                && !scope.touches("a.rs", 5, 5)
734        );
735        assert!(scope.touches("b.rs", 12345, 12345));
736    }
737
738    #[test]
739    fn indexed_positions_match_the_previous_scans() {
740        for row in include_str!("../tests/data/source-positions.pict.tsv")
741            .lines()
742            .skip(1)
743        {
744            let fields: Vec<_> = row.split('\t').collect();
745            let [text, newline, ending, query] = fields.as_slice() else {
746                panic!("invalid fixture row {row}");
747            };
748            let word = if *text == "unicode" { "é🦀" } else { "xyz" };
749            let newline = if *newline == "crlf" { "\r\n" } else { "\n" };
750            let source = match *ending {
751                "empty" => String::new(),
752                "newline" => format!("{word}{newline}{word}{newline}"),
753                "none" => format!("{word}{newline}{word}"),
754                _ => panic!("invalid ending in {row}"),
755            };
756            let lines = LineIndex::new(&source);
757            for offset in 0..=source.len() + 1 {
758                assert_eq!(lines.line_of(offset), line_of(&source, offset), "{row}");
759                let prefix = source.get(..offset).unwrap_or(&source);
760                let column = prefix.rsplit('\n').next().unwrap().chars().count() + 1;
761                assert_eq!(
762                    lines.position(&source, offset),
763                    (line_of(prefix, prefix.len()), column),
764                    "{row}"
765                );
766            }
767            let (line, column) = match *query {
768                "first" => (1, 1),
769                "boundary" => (2, 2),
770                "beyond" => (20, 99),
771                "zero" => (1, 0),
772                _ => panic!("invalid query in {row}"),
773            };
774            assert_eq!(
775                lines.offset_of(&source, line, column),
776                crate::instrument::offset_of(&source, line, column),
777                "{row}"
778            );
779        }
780    }
781
782    #[test]
783    fn long_ascii_prefix_before_multibyte_columns() {
784        let source = format!("start\r\n{}é🦀\n", "a".repeat(64_000));
785        let lines = LineIndex::new(&source);
786        for column in [0, 1, 64_000, 64_001, 64_002, 64_003, usize::MAX] {
787            assert_eq!(
788                lines.offset_of(&source, 2, column),
789                crate::instrument::offset_of(&source, 2, column)
790            );
791        }
792    }
793
794    #[test]
795    fn lines_of_offsets() {
796        let source = "a\nbc\n\nd";
797        assert_eq!(
798            [0, 1, 2, 4, 5, 6, 7, 99].map(|o| line_of(source, o)),
799            [1, 1, 2, 2, 3, 4, 4, 4]
800        );
801    }
802
803    #[test]
804    fn from_diff_ignores_header_like_lines_inside_hunk_body() {
805        let diff = "\
806diff --git a/src/a.rs b/src/a.rs
807--- a/src/a.rs
808+++ b/src/a.rs
809@@ -2,1 +3,3 @@
810--- a/src/fake.rs
811+let header = \"++\";
812+++ /dev/null
813+++ b/src/hijacked.rs
814@@ -10 +13 @@
815--- a/src/another.rs
816+++ b/src/another.rs
817@@ -20 +23 @@
818-old
819+new
820";
821        let scope = Scope::from_diff(diff);
822        assert_eq!(scope.files().collect::<Vec<_>>(), ["src/a.rs"]);
823        assert!(scope.touches("src/a.rs", 3, 5));
824        assert!(scope.touches("src/a.rs", 13, 13));
825        assert!(scope.touches("src/a.rs", 23, 23));
826        assert!(!scope.touches("src/hijacked.rs", 1, 100));
827        assert!(!scope.touches("src/another.rs", 1, 100));
828    }
829
830    #[test]
831    fn hunks_and_from_diff_handle_inter_hunk_context_from_git() {
832        let dir =
833            std::env::temp_dir().join(format!("tmt-inter-hunk-context-{}", std::process::id()));
834        let _ = std::fs::remove_dir_all(&dir);
835        std::fs::create_dir_all(&dir).unwrap();
836        let old = "line 1\nkeep A\nkeep B\nold tail\n";
837        let new = "line 1 changed\nkeep A\nkeep B\n++ b/hijacked.rs\n";
838        std::fs::write(dir.join("a.rs"), old).unwrap();
839        std::fs::write(dir.join("b.rs"), new).unwrap();
840        let output = std::process::Command::new("git")
841            .current_dir(&dir)
842            .args([
843                "-c",
844                "diff.interHunkContext=10",
845                "diff",
846                "--no-index",
847                "-U0",
848                "--no-color",
849                "--no-ext-diff",
850                "--src-prefix=a/",
851                "--dst-prefix=b/",
852                "a.rs",
853                "b.rs",
854            ])
855            .output()
856            .unwrap();
857        let diff = String::from_utf8(output.stdout).unwrap();
858        assert!(
859            diff.contains("\n keep A\n"),
860            "expected context line:\n{diff}"
861        );
862        let scope = Scope::from_diff(&diff);
863        assert_eq!(scope.files().collect::<Vec<_>>(), ["b.rs"]);
864        assert!(scope.touches("b.rs", 1, 4));
865        assert!(!scope.touches("hijacked.rs", 1, 100));
866        let parsed = hunks(&diff);
867        assert_eq!(parsed.len(), 1, "{parsed:?}");
868        assert_eq!(undo(new, &[&parsed[0]]).as_deref(), Some(old));
869
870        // `diff.suppressBlankEmpty=true` omits the leading space on blank context lines.
871        let old_blank = "line 1\n\nold tail\n";
872        let new_blank = "line 1 changed\n\n++ b/hijacked.rs\n";
873        std::fs::write(dir.join("c.rs"), old_blank).unwrap();
874        std::fs::write(dir.join("d.rs"), new_blank).unwrap();
875        let output = std::process::Command::new("git")
876            .current_dir(&dir)
877            .args([
878                "-c",
879                "diff.interHunkContext=10",
880                "-c",
881                "diff.suppressBlankEmpty=true",
882                "diff",
883                "--no-index",
884                "-U0",
885                "--no-color",
886                "--no-ext-diff",
887                "--src-prefix=a/",
888                "--dst-prefix=b/",
889                "c.rs",
890                "d.rs",
891            ])
892            .output()
893            .unwrap();
894        let diff = String::from_utf8(output.stdout).unwrap();
895        assert!(
896            diff.contains("\n\n"),
897            "expected bare blank context line:\n{diff}"
898        );
899        let parsed = hunks(&diff);
900        assert_eq!(parsed.len(), 1, "{parsed:?}");
901        assert_eq!(undo(new_blank, &[&parsed[0]]).as_deref(), Some(old_blank));
902        std::fs::remove_dir_all(&dir).unwrap();
903    }
904
905    #[test]
906    fn simd_line_index_matches_scalar_across_chunk_boundaries() {
907        let scalar = |source: &str| -> Vec<usize> {
908            std::iter::once(0)
909                .chain(
910                    source
911                        .bytes()
912                        .enumerate()
913                        .filter(|&(_, b)| b == b'\n')
914                        .map(|(i, _)| i + 1),
915                )
916                .collect()
917        };
918        for len in 0..=66 {
919            let mut buf = "a".repeat(len);
920            assert_eq!(LineIndex::new(&buf).0, scalar(&buf), "no-nl len={len}");
921            if len > 0 {
922                // Place a newline at every position to test lane 0..15 boundaries.
923                for pos in [0, len / 2, len - 1] {
924                    buf.replace_range(pos..pos + 1, "\n");
925                    assert_eq!(LineIndex::new(&buf).0, scalar(&buf), "len={len} pos={pos}");
926                    buf.replace_range(pos..pos + 1, "a");
927                }
928            }
929        }
930        let all_nl = "\n".repeat(35);
931        assert_eq!(LineIndex::new(&all_nl).0, scalar(&all_nl));
932        let mixed = "猫\r\nαβγ\n".repeat(12);
933        assert_eq!(LineIndex::new(&mixed).0, scalar(&mixed));
934    }
935}