crates/diff/src/word.rs 16.8 KiB raw
1
//! Per-pair intra-line word diff.
2
//!
3
//! Walks each hunk's change blocks (consecutive `-`/`+` runs separated by
4
//! context lines) and pairs the i-th deletion with the i-th addition in the
5
//! same block. For each pair, the line texts are tokenized and an LCS is
6
//! computed to find the byte ranges that differ between them.
7
//!
8
//! A similarity gate filters out pairs whose lines share too few tokens --
9
//! those are two distinct edits that happen to be adjacent, not two versions
10
//! of the same line. Highlighting their internal differences only produces
11
//! noise, so the overlay is suppressed and the dim row tint stands alone.
12
//!
13
//! The same gate naturally handles pure-addition and pure-deletion runs:
14
//! no pairs form, so no overlay is emitted.
15
16
use std::collections::BTreeMap;
17
use std::ops::Range;
18
19
use crate::{DiffLine, DiffLineKind, Hunk, RowId};
20
21
/// Numerator of the minimum LCS-match ratio. A pair must match at least
22
/// `SIMILARITY_NUMERATOR / SIMILARITY_DENOMINATOR` of the longer line's
23
/// tokens or it is treated as two unrelated edits and skipped.
24
const SIMILARITY_NUMERATOR: usize = 1;
25
/// Denominator of the minimum LCS-match ratio. See [`SIMILARITY_NUMERATOR`].
26
const SIMILARITY_DENOMINATOR: usize = 2;
27
28
/// Byte ranges per row that mark changed spans inside a hunk.
29
pub type WordChanges = BTreeMap<RowId, Vec<Range<usize>>>;
30
31
/// A single token taken from one diff line.
32
#[derive(Clone, Debug, Eq, PartialEq)]
33
struct Token<'a> {
34
    /// Row this token came from.
35
    row: RowId,
36
    /// Byte range within the row's text.
37
    range: Range<usize>,
38
    /// Category used for similarity checks.
39
    class: Class,
40
    /// Token text (a slice of the row's text).
41
    text: &'a str,
42
}
43
44
/// One dynamic-programming cell for the token LCS.
45
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
46
struct Cell {
47
    /// Length of the best LCS ending at this cell.
48
    len: u32,
49
    /// Whether that LCS contains at least one relevant token.
50
    is_relevant: bool,
51
}
52
53
/// Token category, used to decide where a token boundary falls.
54
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55
enum Class {
56
    /// Run of `[A-Za-z0-9_]`.
57
    Ident,
58
    /// Run of `' '` or `'\t'`.
59
    Space,
60
    /// Any other character (one per token).
61
    Other,
62
}
63
64
impl Class {
65
    /// Classifies one character.
66
    fn of(ch: char) -> Self {
67
        if ch.is_ascii_alphanumeric() || ch == '_' {
68
            Self::Ident
69
        } else if ch == ' ' || ch == '\t' {
70
            Self::Space
71
        } else {
72
            Self::Other
73
        }
74
    }
75
76
    /// Returns whether this class can anchor a meaningful word-diff pair.
77
    fn is_relevant(self) -> bool {
78
        matches!(self, Self::Ident)
79
    }
80
}
81
82
/// Iterator over tokens in one diff line's text.
83
struct Tokens<'a> {
84
    /// Row identifier carried into each yielded token.
85
    row: RowId,
86
    /// Full line text being tokenized.
87
    text: &'a str,
88
    /// Byte cursor into the line text.
89
    cursor: usize,
90
}
91
92
impl<'a> Iterator for Tokens<'a> {
93
    type Item = Token<'a>;
94
95
    fn next(&mut self) -> Option<Self::Item> {
96
        let rest = self.text.get(self.cursor..)?;
97
        let mut chars = rest.char_indices();
98
        let (_, first) = chars.next()?;
99
        let class = Class::of(first);
100
        let end_local = if matches!(class, Class::Ident | Class::Space) {
101
            chars
102
                .find(|(_, ch)| Class::of(*ch) != class)
103
                .map_or(rest.len(), |(i, _)| i)
104
        } else {
105
            first.len_utf8()
106
        };
107
        let start = self.cursor;
108
        let end = self.cursor + end_local;
109
        self.cursor = end;
110
111
        Some(Token {
112
            row: self.row,
113
            range: start..end,
114
            class,
115
            text: &self.text[start..end],
116
        })
117
    }
118
}
119
120
impl Tokens<'_> {
121
    /// Returns an iterator over tokens in one diff line.
122
    fn new(line: &DiffLine) -> Tokens<'_> {
123
        Tokens {
124
            row: line.id,
125
            text: line.text.as_str(),
126
            cursor: 0,
127
        }
128
    }
129
}
130
131
/// Returns the per-row changed byte ranges for one hunk.
132
pub fn compute(hunk: &Hunk) -> WordChanges {
133
    let mut changes = WordChanges::new();
134
    let mut dels: Vec<&DiffLine> = Vec::new();
135
    let mut adds: Vec<&DiffLine> = Vec::new();
136
    for line in &hunk.lines {
137
        match line.kind {
138
            DiffLineKind::Deletion => dels.push(line),
139
            DiffLineKind::Addition => adds.push(line),
140
            DiffLineKind::Context => {
141
                flush_block(&mut dels, &mut adds, &mut changes);
142
            }
143
            DiffLineKind::NoNewline => {}
144
        }
145
    }
146
    flush_block(&mut dels, &mut adds, &mut changes);
147
148
    // The LCS walks back-to-front, so per-row ranges arrive in reverse order;
149
    // sort and collapse adjacent ranges into clean spans.
150
    for ranges in changes.values_mut() {
151
        ranges.sort_by_key(|range| range.start);
152
        ranges.dedup_by(|next, prev| {
153
            if prev.end >= next.start {
154
                prev.end = prev.end.max(next.end);
155
                true
156
            } else {
157
                false
158
            }
159
        });
160
    }
161
    changes
162
}
163
164
/// Pairs up the deletions and additions in one change block and emits ranges
165
/// for each pair that passes the similarity gate. Clears both buffers so the
166
/// next block starts fresh.
167
fn flush_block(dels: &mut Vec<&DiffLine>, adds: &mut Vec<&DiffLine>, changes: &mut WordChanges) {
168
    let pairs = dels.len().min(adds.len());
169
    for i in 0..pairs {
170
        lcs(dels[i], adds[i], changes);
171
    }
172
    dels.clear();
173
    adds.clear();
174
}
175
176
/// Runs an LCS between one deletion and one addition line. If the pair shares
177
/// enough tokens to look like two edits of the same line, the differing byte
178
/// ranges on each side are pushed into `changes`. Otherwise the pair is
179
/// treated as unrelated and skipped.
180
fn lcs(del: &DiffLine, add: &DiffLine, changes: &mut WordChanges) {
181
    let old: Vec<Token<'_>> = Tokens::new(del).collect();
182
    let new: Vec<Token<'_>> = Tokens::new(add).collect();
183
    if old.is_empty() || new.is_empty() {
184
        return;
185
    }
186
    if non_space_tokens_equal(&old, &new) {
187
        return;
188
    }
189
190
    // Build the standard LCS length table over token texts.
191
    let rows = old.len() + 1;
192
    let cols = new.len() + 1;
193
    let mut table = vec![vec![Cell::default(); cols]; rows];
194
    for i in 1..rows {
195
        for j in 1..cols {
196
            let prev = table[i - 1][j - 1];
197
            let top = table[i - 1][j];
198
            let left = table[i][j - 1];
199
            table[i][j] = if old[i - 1].text == new[j - 1].text {
200
                Cell {
201
                    len: prev.len + 1,
202
                    is_relevant: prev.is_relevant || old[i - 1].class.is_relevant(),
203
                }
204
            } else if top.len >= left.len {
205
                top
206
            } else {
207
                left
208
            };
209
        }
210
    }
211
212
    // Similarity gate: the LCS length must cover at least the configured
213
    // fraction of the longer line, or the lines are too different to usefully
214
    // word-diff against each other.
215
    let common = table[old.len()][new.len()];
216
    let max_len = old.len().max(new.len());
217
    if common.len as usize * SIMILARITY_DENOMINATOR < max_len * SIMILARITY_NUMERATOR
218
        || !common.is_relevant
219
    {
220
        return;
221
    }
222
223
    // Walk the table backwards from the bottom-right corner. Each step that
224
    // advances along only one axis is an old-only or new-only token, whose
225
    // byte range we record under its source row.
226
    let mut i = old.len();
227
    let mut j = new.len();
228
    while i > 0 && j > 0 {
229
        if old[i - 1].text == new[j - 1].text {
230
            i -= 1;
231
            j -= 1;
232
        } else if table[i - 1][j].len >= table[i][j - 1].len {
233
            i -= 1;
234
            push_changed_token(&old, i, changes);
235
        } else {
236
            j -= 1;
237
            push_changed_token(&new, j, changes);
238
        }
239
    }
240
    while i > 0 {
241
        i -= 1;
242
        push_changed_token(&old, i, changes);
243
    }
244
    while j > 0 {
245
        j -= 1;
246
        push_changed_token(&new, j, changes);
247
    }
248
}
249
250
/// Returns whether the edit only changes spacing between existing tokens.
251
fn non_space_tokens_equal(old: &[Token<'_>], new: &[Token<'_>]) -> bool {
252
    old.iter()
253
        .filter(|token| token.class != Class::Space)
254
        .map(|token| (token.class, token.text))
255
        .eq(new
256
            .iter()
257
            .filter(|token| token.class != Class::Space)
258
            .map(|token| (token.class, token.text)))
259
}
260
261
/// Pushes one changed token range, omitting ordinary spacing edits.
262
fn push_changed_token(tokens: &[Token<'_>], index: usize, changes: &mut WordChanges) {
263
    let token = &tokens[index];
264
    if token.class == Class::Space {
265
        return;
266
    }
267
268
    let ranges = changes.entry(token.row).or_default();
269
    if let Some(space) = tokens.get(index + 1)
270
        && let Some(next) = tokens.get(index + 2)
271
        && space.class == Class::Space
272
        && next.class != Class::Space
273
        && token.row == next.row
274
        && ranges.iter().any(|range| range == &next.range)
275
    {
276
        ranges.push(token.range.end..next.range.start);
277
    }
278
    ranges.push(token.range.clone());
279
}
280
281
#[cfg(test)]
282
#[allow(clippy::unwrap_used)]
283
mod tests {
284
    use super::*;
285
    use crate::{Decode, DiffDocument};
286
287
    fn parse(input: &str) -> DiffDocument {
288
        DiffDocument::decode_str(input).unwrap()
289
    }
290
291
    fn tokens(line: &DiffLine) -> Vec<&str> {
292
        Tokens::new(line).map(|t| t.text).collect()
293
    }
294
295
    #[test]
296
    fn tokenizer_splits_idents_whitespace_and_punctuation() {
297
        let line = DiffLine {
298
            id: RowId::new(0),
299
            kind: DiffLineKind::Context,
300
            text: "foo bar+baz".to_owned(),
301
        };
302
        assert_eq!(tokens(&line), vec!["foo", " ", "bar", "+", "baz"]);
303
    }
304
305
    #[test]
306
    fn tokenizer_records_byte_ranges() {
307
        let line = DiffLine {
308
            id: RowId::new(0),
309
            kind: DiffLineKind::Context,
310
            text: "ab cd".to_owned(),
311
        };
312
        let collected: Vec<_> = Tokens::new(&line).collect();
313
        assert_eq!(collected[0].range, 0..2);
314
        assert_eq!(collected[1].range, 2..3);
315
        assert_eq!(collected[2].range, 3..5);
316
    }
317
318
    #[test]
319
    fn similar_lines_get_word_diff() {
320
        let doc = parse(
321
            "\
322
diff --git a/a.rs b/a.rs
323
@@ -1 +1 @@
324
-fn render(view: &View) {
325
+fn render(view: &mut View, opts: Options) {
326
",
327
        );
328
        let hunk = &doc.files[0].hunks[0];
329
        let changes = compute(hunk);
330
        let new_row = hunk
331
            .lines
332
            .iter()
333
            .find(|l| l.kind == DiffLineKind::Addition)
334
            .unwrap();
335
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
336
        assert!(!new_ranges.is_empty(), "expected new-side changed ranges");
337
        let new_text = new_row.text.as_str();
338
        let highlighted: String = new_ranges
339
            .iter()
340
            .map(|r| &new_text[r.clone()])
341
            .collect::<Vec<_>>()
342
            .join("|");
343
        assert!(highlighted.contains("mut"), "got {highlighted:?}");
344
        assert!(highlighted.contains("opts"), "got {highlighted:?}");
345
        assert!(highlighted.contains("Options"), "got {highlighted:?}");
346
    }
347
348
    #[test]
349
    fn spacing_changes_are_suppressed_except_word_splits() {
350
        let doc = parse(
351
            "\
352
diff --git a/a.rs b/a.rs
353
@@ -1 +1 @@
354
-let result = foo + bar;
355
+let  result = foo+bar;
356
",
357
        );
358
        let hunk = &doc.files[0].hunks[0];
359
        let changes = compute(hunk);
360
        assert!(
361
            changes.is_empty(),
362
            "spacing-only edits should not produce a word-diff overlay, got {changes:?}"
363
        );
364
365
        let doc = parse(
366
            "\
367
diff --git a/a.rs b/a.rs
368
@@ -1 +1 @@
369
-let word = foobar;
370
+let word = foo bar;
371
",
372
        );
373
        let hunk = &doc.files[0].hunks[0];
374
        let changes = compute(hunk);
375
        let new_row = hunk
376
            .lines
377
            .iter()
378
            .find(|l| l.kind == DiffLineKind::Addition)
379
            .unwrap();
380
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
381
        let highlighted: String = new_ranges
382
            .iter()
383
            .map(|r| &new_row.text[r.clone()])
384
            .collect();
385
        assert_eq!(highlighted, "foo bar");
386
387
        let doc = parse(
388
            "\
389
diff --git a/a.rs b/a.rs
390
@@ -1 +1 @@
391
-let msg = old name;
392
+let msg = new value;
393
",
394
        );
395
        let hunk = &doc.files[0].hunks[0];
396
        let changes = compute(hunk);
397
        let new_row = hunk
398
            .lines
399
            .iter()
400
            .find(|l| l.kind == DiffLineKind::Addition)
401
            .unwrap();
402
        let new_ranges = changes.get(&new_row.id).cloned().unwrap_or_default();
403
        let highlighted: String = new_ranges
404
            .iter()
405
            .map(|r| &new_row.text[r.clone()])
406
            .collect();
407
        assert_eq!(highlighted, "new value");
408
    }
409
410
    #[test]
411
    fn dissimilar_lines_are_suppressed() {
412
        // The deletion and addition share only a few common tokens (mostly
413
        // spaces and punctuation). Highlighting individual tokens here would
414
        // just be noise โ€” the dim row tint already conveys the change.
415
        let doc = parse(
416
            "\
417
diff --git a/a.rs b/a.rs
418
@@ -1 +1 @@
419
-x = something_complex();
420
+result.set(other_thing);
421
",
422
        );
423
        let hunk = &doc.files[0].hunks[0];
424
        let changes = compute(hunk);
425
        assert!(
426
            changes.is_empty(),
427
            "dissimilar lines should not produce a word-diff overlay, got {changes:?}"
428
        );
429
    }
430
431
    #[test]
432
    fn separator_only_matches_are_suppressed() {
433
        let doc = parse(
434
            "\
435
diff --git a/a.rs b/a.rs
436
@@ -1 +1 @@
437
-old + stale + gone
438
+new + fresh + kept
439
",
440
        );
441
        let hunk = &doc.files[0].hunks[0];
442
        let changes = compute(hunk);
443
        assert!(
444
            changes.is_empty(),
445
            "lines that share only separators should not produce word-diff overlay"
446
        );
447
    }
448
449
    #[test]
450
    fn identical_lines_produce_no_changes() {
451
        let doc = parse(
452
            "\
453
diff --git a/a.rs b/a.rs
454
@@ -1,2 +1,2 @@
455
-same
456
+same
457
 context
458
",
459
        );
460
        let hunk = &doc.files[0].hunks[0];
461
        let changes = compute(hunk);
462
        assert!(changes.values().all(Vec::is_empty) || changes.is_empty());
463
    }
464
465
    #[test]
466
    fn pure_context_hunk_produces_no_changes() {
467
        let doc = parse(
468
            "\
469
diff --git a/a.rs b/a.rs
470
@@ -1,2 +1,2 @@
471
 one
472
 two
473
",
474
        );
475
        let hunk = &doc.files[0].hunks[0];
476
        let changes = compute(hunk);
477
        assert!(changes.is_empty() || changes.values().all(Vec::is_empty));
478
    }
479
480
    #[test]
481
    fn pure_addition_hunk_produces_no_overlay() {
482
        let doc = parse(
483
            "\
484
diff --git a/a.rs b/a.rs
485
@@ -1,2 +1,4 @@
486
 fn main() {
487
+    let foo = 42;
488
+    let bar = 43;
489
 }
490
",
491
        );
492
        let hunk = &doc.files[0].hunks[0];
493
        let changes = compute(hunk);
494
        assert!(changes.is_empty(), "got {changes:?}");
495
    }
496
497
    #[test]
498
    fn pure_deletion_hunk_produces_no_overlay() {
499
        let doc = parse(
500
            "\
501
diff --git a/a.rs b/a.rs
502
@@ -1,4 +1,2 @@
503
 fn main() {
504
-    let foo = 42;
505
-    let bar = 43;
506
 }
507
",
508
        );
509
        let hunk = &doc.files[0].hunks[0];
510
        let changes = compute(hunk);
511
        assert!(changes.is_empty());
512
    }
513
514
    #[test]
515
    fn changed_ranges_per_row_are_merged_and_sorted() {
516
        let doc = parse(
517
            "\
518
diff --git a/a.rs b/a.rs
519
@@ -1 +1 @@
520
-a b c d e
521
+a x y z e
522
",
523
        );
524
        let hunk = &doc.files[0].hunks[0];
525
        let changes = compute(hunk);
526
        for ranges in changes.values() {
527
            for pair in ranges.windows(2) {
528
                assert!(
529
                    pair[0].end <= pair[1].start,
530
                    "ranges not disjoint: {pair:?}"
531
                );
532
            }
533
        }
534
    }
535
536
    #[test]
537
    fn pairing_is_one_to_one_within_a_change_block() {
538
        // alpha/alpha pair is identical โ†’ no overlay.
539
        // beta/gamma pair is dissimilar (no common tokens) โ†’ suppressed.
540
        let doc = parse(
541
            "\
542
diff --git a/a.rs b/a.rs
543
@@ -1,3 +1,3 @@
544
-alpha
545
-beta
546
+alpha
547
+gamma
548
 tail
549
",
550
        );
551
        let hunk = &doc.files[0].hunks[0];
552
        let changes = compute(hunk);
553
        assert!(changes.is_empty(), "got {changes:?}");
554
    }
555
556
    #[test]
557
    fn unpaired_lines_in_a_block_get_no_overlay() {
558
        // Three deletions, one addition: only the first pair is considered;
559
        // the extra deletions stay un-highlighted.
560
        let doc = parse(
561
            "\
562
diff --git a/a.rs b/a.rs
563
@@ -1,3 +1,1 @@
564
-fn alpha() {}
565
-fn beta() {}
566
-fn gamma() {}
567
+fn alpha() {}
568
",
569
        );
570
        let hunk = &doc.files[0].hunks[0];
571
        let changes = compute(hunk);
572
        let beta = hunk
573
            .lines
574
            .iter()
575
            .find(|l| l.kind == DiffLineKind::Deletion && l.text.contains("beta"))
576
            .unwrap();
577
        let gamma = hunk
578
            .lines
579
            .iter()
580
            .find(|l| l.kind == DiffLineKind::Deletion && l.text.contains("gamma"))
581
            .unwrap();
582
        assert!(changes.get(&beta.id).is_none_or(Vec::is_empty));
583
        assert!(changes.get(&gamma.id).is_none_or(Vec::is_empty));
584
    }
585
}