diff: Reduce first highlight latency

e053426288f2ec17181b0d7ae398a5cdd5b9beb4
Defer expensive grammar setup until visible rows need it, and read only
a small blob prefix when first-line grammar detection is still required.

This keeps the initial rustik-diff render under the interactive target
without scanning every hunk for shebang metadata up front.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 72b1e35c
crates/diff/src/bin/rustik-diff/builtins.rs +1 -15
126 126
            .iter()
127 127
            .filter(|syntax| syntax.matches_document(document))
128 128
        {
129 129
            registry.add_grammar(syntax.grammar()?);
130 130
        }
131 -
132 -
        let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME);
133 -
        for file in &document.files {
134 -
            for hunk in &file.hunks {
135 -
                for side in [rustik_diff::DiffSide::Old, rustik_diff::DiffSide::New] {
136 -
                    let source = hunk.highlight_source(side);
137 -
                    if source.head == 1
138 -
                        && let Some(head) = source.text.lines().next()
139 -
                    {
140 -
                        Self::load_head_grammars(&mut highlighter, head)?;
141 -
                    }
142 -
                }
143 -
            }
144 -
        }
145 -
        Ok(highlighter)
131 +
        Ok(BuiltinHighlighter::new(registry, THEME_NAME))
146 132
    }
147 133
148 134
    /// Loads grammars selected by a source file's head line.
149 135
    pub(super) fn load_head_grammars(
150 136
        highlighter: &mut BuiltinHighlighter,
script\n\ +0 -0
crates/diff/src/bin/rustik-diff/session.rs +47 -9
7 7
use std::time::{Duration, Instant};
8 8
9 9
use rustik_diff::{
10 10
    BuiltinHighlighter, ContextChange, ContextRequest, ContextUpdate, Decode, DiffDocument,
11 11
    DiffHighlighter, DiffSide, DiffViewer, FileId, HighlightRequest, HighlightResult,
12 -
    HighlightSource,
12 +
    HighlightSource, Oid,
13 13
};
14 14
use rustik_repo::{GitRepo, Repo};
15 15
use rustik_tui as tui;
16 16
use rustik_tui::{
17 17
    Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Style, Terminal,
271 271
    highlighter: BuiltinHighlighter,
272 272
    /// Git-backed repo used for direct Git invocations.
273 273
    repo: Option<GitRepo>,
274 274
    /// Highlight source context cache keyed by diff file and side.
275 275
    context_sources: BTreeMap<(FileId, DiffSide), Vec<HighlightSource>>,
276 +
    /// Source object ids keyed by diff file and side.
277 +
    head_oids: BTreeMap<(FileId, DiffSide), Oid>,
278 +
    /// File-side heads already checked for first-line grammar metadata.
279 +
    loaded_heads: BTreeSet<(FileId, DiffSide)>,
276 280
}
277 281
278 282
impl HighlightWorker {
279 283
    /// Creates a background worker.
280 284
    fn new(document: &DiffDocument, repo: Option<GitRepo>) -> Self {
285 +
        let mut head_oids = BTreeMap::new();
286 +
        for file in &document.files {
287 +
            if let Some(oid) = file.header.old_oid.clone() {
288 +
                head_oids.insert((file.id, DiffSide::Old), oid);
289 +
            }
290 +
            if let Some(oid) = file.header.new_oid.clone() {
291 +
                head_oids.insert((file.id, DiffSide::New), oid);
292 +
            }
293 +
        }
281 294
        Self {
282 295
            highlighter: Builtins::highlighter(document)
283 296
                .unwrap_or_else(|_| BuiltinHighlighter::new(Default::default(), "")),
284 297
            repo,
285 298
            context_sources: BTreeMap::new(),
299 +
            head_oids,
300 +
            loaded_heads: BTreeSet::new(),
286 301
        }
287 302
    }
288 303
289 304
    /// Highlights one batch with context and syntax timings.
290 305
    fn highlight(
298 313
        let syntax = Instant::now();
299 314
        for request in &mut requests {
300 315
            if let Some(source) = self.context_source_for(request) {
301 316
                request.source = source.clone();
302 317
            }
318 +
            self.load_head_grammar(request);
303 319
        }
304 320
        let results = self.highlighter.highlight_batch(requests);
305 321
        timings.syntax = syntax.elapsed();
306 322
        (results, timings)
307 323
    }
308 324
325 +
    /// Loads first-line-selected grammars for a request's file side.
326 +
    fn load_head_grammar(&mut self, request: &HighlightRequest) {
327 +
        let key = (request.key.file, request.key.side);
328 +
        if !self.loaded_heads.insert(key) {
329 +
            return;
330 +
        }
331 +
        if request.source.head == 1
332 +
            && let Some(head) = request.source.text.lines().next()
333 +
        {
334 +
            let _ = Builtins::load_head_grammars(&mut self.highlighter, head);
335 +
            return;
336 +
        }
337 +
        let Some(repo) = self.repo.as_ref() else {
338 +
            return;
339 +
        };
340 +
        let Some(path) = request.path.as_deref() else {
341 +
            return;
342 +
        };
343 +
        if self.highlighter.has_path_grammar(path) {
344 +
            return;
345 +
        }
346 +
        let Some(oid) = self.head_oids.get(&key) else {
347 +
            return;
348 +
        };
349 +
        let head = repo.head_line(oid.as_str());
350 +
        if let Ok(Some(head)) = head {
351 +
            let _ = Builtins::load_head_grammars(&mut self.highlighter, &head);
352 +
        }
353 +
    }
354 +
309 355
    /// Loads bounded source context for uncached request paths.
310 356
    fn load_context_sources(&mut self, requests: &[HighlightRequest]) {
311 357
        let Some(repo) = self.repo.as_ref() else {
312 358
            return;
313 359
        };
349 395
                let sources = file
350 396
                    .hunks
351 397
                    .iter()
352 398
                    .map(|hunk| hunk.highlight_source(side))
353 399
                    .collect::<Vec<_>>();
354 -
                for source in &sources {
355 -
                    if side == DiffSide::New
356 -
                        && source.head == 1
357 -
                        && let Some(head) = source.text.lines().next()
358 -
                    {
359 -
                        let _ = Builtins::load_head_grammars(&mut self.highlighter, head);
360 -
                    }
361 -
                }
362 400
                self.context_sources.insert((file_id, side), sources);
363 401
            }
364 402
        }
365 403
    }
366 404
crates/diff/src/highlight.rs +12 -1
1 1
//! Highlight request and result protocol for diff rendering.
2 2
3 3
use std::collections::{BTreeMap, hash_map::DefaultHasher};
4 4
use std::hash::{Hash, Hasher};
5 -
use std::path::PathBuf;
5 +
use std::path::{Path, PathBuf};
6 6
use std::sync::Arc;
7 7
8 8
use rustik_highlight as syntax;
9 9
use rustik_tui as tui;
10 10
use rustik_tui::{Color, Label, Line, Style};
282 282
        if self.registry.grammar_by_name(&grammar.name).is_err() {
283 283
            self.registry.add_grammar(grammar);
284 284
        }
285 285
    }
286 286
287 +
    /// Returns whether a path selects a loaded non-plain grammar.
288 +
    pub fn has_path_grammar(&self, path: &Path) -> bool {
289 +
        self.registry
290 +
            .query(syntax::GrammarQuery {
291 +
                syntax: None,
292 +
                path: Some(path),
293 +
                head: None,
294 +
            })
295 +
            .is_ok_and(|grammar| grammar.scope_name != "text.plain")
296 +
    }
297 +
287 298
    /// Highlights one request.
288 299
    pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
289 300
        self.highlight_group(vec![request]).remove(0)
290 301
    }
291 302
a.css +0 -0
a.rs\n", +0 -0
crates/highlight/src/grammar/pattern.rs +91 -47
1 1
//! Pattern compilation and matching for TextMate grammars.
2 2
//!
3 3
//! Raw TextMate patterns compile into a tree of [`Pattern`] values grouped into
4 -
//! [`PatternSet`]s. Each set keeps a combined Oniguruma [`RegSet`] so that
5 -
//! finding the next match in a line is one regex search regardless of how many
6 -
//! patterns share that nesting level. Begin/end rules carry their end pattern
7 -
//! on the same node; static end patterns are precompiled, while dynamic ones
8 -
//! are resolved against the begin match the first time they are needed and
9 -
//! cached for subsequent lines.
4 +
//! [`PatternSet`]s. Each set caches a combined Oniguruma [`RegSet`] on first
5 +
//! search so that finding the next match in a line is one regex search
6 +
//! regardless of how many patterns share that nesting level. Begin/end rules
7 +
//! carry their end pattern on the same node; static end patterns are
8 +
//! precompiled, while dynamic ones are resolved against the begin match the
9 +
//! first time they are needed and cached for subsequent lines.
10 10
11 11
use super::end::{EndPattern, EndRegex, EndRegexCache};
12 12
use super::selector::ScopeSelector;
13 13
use super::*;
14 14
use crate::raw::truthy_flag;
15 +
use std::cell::OnceCell;
15 16
16 17
/// Capture-group index to capture metadata mapping.
17 18
pub(super) type Captures = BTreeMap<usize, Capture>;
18 19
19 20
/// A scope assigned by a pattern.
89 90
pub(super) struct PatternSet {
90 91
    /// Patterns in declaration order.
91 92
    pub(super) patterns: Vec<Pattern>,
92 93
    /// Ordered local patterns and includes declared in this set.
93 94
    entries: Vec<PatternEntry>,
94 -
    /// Pattern locations in the flattened regex search set.
95 +
    /// Pattern locations in flattened search order.
95 96
    matches: Vec<RuleLocation>,
96 97
    /// Combined RegSet covering flattened pattern match or begin sources.
97 -
    regexes: Option<RegSet>,
98 +
    regexes: OnceCell<Option<SearchRegexes>>,
99 +
}
100 +
101 +
/// Lazily compiled combined regex set plus its filtered match table.
102 +
#[derive(Debug)]
103 +
struct SearchRegexes {
104 +
    /// Pattern locations in the same order as [`Self::regexes`].
105 +
    matches: Vec<RuleLocation>,
106 +
    /// Combined Oniguruma regex set for all valid search sources.
107 +
    regexes: RegSet,
98 108
}
99 109
100 110
/// Ordered search entry inside one pattern set.
101 111
#[derive(Clone, Copy, Debug)]
102 112
enum PatternEntry {
491 501
    pub(super) fn empty() -> Self {
492 502
        Self {
493 503
            patterns: Vec::new(),
494 504
            entries: Vec::new(),
495 505
            matches: Vec::new(),
496 -
            regexes: None,
506 +
            regexes: OnceCell::new(),
497 507
        }
498 508
    }
499 509
500 510
    /// Builds a pattern set from local patterns and declaration-order search entries.
501 511
    fn new(patterns: Vec<Pattern>, entries: Vec<PatternEntry>) -> Self {
502 512
        Self {
503 513
            patterns,
504 514
            entries,
505 515
            matches: Vec::new(),
506 -
            regexes: None,
516 +
            regexes: OnceCell::new(),
507 517
        }
508 518
    }
509 519
510 520
    /// Finds the next flattened pattern match at or after `pos`.
511 521
    fn find_next(&self, search: &mut PatternSearch<'_, '_, '_>, pos: usize) -> Option<Match> {
513 523
            || search.limit > search.line.len()
514 524
            || !search.line.is_char_boundary(pos)
515 525
        {
516 526
            return None;
517 527
        }
518 -
        let regexes = self.regexes.as_ref()?;
519 -
        let (entry, captures) = regexes.captures_with_options(
528 +
        let search_regexes = self.regexes(search.sets)?;
529 +
        let (entry, captures) = search_regexes.regexes.captures_with_options(
520 530
            search.line,
521 531
            pos,
522 532
            search.limit,
523 533
            RegSetLead::Position,
524 534
            search.anchors.search_options(pos),
525 535
        )?;
526 -
        let location = self.matches.get(entry)?;
536 +
        let location = search_regexes.matches.get(entry)?;
527 537
        let pattern = search
528 538
            .sets
529 539
            .get(location.set.index())?
530 540
            .patterns
531 541
            .get(location.index)?;
532 542
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
533 543
534 544
        pattern.match_result(regex_match, search)
535 545
    }
546 +
547 +
    /// Returns the compiled search regex set, building it on first use.
548 +
    fn regexes(&self, sets: &[PatternSet]) -> Option<&SearchRegexes> {
549 +
        self.regexes
550 +
            .get_or_init(|| SearchRegexes::new(&self.matches, sets))
551 +
            .as_ref()
552 +
    }
553 +
}
554 +
555 +
impl SearchRegexes {
556 +
    /// Compiles a combined search set, filtering invalid sources only on failure.
557 +
    fn new(matches: &[RuleLocation], sets: &[PatternSet]) -> Option<Self> {
558 +
        if matches.is_empty() {
559 +
            return None;
560 +
        }
561 +
        let mut compiled_matches = Vec::new();
562 +
        let mut sources = Vec::new();
563 +
        for location in matches {
564 +
            let Some(source) = search_source(sets, *location) else {
565 +
                continue;
566 +
            };
567 +
            compiled_matches.push(*location);
568 +
            sources.push(source);
569 +
        }
570 +
        if sources.is_empty() {
571 +
            return None;
572 +
        }
573 +
        if let Ok(regexes) = RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS) {
574 +
            return Some(Self {
575 +
                matches: compiled_matches,
576 +
                regexes,
577 +
            });
578 +
        }
579 +
580 +
        let mut valid_matches = Vec::new();
581 +
        let mut sources = Vec::new();
582 +
        for location in matches {
583 +
            let Some(source) = search_source(sets, *location) else {
584 +
                continue;
585 +
            };
586 +
            if regex(source).is_ok() {
587 +
                valid_matches.push(*location);
588 +
                sources.push(source);
589 +
            }
590 +
        }
591 +
        if sources.is_empty() {
592 +
            return None;
593 +
        }
594 +
        RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS)
595 +
            .ok()
596 +
            .map(|regexes| Self {
597 +
                matches: valid_matches,
598 +
                regexes,
599 +
            })
600 +
    }
601 +
}
602 +
603 +
/// Returns the search regex source for a flattened pattern location.
604 +
fn search_source(sets: &[PatternSet], location: RuleLocation) -> Option<&str> {
605 +
    sets.get(location.set.index())?
606 +
        .patterns
607 +
        .get(location.index)
608 +
        .map(Pattern::search_source)
536 609
}
537 610
538 611
impl<'raw> PatternCompiler<'raw> {
539 612
    /// Creates a compiler for a raw grammar.
540 613
    pub(super) fn new(raw: &'raw RawGrammar, dependencies: &'raw [RawGrammar]) -> Self {
627 700
            &pattern.match_rule,
628 701
            &pattern.begin,
629 702
            &pattern.end,
630 703
            &pattern.while_rule,
631 704
        ) {
632 -
            (Some(source), _, _, _) => {
633 -
                if regex(source).is_err() {
634 -
                    return Ok(());
635 -
                }
636 -
                PatternBody::Match {
637 -
                    source: source.clone(),
638 -
                }
639 -
            }
705 +
            (Some(source), _, _, _) => PatternBody::Match {
706 +
                source: source.clone(),
707 +
            },
640 708
            (None, Some(begin), Some(end), _) => {
641 -
                if regex(begin).is_err() {
642 -
                    return Ok(());
643 -
                }
644 709
                let Some(end) = EndPattern::compile(end) else {
645 710
                    return Ok(());
646 711
                };
647 712
                PatternBody::BeginEnd {
648 713
                    begin_source: begin.clone(),
649 714
                    end,
650 715
                    apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()),
651 716
                }
652 717
            }
653 718
            (None, Some(begin), None, Some(while_rule)) => {
654 -
                if regex(begin).is_err() {
655 -
                    return Ok(());
656 -
                }
657 719
                let Some(while_rule) = EndPattern::compile(while_rule) else {
658 720
                    return Ok(());
659 721
                };
660 722
                PatternBody::BeginWhile {
661 723
                    begin_source: begin.clone(),
867 929
    fn compile_searches(&mut self) {
868 930
        let mut searches = Vec::with_capacity(self.sets.len());
869 931
        for index in 0..self.sets.len() {
870 932
            let mut active = Vec::new();
871 933
            let mut collected = Vec::new();
872 -
            let mut matches = Vec::new();
873 -
            let mut sources = Vec::new();
874 934
            self.collect_search_entries(PatternSetId::new(index), &mut active, &mut collected);
875 -
            for location in collected {
876 -
                let Some(pattern) = self
877 -
                    .sets
878 -
                    .get(location.set.index())
879 -
                    .and_then(|set| set.patterns.get(location.index))
880 -
                else {
881 -
                    continue;
882 -
                };
883 -
                matches.push(location);
884 -
                sources.push(pattern.search_source());
885 -
            }
886 -
            let regexes = (!sources.is_empty())
887 -
                .then(|| RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS).ok())
888 -
                .flatten();
889 -
890 -
            searches.push((matches, regexes));
935 +
            searches.push(collected);
891 936
        }
892 937
893 -
        for (set, (matches, regexes)) in self.sets.iter_mut().zip(searches) {
938 +
        for (set, matches) in self.sets.iter_mut().zip(searches) {
894 939
            set.matches = matches;
895 -
            set.regexes = regexes;
896 940
        }
897 941
    }
898 942
899 943
    /// Collects the declaration-order patterns searched for `set`.
900 944
    fn collect_search_entries(
crates/repo/src/lib.rs +39 -2
9 9
#![deny(unsafe_code)]
10 10
#![warn(missing_docs)]
11 11
#![warn(clippy::unwrap_used)]
12 12
13 13
use std::ffi::{OsStr, OsString};
14 -
use std::io;
14 +
use std::io::{self, Read as _};
15 15
use std::path::{Path, PathBuf};
16 -
use std::process::Command;
16 +
use std::process::{Command, Stdio};
17 17
18 18
// Constants //
19 19
20 20
/// Environment variable that disables Git's colored output.
21 21
const NO_COLOR: &str = "NO_COLOR";
22 22
/// Pathspec separator that ends Git's option list.
23 23
const PATHSPEC_SEPARATOR: &str = "--";
24 +
/// Maximum bytes read from a file head for shebang-style inference.
25 +
const HEAD_BYTES: usize = 64;
24 26
25 27
// Repo //
26 28
27 29
/// A diff backend a viewer can re-query for wider hunk context.
28 30
pub trait Repo {
60 62
        args.iter()
61 63
            .map(OsString::as_os_str)
62 64
            .filter(|arg| !is_refetched_path(arg, paths))
63 65
            .collect()
64 66
    }
67 +
68 +
    /// Reads the first bytes of a Git blob object.
69 +
    pub fn head_line(&self, oid: &str) -> Result<Option<String>, RepoError> {
70 +
        let mut child = Command::new("git")
71 +
            .arg("show")
72 +
            .arg(oid)
73 +
            .current_dir(&self.cwd)
74 +
            .stdout(Stdio::piped())
75 +
            .stderr(Stdio::null())
76 +
            .spawn()?;
77 +
        let Some(mut stdout) = child.stdout.take() else {
78 +
            return Ok(None);
79 +
        };
80 +
        let head = read_head(&mut stdout)?;
81 +
        let _ = child.kill();
82 +
        let _ = child.wait();
83 +
84 +
        Ok(head)
85 +
    }
65 86
}
66 87
67 88
impl Repo for GitRepo {
68 89
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
69 90
        // Forwarded args up to any `--` pathspec separator select the diff; the
95 116
        let normalized_path = path.strip_prefix(".").unwrap_or(path);
96 117
        normalized == normalized_path
97 118
    })
98 119
}
99 120
121 +
/// Reads a bounded file prefix and returns its first line.
122 +
fn read_head(reader: &mut impl io::Read) -> Result<Option<String>, RepoError> {
123 +
    let mut bytes = Vec::with_capacity(HEAD_BYTES);
124 +
    let read = reader.take(HEAD_BYTES as u64).read_to_end(&mut bytes)?;
125 +
    if read == 0 {
126 +
        return Ok(None);
127 +
    }
128 +
    if let Some(end) = bytes.iter().position(|byte| *byte == b'\n') {
129 +
        bytes.truncate(end);
130 +
    }
131 +
    if bytes.last() == Some(&b'\r') {
132 +
        bytes.pop();
133 +
    }
134 +
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
135 +
}
136 +
100 137
// Error Handling //
101 138
102 139
/// A failure while refetching diff data from a [`Repo`].
103 140
#[derive(Debug)]
104 141
pub enum RepoError {