diff: Speed up visible highlight landing

a7290fb32e4b82cc7a6c69fd718f9524c85ac579
Resolve repeated theme style stacks through reusable scratch storage,
then land visible highlight batches before queuing lookahead
work. This keeps the existing highlight context and lookahead
behavior while reducing the first visible TUI landing time.

The plain dev profile is optimized so the requested cargo run path
matches the measured optimized highlighter behavior.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent f83525c5
crates/diff/benches/render.rs +1 -1
585 585
586 586
    for frame in 0..frames {
587 587
        buffer.clear();
588 588
        viewer.render(AREA, &mut buffer);
589 589
        checksum ^= sample_buffer(&buffer, frame);
590 -
        let requests = viewer.highlight_requests(AREA);
590 +
        let requests = viewer.visible_highlight_requests(AREA);
591 591
        let results = highlighter.highlight_requests(requests);
592 592
        viewer.apply_highlights(results);
593 593
        buffer.clear();
594 594
        viewer.render(AREA, &mut buffer);
595 595
        checksum ^= sample_buffer(&buffer, frame.wrapping_add(frames));
src/file_{file:04}.rs\n" +0 -0
crates/diff/src/bin/rustik-diff/session.rs +51 -5
106 106
                    *redraw = true;
107 107
                }
108 108
                Ok(control)
109 109
            }
110 110
            TerminalEvent::Highlights(update) => {
111 -
                if self.debug {
111 +
                if self.debug && update.kind == HighlightWorkKind::Visible {
112 112
                    self.debug_status =
113 113
                        Some(update.timings.status(update.timings.started.elapsed()));
114 114
                }
115 -
                if self.viewer.apply_highlights(update.results) || self.debug {
115 +
                if self.viewer.apply_highlights(update.results)
116 +
                    || (self.debug && update.kind == HighlightWorkKind::Visible)
117 +
                {
116 118
                    self.draw_frame()?;
117 119
                }
118 120
                Ok(Control::Continue)
119 121
            }
120 122
            TerminalEvent::Context(update) => {
131 133
132 134
    /// Draws a frame and requests highlights for visible rows.
133 135
    fn redraw(&mut self) -> io::Result<()> {
134 136
        self.request_visible_highlights();
135 137
        self.draw_frame()?;
138 +
        self.request_lookahead_highlights();
136 139
        Ok(())
137 140
    }
138 141
139 142
    /// Requests highlight work for currently visible rows.
140 143
    fn request_visible_highlights(&mut self) {
143 146
            view: Duration::ZERO,
144 147
            context: Duration::ZERO,
145 148
            syntax: Duration::ZERO,
146 149
        };
147 150
        let area = viewer_area(self.terminal.area());
148 -
        let requests = self.viewer.highlight_requests(area);
151 +
        let requests = self.viewer.visible_highlight_requests(area);
149 152
        timings.view = timings.started.elapsed();
153 +
        self.queue_highlights(requests, timings, HighlightWorkKind::Visible);
154 +
    }
155 +
156 +
    /// Requests highlight work for rows after the visible viewport.
157 +
    fn request_lookahead_highlights(&mut self) {
158 +
        let mut timings = Timings {
159 +
            started: Instant::now(),
160 +
            view: Duration::ZERO,
161 +
            context: Duration::ZERO,
162 +
            syntax: Duration::ZERO,
163 +
        };
164 +
        let area = viewer_area(self.terminal.area());
165 +
        let requests = self.viewer.lookahead_highlight_requests(area);
166 +
        timings.view = timings.started.elapsed();
167 +
        self.queue_highlights(requests, timings, HighlightWorkKind::Lookahead);
168 +
    }
169 +
170 +
    /// Queues highlight work and records request timings.
171 +
    fn queue_highlights(
172 +
        &mut self,
173 +
        requests: Vec<HighlightRequest>,
174 +
        timings: Timings,
175 +
        kind: HighlightWorkKind,
176 +
    ) {
150 177
        if requests.is_empty() {
151 -
            if self.debug {
178 +
            if self.debug && kind == HighlightWorkKind::Visible {
152 179
                self.debug_status = Some(format!(
153 180
                    "view {} highlight {} (cached)",
154 181
                    format_ms(timings.view),
155 182
                    format_ms(timings.started.elapsed())
156 183
                ));
161 188
        match self
162 189
            .worker_tx
163 190
            .try_send(WorkerCommand::Highlight(HighlightWork {
164 191
                requests,
165 192
                timings,
193 +
                kind,
166 194
            })) {
167 195
            Ok(()) => {}
168 196
            Err(
169 197
                TrySendError::Full(WorkerCommand::Highlight(work))
170 198
                | TrySendError::Disconnected(WorkerCommand::Highlight(work)),
224 252
struct HighlightWork {
225 253
    /// Rows that need highlighting.
226 254
    requests: Vec<HighlightRequest>,
227 255
    /// Timings collected before the worker receives the request.
228 256
    timings: Timings,
257 +
    /// Whether this batch affects visible landing diagnostics.
258 +
    kind: HighlightWorkKind,
229 259
}
230 260
231 261
/// Highlight result produced by the background worker.
232 262
struct HighlightUpdate {
233 263
    /// Highlighted visible rows.
234 264
    results: Vec<HighlightResult>,
235 265
    /// Timings collected while producing the results.
236 266
    timings: Timings,
267 +
    /// Whether this batch affects visible landing diagnostics.
268 +
    kind: HighlightWorkKind,
269 +
}
270 +
271 +
/// Highlight batch role.
272 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273 +
enum HighlightWorkKind {
274 +
    /// Currently visible rows.
275 +
    Visible,
276 +
    /// Rows after the visible viewport.
277 +
    Lookahead,
237 278
}
238 279
239 280
/// Debug timings for one highlight batch.
240 281
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
241 282
struct Timings {
445 486
                match command {
446 487
                    WorkerCommand::Highlight(work) => {
447 488
                        if work.requests.is_empty() {
448 489
                            continue;
449 490
                        }
491 +
                        let kind = work.kind;
450 492
                        let (results, timings) = worker.highlight(work.requests, work.timings);
451 493
                        if tx
452 -
                            .send(Self::Highlights(HighlightUpdate { results, timings }))
494 +
                            .send(Self::Highlights(HighlightUpdate {
495 +
                                results,
496 +
                                timings,
497 +
                                kind,
498 +
                            }))
453 499
                            .is_err()
454 500
                        {
455 501
                            break;
456 502
                        }
457 503
                    }
crates/diff/src/viewer.rs +42 -2
3 3
mod tree;
4 4
5 5
use std::collections::btree_map::Entry;
6 6
use std::collections::{BTreeMap, BTreeSet};
7 7
use std::convert::Infallible;
8 +
use std::ops::Range;
8 9
use std::path::{Path, PathBuf};
9 10
10 11
use rustik_highlight as syntax;
11 12
use rustik_tui as tui;
12 13
use tui::{
23 24
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
24 25
};
25 26
26 27
pub use tree::{FileTreeMode, FileTreeTarget};
27 28
29 +
/// Visible and lookahead row ranges that should be highlighted.
30 +
#[derive(Clone, Debug, Eq, PartialEq)]
31 +
struct HighlightWindow {
32 +
    /// First row that can produce a visible highlight.
33 +
    start: usize,
34 +
    /// End of the currently visible row range.
35 +
    visible_end: usize,
36 +
    /// End of the lookahead row range.
37 +
    lookahead_end: usize,
38 +
}
39 +
28 40
/// Minimum width before the viewer attempts table-style diff rows.
29 41
const MIN_RENDER_COLS: usize = 12;
30 42
/// Width of old and new line number cells.
31 43
const LINE_NUMBER_WIDTH: usize = 5;
32 44
/// Foreground color used by old and new line number cells.
873 885
            ViewChange::Changed => Control::Redraw,
874 886
            ViewChange::Unchanged => Control::Continue,
875 887
        }
876 888
    }
877 889
890 +
    /// Returns highlight requests for visible source rows.
891 +
    pub fn visible_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
892 +
        let window = self.highlight_window(area);
893 +
        self.highlight_requests_in(window.start..window.visible_end)
894 +
    }
895 +
896 +
    /// Returns highlight requests for one viewport after the visible rows.
897 +
    pub fn lookahead_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
898 +
        let window = self.highlight_window(area);
899 +
        self.highlight_requests_in(window.visible_end..window.lookahead_end)
900 +
    }
901 +
878 902
    /// Returns highlight requests for visible source rows plus one viewport of lookahead.
879 903
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
904 +
        let window = self.highlight_window(area);
905 +
        self.highlight_requests_in(window.start..window.lookahead_end)
906 +
    }
907 +
908 +
    /// Returns the row ranges used for visible and lookahead highlighting.
909 +
    fn highlight_window(&self, area: Rect) -> HighlightWindow {
880 910
        let diff = self.layout(area).diff;
881 -
        let take = diff.rows.saturating_mul(2);
882 911
        let view = View::new(
883 912
            self.state.scroll.offset,
884 913
            self.render_rows_for(self.state.scroll.offset, diff.rows),
885 914
            diff.rows,
886 915
        );
887 916
        let start = view
888 917
            .offset
889 918
            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
919 +
        let visible_end = view.offset.saturating_add(diff.rows);
920 +
921 +
        HighlightWindow {
922 +
            start,
923 +
            visible_end,
924 +
            lookahead_end: visible_end.saturating_add(diff.rows),
925 +
        }
926 +
    }
927 +
928 +
    /// Returns highlight requests for one absolute row range.
929 +
    fn highlight_requests_in(&mut self, rows: Range<usize>) -> Vec<HighlightRequest> {
890 930
        let mut requests = Vec::new();
891 931
892 -
        for row in start..start.saturating_add(take) {
932 +
        for row in rows {
893 933
            let Some(meta) = self.diff_meta_at(row) else {
894 934
                continue;
895 935
            };
896 936
            let key = self.key_for(&meta);
897 937
            if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/highlight/src/theme.rs +125 -30
36 36
}
37 37
38 38
/// Per-line scratch buffer used while applying a theme.
39 39
#[derive(Debug, Default)]
40 40
pub(crate) struct StyleScratch {
41 +
    /// Theme and grammar identity this scratch cache belongs to.
42 +
    context: Option<StyleScratchContext>,
41 43
    /// Sorted byte boundaries that split a line into uniformly styled segments.
42 44
    boundaries: Vec<usize>,
45 +
    /// Uniformly styled segments for the current line.
46 +
    segments: Vec<Segment>,
47 +
    /// Scope spans covering the current segment.
48 +
    covering: Vec<ScopeSpan>,
49 +
    /// Scope stack for the current segment.
50 +
    stack: Vec<ScopeId>,
51 +
    /// Cached style results for repeated scope stacks.
52 +
    styles: Vec<StyleStackEntry>,
43 53
}
44 54
45 55
/// Byte range for one fully resolved style segment.
46 56
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47 57
struct Segment {
49 59
    start: usize,
50 60
    /// End byte in the line.
51 61
    end: usize,
52 62
}
53 63
64 +
/// Identity of the immutable inputs used by style scratch caches.
65 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
66 +
struct StyleScratchContext {
67 +
    /// Theme object address.
68 +
    theme: usize,
69 +
    /// Grammar object address.
70 +
    grammar: usize,
71 +
}
72 +
73 +
/// Cached style result for one ordered scope stack.
74 +
#[derive(Clone, Debug, Eq, PartialEq)]
75 +
struct StyleStackEntry {
76 +
    /// Ordered scopes covering a segment.
77 +
    stack: Vec<ScopeId>,
78 +
    /// The most specific scope covering this styled span, if any.
79 +
    scope: Option<ScopeId>,
80 +
    /// Resolved style.
81 +
    style: Style,
82 +
}
83 +
54 84
/// Resolved style and selector score for one scope.
55 85
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56 86
struct ScopeStyle {
57 87
    /// Resolved style.
58 88
    style: RuleStyle,
190 220
        output.clear();
191 221
        let line = trim_line_end(line);
192 222
        if line.is_empty() {
193 223
            return;
194 224
        }
225 +
        scratch.prepare(self, grammar);
195 226
        scratch.collect_boundaries(line, scopes);
196 227
197 -
        for segment in scratch.segments() {
198 -
            output.push(self.style_stack_segment(grammar, scopes, segment));
228 +
        for index in 0..scratch.segment_count() {
229 +
            let segment = scratch.segment(index);
230 +
            output.push(self.style_stack_segment(grammar, scopes, scratch, segment));
199 231
        }
200 232
    }
201 233
202 234
    /// Resolves one segment using TextMate-style scope stack matching.
203 235
    fn style_stack_segment(
204 236
        &self,
205 237
        grammar: &Grammar,
206 238
        scopes: &[ScopeSpan],
239 +
        scratch: &mut StyleScratch,
207 240
        segment: Segment,
208 241
    ) -> StyleSpan {
209 -
        let mut style = self
210 -
            .match_scope(&grammar.scope_name, &[])
211 -
            .style
212 -
            .apply_to(self.default);
213 -
        let mut scope = None;
214 -
        let mut stack = vec![grammar.scope_name.as_str()];
215 -
        let mut covering = segment.covering(scopes);
242 +
        scratch.collect_covering(segment, scopes);
216 243
217 -
        covering.sort_by_key(|span| (Reverse(span.end - span.start), span.start, span.end));
244 +
        if let Some(entry) = scratch.cached_stack() {
245 +
            return segment.styled(entry.scope, entry.style);
246 +
        }
218 247
219 -
        for span in covering {
248 +
        let mut style = self.root_style(grammar);
249 +
        let mut scope = None;
250 +
        let mut parents = vec![grammar.scope_name.as_str()];
251 +
252 +
        for span in scratch.covering() {
220 253
            let Some(name) = grammar.scopes.get(span.scope.index()) else {
221 254
                continue;
222 255
            };
223 -
            let matched = self.match_scope(name, &stack);
256 +
            let matched = self.match_scope(name, &parents);
224 257
            if matched.score > 0 {
225 258
                style = matched.style.apply_to(style);
226 259
                scope = Some(span.scope);
227 260
            } else if scope.is_none() {
228 261
                scope = Some(span.scope);
229 262
            }
230 -
            stack.push(name);
263 +
            parents.push(name);
231 264
        }
265 +
        scratch.insert_cached_stack(scope, style);
232 266
        segment.styled(scope, style)
233 267
    }
234 268
269 +
    /// Returns the base style for the grammar root scope.
270 +
    fn root_style(&self, grammar: &Grammar) -> Style {
271 +
        self.match_scope(&grammar.scope_name, &[])
272 +
            .style
273 +
            .apply_to(self.default)
274 +
    }
275 +
235 276
    /// Returns the strongest rule matching one current scope and its parents.
236 277
    fn match_scope(&self, scope: &str, parents: &[&str]) -> ScopeStyle {
237 278
        let mut style = RuleStyle::NONE;
238 279
        let mut best = 0;
239 280
314 355
315 356
impl StyleScratch {
316 357
    /// Clears per-line scratch storage while retaining allocations.
317 358
    pub(crate) fn clear_line(&mut self) {
318 359
        self.boundaries.clear();
360 +
        self.segments.clear();
361 +
        self.covering.clear();
362 +
        self.stack.clear();
363 +
    }
364 +
365 +
    /// Prepares scratch caches for one immutable theme and grammar pair.
366 +
    fn prepare(&mut self, theme: &Theme, grammar: &Grammar) {
367 +
        let context = StyleScratchContext {
368 +
            theme: theme as *const Theme as usize,
369 +
            grammar: grammar as *const Grammar as usize,
370 +
        };
371 +
        if self.context == Some(context) {
372 +
            return;
373 +
        }
374 +
        self.context = Some(context);
375 +
        self.styles.clear();
319 376
    }
320 377
321 378
    /// Collects sorted byte boundaries for the style segments in a line.
322 379
    fn collect_boundaries(&mut self, line: &str, scopes: &[ScopeSpan]) {
323 380
        self.boundaries.clear();
332 389
                self.boundaries.push(end);
333 390
            }
334 391
        }
335 392
        self.boundaries.sort_unstable();
336 393
        self.boundaries.dedup();
394 +
395 +
        self.segments.clear();
396 +
        self.segments
397 +
            .extend(self.boundaries.windows(2).filter_map(|window| {
398 +
                let [start, end] = *window else {
399 +
                    return None;
400 +
                };
401 +
                (start < end).then_some(Segment { start, end })
402 +
            }));
337 403
    }
338 404
339 -
    /// Iterates over the non-empty segments produced by the collected boundaries.
340 -
    fn segments(&self) -> impl Iterator<Item = Segment> + '_ {
341 -
        self.boundaries.windows(2).filter_map(|window| {
342 -
            let [start, end] = *window else {
343 -
                return None;
344 -
            };
345 -
            (start < end).then_some(Segment { start, end })
346 -
        })
405 +
    /// Returns how many segments are in the current line.
406 +
    fn segment_count(&self) -> usize {
407 +
        self.segments.len()
408 +
    }
409 +
410 +
    /// Returns one segment by index.
411 +
    fn segment(&self, index: usize) -> Segment {
412 +
        self.segments[index]
413 +
    }
414 +
415 +
    /// Collects ordered scope spans covering a segment.
416 +
    fn collect_covering(&mut self, segment: Segment, spans: &[ScopeSpan]) {
417 +
        self.covering.clear();
418 +
        self.stack.clear();
419 +
420 +
        self.covering.extend(
421 +
            spans
422 +
                .iter()
423 +
                .copied()
424 +
                .filter(|span| span.start <= segment.start && span.end >= segment.end),
425 +
        );
426 +
        self.covering
427 +
            .sort_by_key(|span| (Reverse(span.end - span.start), span.start, span.end));
428 +
        self.stack
429 +
            .extend(self.covering.iter().map(|span| span.scope));
430 +
    }
431 +
432 +
    /// Returns the cached style result for the current scope stack.
433 +
    fn cached_stack(&self) -> Option<&StyleStackEntry> {
434 +
        self.styles
435 +
            .iter()
436 +
            .find(|entry| entry.stack.as_slice() == self.stack.as_slice())
437 +
    }
438 +
439 +
    /// Inserts a style result for the current scope stack.
440 +
    fn insert_cached_stack(&mut self, scope: Option<ScopeId>, style: Style) {
441 +
        self.styles.push(StyleStackEntry {
442 +
            stack: self.stack.clone(),
443 +
            scope,
444 +
            style,
445 +
        });
347 446
    }
348 -
}
349 447
448 +
    /// Returns the current segment's ordered covering scopes.
449 +
    fn covering(&self) -> &[ScopeSpan] {
450 +
        &self.covering
451 +
    }
452 +
}
350 453
impl Segment {
351 454
    /// Builds a styled span from this segment.
352 455
    fn styled(self, scope: Option<ScopeId>, style: Style) -> StyleSpan {
353 456
        StyleSpan {
354 457
            start: self.start,
355 458
            end: self.end,
356 459
            scope,
357 460
            style,
358 461
        }
359 462
    }
360 -
361 -
    /// Returns scopes covering this segment.
362 -
    fn covering(self, spans: &[ScopeSpan]) -> Vec<&ScopeSpan> {
363 -
        spans
364 -
            .iter()
365 -
            .filter(|span| span.start <= self.start && span.end >= self.end)
366 -
            .collect()
367 -
    }
368 463
}
369 464
370 465
/// Returns a theme selector fallback for scopes that Shiki emits as metadata.
371 466
fn fallback_scope(scope: &str) -> Option<&'static str> {
372 467
    if scope_matches_selector(scope, "meta.attribute") {