Skip to main content

rustaco_core/
diff.rs

1//! Line diff with a char-level pass inside changed lines.
2//!
3//! Lines are compared as interned ids (optionally ignoring whitespace) with Myers' O(ND)
4//! algorithm in linear space (bisection at the middle snake, as diff-match-patch does), after
5//! trimming the common prefix and suffix. When `keep_going` says to stop, the rest of the
6//! input is reported as one replaced block, so a huge input still yields a usable, coarser
7//! diff. Inside each changed block both sides are diffed again by chars, and deleted blocks
8//! that reappear unchanged elsewhere are paired up as moves.
9
10use std::collections::HashMap;
11use std::ops::Range;
12
13use ropey::Rope;
14
15/// One changed block: lines `old` were replaced by lines `new` (either may be empty).
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct LineChange {
18    pub old: Range<usize>,
19    pub new: Range<usize>,
20    /// Char ranges (offsets into each text) that differ inside the block.
21    pub inner: Vec<CharChange>,
22    /// The index of the change this block moved to or from, when its lines reappear
23    /// unchanged elsewhere.
24    pub moved: Option<usize>,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct CharChange {
29    pub old: Range<usize>,
30    pub new: Range<usize>,
31}
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct Diff {
35    pub changes: Vec<LineChange>,
36    /// False when the time budget ran out and part of the result is coarse.
37    pub complete: bool,
38}
39
40#[derive(Clone, Copy, Debug, Default)]
41pub struct DiffOptions {
42    /// Lines that differ only in whitespace count as equal.
43    pub ignore_whitespace: bool,
44}
45
46/// Blocks with more chars than this on a side skip the char-level pass.
47const MAX_INNER_CHARS: usize = 20_000;
48
49/// Moved blocks must have at least this many lines.
50const MIN_MOVED_LINES: usize = 3;
51
52/// Diffs two texts by lines, then by chars inside changed blocks. `keep_going` is asked
53/// now and then; once it returns false the remaining work is done coarsely.
54pub fn diff(old: &Rope, new: &Rope, options: DiffOptions, keep_going: &mut dyn FnMut() -> bool) -> Diff {
55    let mut ids: HashMap<String, u32> = HashMap::new();
56    let mut intern = |rope: &Rope| -> Vec<u32> {
57        rope.lines()
58            .map(|line| {
59                let mut s: String = line.chars().filter(|c| *c != '\n' && *c != '\r').collect();
60                if options.ignore_whitespace {
61                    s = s.split_whitespace().collect::<Vec<_>>().join(" ");
62                }
63                let next = ids.len() as u32;
64                *ids.entry(s).or_insert(next)
65            })
66            .collect()
67    };
68    let a = intern(old);
69    let b = intern(new);
70    let mut ops = Vec::new();
71    let mut complete = true;
72    myers(&a, &b, 0, 0, &mut ops, keep_going, &mut complete);
73    let mut changes = blocks(&ops, a.len(), b.len());
74    for c in &mut changes {
75        if !c.old.is_empty() && !c.new.is_empty() {
76            c.inner = inner(old, new, c, keep_going, &mut complete);
77        }
78    }
79    pair_moves(&mut changes, &a, &b);
80    Diff { changes, complete }
81}
82
83/// An edit op on line indexes: (old start, old len, new start, new len) of a replaced run.
84type Op = (usize, usize, usize, usize);
85
86fn myers(
87    a: &[u32],
88    b: &[u32],
89    ao: usize,
90    bo: usize,
91    ops: &mut Vec<Op>,
92    keep_going: &mut dyn FnMut() -> bool,
93    complete: &mut bool,
94) {
95    // Common prefix and suffix.
96    let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
97    let (a, b) = (&a[prefix..], &b[prefix..]);
98    let (ao, bo) = (ao + prefix, bo + prefix);
99    let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();
100    let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);
101    if a.is_empty() && b.is_empty() {
102        return;
103    }
104    if a.is_empty() || b.is_empty() {
105        ops.push((ao, a.len(), bo, b.len()));
106        return;
107    }
108    if !*complete || !keep_going() {
109        *complete = false;
110        ops.push((ao, a.len(), bo, b.len()));
111        return;
112    }
113    match bisect(a, b, keep_going) {
114        Some((x, y)) => {
115            myers(&a[..x], &b[..y], ao, bo, ops, keep_going, complete);
116            myers(&a[x..], &b[y..], ao + x, bo + y, ops, keep_going, complete);
117        }
118        None => ops.push((ao, a.len(), bo, b.len())),
119    }
120}
121
122/// The middle snake of the edit graph: a split point (x, y) such that diffing the halves
123/// separately gives a shortest edit script. None when the sides share nothing (or time ran
124/// out), which means "replace everything".
125fn bisect(a: &[u32], b: &[u32], keep_going: &mut dyn FnMut() -> bool) -> Option<(usize, usize)> {
126    let (n, m) = (a.len() as isize, b.len() as isize);
127    let max_d = (n + m + 1) / 2;
128    let offset = max_d;
129    let len = (2 * max_d + 2) as usize;
130    let mut v1 = vec![-1isize; len];
131    let mut v2 = vec![-1isize; len];
132    v1[(offset + 1) as usize] = 0;
133    v2[(offset + 1) as usize] = 0;
134    let delta = n - m;
135    let front = delta % 2 != 0;
136    let (mut k1start, mut k1end, mut k2start, mut k2end) = (0, 0, 0, 0);
137    for d in 0..max_d {
138        if d % 64 == 63 && !keep_going() {
139            return None;
140        }
141        let mut k1 = -d + k1start;
142        while k1 <= d - k1end {
143            let k1o = (offset + k1) as usize;
144            let mut x1 = if k1 == -d || (k1 != d && v1[k1o - 1] < v1[k1o + 1]) { v1[k1o + 1] } else { v1[k1o - 1] + 1 };
145            let mut y1 = x1 - k1;
146            while x1 < n && y1 < m && a[x1 as usize] == b[y1 as usize] {
147                x1 += 1;
148                y1 += 1;
149            }
150            v1[k1o] = x1;
151            if x1 > n {
152                k1end += 2;
153            } else if y1 > m {
154                k1start += 2;
155            } else if front {
156                let k2o = offset + delta - k1;
157                if k2o >= 0 && (k2o as usize) < len && v2[k2o as usize] != -1 {
158                    let x2 = n - v2[k2o as usize];
159                    if x1 >= x2 {
160                        return Some((x1 as usize, y1 as usize));
161                    }
162                }
163            }
164            k1 += 2;
165        }
166        let mut k2 = -d + k2start;
167        while k2 <= d - k2end {
168            let k2o = (offset + k2) as usize;
169            let mut x2 = if k2 == -d || (k2 != d && v2[k2o - 1] < v2[k2o + 1]) { v2[k2o + 1] } else { v2[k2o - 1] + 1 };
170            let mut y2 = x2 - k2;
171            while x2 < n && y2 < m && a[(n - x2 - 1) as usize] == b[(m - y2 - 1) as usize] {
172                x2 += 1;
173                y2 += 1;
174            }
175            v2[k2o] = x2;
176            if x2 > n {
177                k2end += 2;
178            } else if y2 > m {
179                k2start += 2;
180            } else if !front {
181                let k1o = offset + delta - k2;
182                if k1o >= 0 && (k1o as usize) < len && v1[k1o as usize] != -1 {
183                    let x1 = v1[k1o as usize];
184                    let y1 = offset + x1 - k1o;
185                    if x1 >= n - x2 {
186                        return Some((x1 as usize, y1 as usize));
187                    }
188                }
189            }
190            k2 += 2;
191        }
192    }
193    None
194}
195
196/// Merges adjacent ops into changed blocks, sorted.
197fn blocks(ops: &[Op], _old_len: usize, _new_len: usize) -> Vec<LineChange> {
198    let mut sorted = ops.to_vec();
199    sorted.sort_by_key(|o| (o.0, o.2));
200    let mut out: Vec<LineChange> = Vec::new();
201    for (ao, al, bo, bl) in sorted {
202        match out.last_mut() {
203            Some(last) if last.old.end == ao && last.new.end == bo => {
204                last.old.end = ao + al;
205                last.new.end = bo + bl;
206            }
207            _ => out.push(LineChange { old: ao..ao + al, new: bo..bo + bl, inner: Vec::new(), moved: None }),
208        }
209    }
210    out
211}
212
213/// The char-level differences inside a changed block.
214fn inner(
215    old: &Rope,
216    new: &Rope,
217    c: &LineChange,
218    keep_going: &mut dyn FnMut() -> bool,
219    complete: &mut bool,
220) -> Vec<CharChange> {
221    let span = |rope: &Rope, lines: &Range<usize>| {
222        rope.line_to_char(lines.start)..rope.line_to_char(lines.end.min(rope.len_lines()))
223    };
224    let (os, ns) = (span(old, &c.old), span(new, &c.new));
225    if os.len() > MAX_INNER_CHARS || ns.len() > MAX_INNER_CHARS {
226        return vec![CharChange { old: os, new: ns }];
227    }
228    let a: Vec<u32> = old.slice(os.clone()).chars().map(|ch| ch as u32).collect();
229    let b: Vec<u32> = new.slice(ns.clone()).chars().map(|ch| ch as u32).collect();
230    let mut ops = Vec::new();
231    myers(&a, &b, 0, 0, &mut ops, keep_going, complete);
232    let mut merged = blocks(&ops, a.len(), b.len());
233    // Equal runs of one or two chars between changes read as noise: join across them.
234    let mut joined: Vec<LineChange> = Vec::new();
235    for ch in merged.drain(..) {
236        match joined.last_mut() {
237            Some(last) if ch.old.start - last.old.end <= 2 && ch.new.start - last.new.end <= 2 => {
238                last.old.end = ch.old.end;
239                last.new.end = ch.new.end;
240            }
241            _ => joined.push(ch),
242        }
243    }
244    joined
245        .into_iter()
246        .map(|ch| CharChange {
247            old: os.start + ch.old.start..os.start + ch.old.end,
248            new: ns.start + ch.new.start..ns.start + ch.new.end,
249        })
250        .collect()
251}
252
253/// Pairs pure deletions with pure insertions of the same lines (moves).
254fn pair_moves(changes: &mut [LineChange], a: &[u32], b: &[u32]) {
255    let mut inserted: HashMap<&[u32], usize> = HashMap::new();
256    for (i, c) in changes.iter().enumerate() {
257        if c.old.is_empty() && c.new.len() >= MIN_MOVED_LINES {
258            inserted.entry(&b[c.new.clone()]).or_insert(i);
259        }
260    }
261    let mut pairs = Vec::new();
262    for (i, c) in changes.iter().enumerate() {
263        if c.new.is_empty()
264            && c.old.len() >= MIN_MOVED_LINES
265            && let Some(&j) = inserted.get(&a[c.old.clone()])
266        {
267            pairs.push((i, j));
268            inserted.remove(&a[c.old.clone()]);
269        }
270    }
271    for (i, j) in pairs {
272        changes[i].moved = Some(j);
273        changes[j].moved = Some(i);
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    fn d(a: &str, b: &str) -> Diff {
282        diff(&Rope::from_str(a), &Rope::from_str(b), DiffOptions::default(), &mut || true)
283    }
284
285    /// Applies the line changes to `a` and checks the result is `b`.
286    fn check(a: &str, b: &str) {
287        let diff = d(a, b);
288        apply(a, b, &diff);
289    }
290
291    fn apply(a: &str, b: &str, diff: &Diff) {
292        let al: Vec<&str> = a.split_inclusive('\n').collect();
293        let bl: Vec<&str> = b.split_inclusive('\n').collect();
294        let mut out: Vec<&str> = Vec::new();
295        let mut at = 0;
296        for c in &diff.changes {
297            out.extend(&al[at..c.old.start.min(al.len())]);
298            out.extend(&bl[c.new.start.min(bl.len())..c.new.end.min(bl.len())]);
299            at = c.old.end.min(al.len());
300        }
301        out.extend(&al[at.min(al.len())..]);
302        assert_eq!(out.concat(), b, "diff of {a:?} -> {b:?}: {:?}", diff.changes);
303    }
304
305    #[test]
306    fn line_changes_rebuild_the_new_text() {
307        check("a\nb\nc\n", "a\nx\nc\n");
308        check("a\nb\nc\n", "a\nc\n");
309        check("a\nc\n", "a\nb\nc\n");
310        check("", "x\ny\n");
311        check("x\ny\n", "");
312        check("1\n2\n3\n4\n5\n6\n", "0\n2\n3\nx\n5\n6\n7\n");
313    }
314
315    #[test]
316    fn random_texts_round_trip() {
317        let mut seed = 0x7a3c_51d2_u64;
318        let mut rand = move |n: usize| {
319            seed ^= seed << 13;
320            seed ^= seed >> 7;
321            seed ^= seed << 17;
322            (seed % n as u64) as usize
323        };
324        for _ in 0..200 {
325            let a: String = (0..rand(30)).map(|_| format!("{}\n", rand(6))).collect();
326            let b: String = (0..rand(30)).map(|_| format!("{}\n", rand(6))).collect();
327            check(&a, &b);
328        }
329    }
330
331    #[test]
332    fn chars_inside_a_changed_line_and_whitespace() {
333        let lines = d("let value = 1;\n", "let total = 1;\n");
334        assert_eq!(lines.changes.len(), 1);
335        assert_eq!(lines.changes[0].inner, vec![CharChange { old: 4..9, new: 4..9 }]);
336        let ws = diff(
337            &Rope::from_str("a  b\n"),
338            &Rope::from_str("a b\n"),
339            DiffOptions { ignore_whitespace: true },
340            &mut || true,
341        );
342        assert!(ws.changes.is_empty());
343    }
344
345    #[test]
346    fn moved_blocks_are_paired() {
347        let a = "m1\nm2\nm3\nv\nw\nx\ny\nz\n";
348        let b = "v\nw\nx\ny\nz\nm1\nm2\nm3\n";
349        let diff = d(a, b);
350        let moved: Vec<Option<usize>> = diff.changes.iter().map(|c| c.moved).collect();
351        assert!(moved.iter().all(Option::is_some), "{:?}", diff.changes);
352    }
353
354    #[test]
355    fn a_stop_gives_a_coarse_but_correct_diff() {
356        let a: String = (0..2000).map(|i| format!("{i}\n")).collect();
357        let b: String = (0..2000).map(|i| if i % 7 == 0 { "x\n".to_owned() } else { format!("{i}\n") }).collect();
358        let mut calls = 0;
359        let coarse = diff(&Rope::from_str(&a), &Rope::from_str(&b), DiffOptions::default(), &mut || {
360            calls += 1;
361            calls < 3
362        });
363        assert!(!coarse.complete);
364        // Coarser, but it still turns one text into the other.
365        apply(&a, &b, &coarse);
366    }
367}