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