Skip to main content

diffler_core/syntax/
intraline.rs

1//! Char-precise intra-line change emphasis driven by an AST diff (syndiff).
2//! Unlike the textual engine in [`crate::pairing`], reindentation and block
3//! wrapping are not flagged — only the byte ranges that differ structurally
4//! are emphasized — so a reformatted or re-wrapped block highlights just the
5//! tokens that actually changed.
6
7use std::ops::Range;
8
9use syndiff::{SyntaxDiffOptions, build_tree, diff_trees};
10
11use crate::model::{FileDiff, Hunk, LineKind};
12use crate::syntax::registry::LanguageRegistry;
13use crate::syntax::{MAX_PARSE_BYTES, line_bounds, parse, split_range_by_line};
14
15/// Emphasis byte ranges per line (one inner vec per source line).
16type LineEmphasis = Vec<Vec<Range<usize>>>;
17
18/// Bounds the AST-diff graph search so a huge, heavily rewritten file cannot
19/// stall the render thread; beyond it `diff_trees` returns `None` and the
20/// caller falls back to the textual engine. Well above any normal diff.
21const GRAPH_LIMIT: usize = 250_000;
22
23impl LanguageRegistry {
24    /// Per-line emphasis byte ranges for both sides, from an AST diff of the
25    /// full old/new content. `None` (caller falls back to the textual engine)
26    /// when the language is unsupported, content is too large, parsing fails,
27    /// or the diff exceeds its graph budget.
28    fn line_emphasis(
29        &self,
30        path: &str,
31        old_src: &str,
32        new_src: &str,
33    ) -> Option<(LineEmphasis, LineEmphasis)> {
34        if old_src.len() > MAX_PARSE_BYTES || new_src.len() > MAX_PARSE_BYTES {
35            return None;
36        }
37        let entry = self.for_path(path)?;
38        let old_ts = parse(entry, old_src)?;
39        let new_ts = parse(entry, new_src)?;
40        let old_tree = build_tree(old_ts.walk(), old_src);
41        let new_tree = build_tree(new_ts.walk(), new_src);
42        let options = SyntaxDiffOptions {
43            graph_limit: GRAPH_LIMIT,
44        };
45        let (old_ranges, new_ranges) = diff_trees(&old_tree, &new_tree, None, None, Some(options))?;
46        Some((
47            per_line_emphasis(old_src, &old_ranges),
48            per_line_emphasis(new_src, &new_ranges),
49        ))
50    }
51
52    /// Set char-precise emphasis on `file`'s diff lines from the AST diff.
53    /// Returns `false` when the syntactic engine is unavailable, so the caller
54    /// can fall back to the textual engine.
55    pub fn syntactic_emphasis(&self, file: &mut FileDiff) -> bool {
56        let emphasis = match (file.old_text.as_deref(), file.new_text.as_deref()) {
57            (Some(old), Some(new)) => self.line_emphasis(&file.path, old, new),
58            _ => None,
59        };
60        let Some((old_emph, new_emph)) = emphasis else {
61            return false;
62        };
63        for hunk in &mut file.hunks {
64            for line in &mut hunk.lines {
65                let ranges = match (line.new_no, line.old_no) {
66                    (Some(n), _) => new_emph.get(n as usize - 1),
67                    (None, Some(o)) => old_emph.get(o as usize - 1),
68                    _ => None,
69                };
70                let (moved, emphasis) =
71                    classify_line(line.kind, &line.text, ranges.map_or(&[], Vec::as_slice));
72                line.moved = moved;
73                line.emphasis = emphasis;
74            }
75            refine_partial_changes(hunk);
76        }
77        true
78    }
79}
80
81/// Where the AST diff flagged a *partial* line change (some token ranges, not
82/// the whole line and not a reformat), replace the coarse token ranges with a
83/// grapheme-level diff of the paired lines, so only the characters that actually
84/// changed are emphasized (an edit inside a string scalar shouldn't light up the
85/// whole scalar). Whole-line changes and reformat-only lines keep the AST result.
86fn refine_partial_changes(hunk: &mut Hunk) {
87    for (del_idx, add_idx) in crate::pairing::paired_run_indices(&hunk.lines) {
88        let partial = hunk
89            .lines
90            .get(del_idx)
91            .is_some_and(|l| !l.emphasis.is_empty())
92            || hunk
93                .lines
94                .get(add_idx)
95                .is_some_and(|l| !l.emphasis.is_empty());
96        if !partial {
97            continue;
98        }
99        let (Some(old), Some(new)) = (
100            hunk.lines.get(del_idx).map(|l| l.text.clone()),
101            hunk.lines.get(add_idx).map(|l| l.text.clone()),
102        ) else {
103            continue;
104        };
105        let (old_emph, new_emph) = crate::diff::intraline(&old, &new);
106        if let Some(line) = hunk.lines.get_mut(del_idx) {
107            line.emphasis = old_emph;
108        }
109        if let Some(line) = hunk.lines.get_mut(add_idx) {
110            line.emphasis = new_emph;
111        }
112    }
113}
114
115/// Map whole-file changed byte ranges to the raw per-line, within-line ranges.
116fn per_line_emphasis(src: &str, ranges: &[Range<usize>]) -> LineEmphasis {
117    let bounds = line_bounds(src);
118    let starts: Vec<usize> = bounds.iter().map(|&(s, _)| s).collect();
119    let mut out = vec![Vec::new(); bounds.len()];
120    for r in ranges {
121        split_range_by_line(&bounds, &starts, r, |li, rr| {
122            if let Some(v) = out.get_mut(li) {
123                v.push(rr);
124            }
125        });
126    }
127    out
128}
129
130/// Classify an added/deleted `line` from its raw changed byte `ranges`:
131/// - no change → a reindent/move: `(moved = true, no emphasis)`, a thin rail;
132/// - the whole content changed → `(false, no emphasis)`, a full +/- background;
133/// - some tokens changed → `(false, those ranges)`, background plus emphasis.
134fn classify_line(kind: LineKind, text: &str, ranges: &[Range<usize>]) -> (bool, Vec<Range<usize>>) {
135    let ranges = clamp(ranges, text.len());
136    let changed = matches!(kind, LineKind::Added | LineKind::Deleted);
137    if ranges.is_empty() {
138        return (changed, Vec::new());
139    }
140    if whole_line_changed(text, &ranges) {
141        return (false, Vec::new());
142    }
143    (false, ranges)
144}
145
146/// True when every non-whitespace byte of the line is emphasized (gaps fall
147/// only on whitespace) — i.e. the entire content changed.
148fn whole_line_changed(text: &str, ranges: &[Range<usize>]) -> bool {
149    let mut any_content = false;
150    for (i, &b) in text.as_bytes().iter().enumerate() {
151        if b == b' ' || b == b'\t' {
152            continue;
153        }
154        any_content = true;
155        if !ranges.iter().any(|r| r.start <= i && i < r.end) {
156            return false;
157        }
158    }
159    any_content
160}
161
162/// Clip ranges to the line's length and drop any that become empty.
163fn clamp(ranges: &[Range<usize>], len: usize) -> Vec<Range<usize>> {
164    ranges
165        .iter()
166        .filter_map(|r| {
167            let end = r.end.min(len);
168            (r.start < end).then_some(r.start..end)
169        })
170        .collect()
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn line_with(src: &str, needle: &str) -> usize {
178        src.lines()
179            .position(|l| l.contains(needle))
180            .unwrap_or_else(|| panic!("no line with {needle:?}"))
181    }
182
183    #[test]
184    fn pure_reindent_is_not_emphasized() {
185        let reg = LanguageRegistry::build();
186        let old = "fn f() {\n    let x = compute();\n    use_it(x);\n}\n";
187        let new = "fn f() {\n        let x = compute();\n        use_it(x);\n}\n";
188        let (_, new_e) = reg.line_emphasis("a.rs", old, new).expect("rust parses");
189        assert!(
190            new_e.iter().all(Vec::is_empty),
191            "reindentation must produce no emphasis, got {new_e:?}"
192        );
193    }
194
195    #[test]
196    fn a_real_token_change_is_emphasized() {
197        let reg = LanguageRegistry::build();
198        let old = "fn f() {\n    let x = 1;\n}\n";
199        let new = "fn f() {\n    let x = 2;\n}\n";
200        let (_, new_e) = reg.line_emphasis("a.rs", old, new).expect("rust parses");
201        let changed = line_with(new, "let x = 2");
202        let signature = line_with(new, "fn f()");
203        assert!(!new_e[changed].is_empty(), "the changed line is emphasized");
204        assert!(
205            new_e[signature].is_empty(),
206            "the unchanged signature line is not"
207        );
208    }
209
210    #[test]
211    fn in_string_edit_is_char_precise_not_whole_token() {
212        use crate::model::{DiffLine, FileDiff, FileStatus, Hunk, HunkId, LineKind};
213        let old_line = "fn f() { let s = \"foo/bar\"; }";
214        let new_line = "fn f() { let s = \"foo/EXTRA/bar\"; }";
215        let mut file = FileDiff {
216            path: "a.rs".into(),
217            old_path: None,
218            status: FileStatus::Modified,
219            binary: false,
220            old_text: Some(format!("{old_line}\n")),
221            new_text: Some(format!("{new_line}\n")),
222            hunks: vec![Hunk {
223                id: HunkId("h".into()),
224                old_start: 1,
225                old_lines: 1,
226                new_start: 1,
227                new_lines: 1,
228                context: String::new(),
229                lines: vec![
230                    DiffLine::new(LineKind::Deleted, Some(1), None, old_line.to_owned()),
231                    DiffLine::new(LineKind::Added, None, Some(1), new_line.to_owned()),
232                ],
233            }],
234        };
235        assert!(LanguageRegistry::build().syntactic_emphasis(&mut file));
236        let added = &file.hunks[0].lines[1];
237        assert!(!added.emphasis.is_empty(), "the changed line is emphasized");
238        let covered: String = added
239            .emphasis
240            .iter()
241            .filter_map(|r| new_line.get(r.clone()))
242            .collect();
243        // only the inserted run is emphasized, not the whole "foo/EXTRA/bar" token
244        assert!(
245            covered.contains("EXTRA"),
246            "covers the insertion: {covered:?}"
247        );
248        assert!(
249            !covered.contains("foo"),
250            "the unchanged prefix is not emphasized: {covered:?}"
251        );
252    }
253
254    #[test]
255    fn tsx_wrap_and_reindent_marks_only_real_changes() {
256        let reg = LanguageRegistry::build();
257        let old = "<Form>\n  <Button onClick={onApply}>Apply</Button>\n</Form>\n";
258        let new = "{(values) => (\n  <Form>\n    <Button onClick={() => apply(values)}>Apply</Button>\n  </Form>\n)}\n";
259        let (_, new_e) = reg.line_emphasis("a.tsx", old, new).expect("tsx parses");
260        let reindented = line_with(new, "<Form>");
261        let changed = line_with(new, "apply(values)");
262        assert!(
263            new_e[reindented].is_empty(),
264            "a reindented-but-identical line is not emphasized, got {:?}",
265            new_e[reindented]
266        );
267        assert!(
268            !new_e[changed].is_empty(),
269            "the structurally changed line is emphasized"
270        );
271    }
272
273    #[test]
274    fn unsupported_language_returns_none() {
275        let reg = LanguageRegistry::build();
276        assert!(reg.line_emphasis("a.zzz", "a\n", "b\n").is_none());
277    }
278
279    #[test]
280    fn classify_reindented_line_is_a_move() {
281        // an added/deleted line with no changed bytes only moved/reindented
282        let (moved, emph) = classify_line(LineKind::Added, "    <Form>", &[]);
283        assert!(moved, "reindent/move is flagged");
284        assert!(emph.is_empty());
285    }
286
287    #[test]
288    fn classify_whole_line_change_keeps_background_without_emphasis() {
289        // every non-whitespace byte changed -> full +/- bg, no char emphasis
290        let text = "    let entirely_new = compute();";
291        let ranges = [4..7, 8..20, 21..22, 23..text.len()];
292        let (moved, emph) = classify_line(LineKind::Added, text, &ranges);
293        assert!(!moved, "a wholly-changed line is a real change, not a move");
294        assert!(
295            emph.is_empty(),
296            "no char emphasis when the whole line changed"
297        );
298    }
299
300    #[test]
301    fn classify_partial_change_keeps_emphasis() {
302        // only `2` changed in `    let x = 2;`
303        let text = "    let x = 2;";
304        let changed = 12..13;
305        let (moved, emph) = classify_line(LineKind::Added, text, std::slice::from_ref(&changed));
306        assert!(!moved);
307        assert_eq!(emph.len(), 1);
308        assert_eq!(emph[0], changed);
309    }
310
311    #[test]
312    fn classify_context_line_is_never_moved() {
313        let (moved, emph) = classify_line(LineKind::Context, "    unchanged", &[]);
314        assert!(!moved);
315        assert!(emph.is_empty());
316    }
317}