highlight: Implement blob cache for performance
0144f037841c2674117db4590424986ed0325c47
1 parent
3a9268c7
crates/diff/src/highlight.rs
+49 -4
| 79 | 79 | pub struct BuiltinHighlighter { |
|
| 80 | 80 | /// Grammar and theme registry. |
|
| 81 | 81 | registry: syntax::Registry, |
|
| 82 | 82 | /// Theme used when requests ask for automatic theme selection. |
|
| 83 | 83 | default_theme: String, |
|
| 84 | + | /// Per-source tokenizer caches reused across batches. |
|
| 85 | + | blob_caches: BTreeMap<BlobCacheKey, BlobCacheEntry>, |
|
| 86 | + | } |
|
| 87 | + | ||
| 88 | + | /// Identifier for cached blob-highlight state. |
|
| 89 | + | #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
|
| 90 | + | struct BlobCacheKey { |
|
| 91 | + | /// Grammar name used to tokenize the source. |
|
| 92 | + | grammar: String, |
|
| 93 | + | /// Address of the cached source allocation. |
|
| 94 | + | text_ptr: usize, |
|
| 95 | + | /// Length of the cached source allocation. |
|
| 96 | + | text_len: usize, |
|
| 97 | + | } |
|
| 98 | + | ||
| 99 | + | /// Cached tokenizer state for one source allocation. |
|
| 100 | + | #[derive(Debug)] |
|
| 101 | + | struct BlobCacheEntry { |
|
| 102 | + | /// Source owner that keeps the cached allocation pinned. |
|
| 103 | + | _source: Arc<str>, |
|
| 104 | + | /// Per-line parser state and scope cache. |
|
| 105 | + | cache: syntax::BlobCache, |
|
| 84 | 106 | } |
|
| 85 | 107 | ||
| 86 | 108 | /// Highlights diff rows requested by a [`crate::DiffViewer`]. |
|
| 87 | 109 | pub trait DiffHighlighter { |
|
| 88 | 110 | /// Highlights one batch of visible diff rows. |
| 239 | 261 | /// Creates a highlighter from caller-loaded grammars and themes. |
|
| 240 | 262 | pub fn new(registry: syntax::Registry, default_theme: impl Into<String>) -> Self { |
|
| 241 | 263 | Self { |
|
| 242 | 264 | registry, |
|
| 243 | 265 | default_theme: default_theme.into(), |
|
| 266 | + | blob_caches: BTreeMap::new(), |
|
| 244 | 267 | } |
|
| 245 | 268 | } |
|
| 246 | 269 | ||
| 247 | 270 | /// Adds `grammar` to this highlighter if a grammar with the same name is absent. |
|
| 248 | 271 | pub fn ensure_grammar(&mut self, grammar: syntax::Grammar) { |
| 308 | 331 | end = end.max(range.end); |
|
| 309 | 332 | } |
|
| 310 | 333 | if start >= end { |
|
| 311 | 334 | return requests.into_iter().map(HighlightResult::plain).collect(); |
|
| 312 | 335 | } |
|
| 336 | + | let source = first.source.text.clone(); |
|
| 337 | + | let cache_key = BlobCacheKey { |
|
| 338 | + | grammar: grammar.name.clone(), |
|
| 339 | + | text_ptr: source.as_ptr() as usize, |
|
| 340 | + | text_len: source.len(), |
|
| 341 | + | }; |
|
| 342 | + | let cache = self |
|
| 343 | + | .blob_caches |
|
| 344 | + | .remove(&cache_key) |
|
| 345 | + | .map(|entry| entry.cache) |
|
| 346 | + | .unwrap_or_default(); |
|
| 347 | + | ||
| 313 | 348 | let mut lines = BTreeMap::new(); |
|
| 314 | - | let mut blob = syntax::BlobHighlighter::new(grammar, first.source.text.as_ref()); |
|
| 315 | - | blob.highlight_styled_range(theme, start..end, |line| { |
|
| 316 | - | lines.insert(line.line_index, line_from_spans(line.text, line.styles)); |
|
| 317 | - | }); |
|
| 349 | + | let cache = { |
|
| 350 | + | let mut blob = syntax::BlobHighlighter::with_cache(grammar, source.as_ref(), cache); |
|
| 351 | + | blob.highlight_styled_range(theme, start..end, |line| { |
|
| 352 | + | lines.insert(line.line_index, line_from_spans(line.text, line.styles)); |
|
| 353 | + | }); |
|
| 354 | + | blob.into_cache() |
|
| 355 | + | }; |
|
| 356 | + | self.blob_caches.insert( |
|
| 357 | + | cache_key, |
|
| 358 | + | BlobCacheEntry { |
|
| 359 | + | _source: source, |
|
| 360 | + | cache, |
|
| 361 | + | }, |
|
| 362 | + | ); |
|
| 318 | 363 | ||
| 319 | 364 | requests |
|
| 320 | 365 | .into_iter() |
|
| 321 | 366 | .map(|request| { |
|
| 322 | 367 | let line = request |
a.css
+0 -0
a.rs\n",
+0 -0
crates/highlight/src/blob.rs
+76 -49
| 74 | 74 | pub byte_range: Range<usize>, |
|
| 75 | 75 | /// Scope spans for this line. |
|
| 76 | 76 | pub scopes: Vec<ScopeSpan>, |
|
| 77 | 77 | } |
|
| 78 | 78 | ||
| 79 | + | /// Owned per-line tokenization cache for [`BlobHighlighter`]. |
|
| 80 | + | /// |
|
| 81 | + | /// Callers that highlight the same source text repeatedly can keep one of |
|
| 82 | + | /// these between calls so the tokenizer state at the visible window is reused |
|
| 83 | + | /// instead of being rebuilt from the top of the file every time. |
|
| 84 | + | #[derive(Debug, Default)] |
|
| 85 | + | pub struct BlobCache { |
|
| 86 | + | /// Byte offsets for each source line start. |
|
| 87 | + | line_starts: Vec<usize>, |
|
| 88 | + | /// Parser state at the start of each source line. |
|
| 89 | + | states: Vec<Option<LineState>>, |
|
| 90 | + | /// Cached scope spans for each source line. |
|
| 91 | + | scopes: Vec<Option<Vec<ScopeSpan>>>, |
|
| 92 | + | /// Reusable per-line scratch for styled range calls. |
|
| 93 | + | buffer: LineBuffer, |
|
| 94 | + | } |
|
| 95 | + | ||
| 79 | 96 | /// Incremental highlighter for a complete text blob. |
|
| 80 | 97 | /// |
|
| 81 | 98 | /// The highlighter caches parser states and per-line scope spans so callers can |
|
| 82 | 99 | /// ask for individual lines or ranges without reparsing the whole blob each |
|
| 83 | 100 | /// time. Editing callers should call [`BlobHighlighter::reset_text`] or |
| 87 | 104 | pub struct BlobHighlighter<'text> { |
|
| 88 | 105 | /// Reusable tokenizer for the backing grammar. |
|
| 89 | 106 | tokenizer: LineTokenizer<'text>, |
|
| 90 | 107 | /// Backing source text. |
|
| 91 | 108 | text: &'text str, |
|
| 92 | - | /// Byte offsets for each source line start. |
|
| 93 | - | line_starts: Vec<usize>, |
|
| 94 | - | /// Parser state at the start of each source line. |
|
| 95 | - | states: Vec<Option<LineState>>, |
|
| 96 | - | /// Cached scope spans for each source line. |
|
| 97 | - | scopes: Vec<Option<Vec<ScopeSpan>>>, |
|
| 98 | - | /// Reusable per-line scratch for styled range calls. |
|
| 99 | - | buffer: LineBuffer, |
|
| 109 | + | /// Per-line cache that may be reused across constructions. |
|
| 110 | + | cache: BlobCache, |
|
| 100 | 111 | } |
|
| 101 | 112 | ||
| 102 | 113 | impl LineBuffer { |
|
| 103 | 114 | /// Clears all buffered spans while retaining allocations. |
|
| 104 | 115 | pub fn clear(&mut self) { |
| 148 | 159 | (&self.scopes, &self.styles) |
|
| 149 | 160 | } |
|
| 150 | 161 | } |
|
| 151 | 162 | ||
| 152 | 163 | impl<'text> BlobHighlighter<'text> { |
|
| 153 | - | /// Creates a blob highlighter and caches only the initial empty state. |
|
| 164 | + | /// Creates a blob highlighter with an empty per-line cache. |
|
| 154 | 165 | pub fn new(grammar: &'text Grammar, text: &'text str) -> Self { |
|
| 155 | - | let mut highlighter = Self { |
|
| 166 | + | Self::with_cache(grammar, text, BlobCache::default()) |
|
| 167 | + | } |
|
| 168 | + | ||
| 169 | + | /// Creates a blob highlighter that reuses a caller-owned per-line cache. |
|
| 170 | + | pub fn with_cache(grammar: &'text Grammar, text: &'text str, mut cache: BlobCache) -> Self { |
|
| 171 | + | cache.reset_for(text); |
|
| 172 | + | Self { |
|
| 156 | 173 | tokenizer: LineTokenizer::new(grammar), |
|
| 157 | 174 | text, |
|
| 158 | - | line_starts: Vec::new(), |
|
| 159 | - | states: Vec::new(), |
|
| 160 | - | scopes: Vec::new(), |
|
| 161 | - | buffer: LineBuffer::default(), |
|
| 162 | - | }; |
|
| 163 | - | highlighter.rebuild_caches(); |
|
| 164 | - | highlighter |
|
| 175 | + | cache, |
|
| 176 | + | } |
|
| 177 | + | } |
|
| 178 | + | ||
| 179 | + | /// Returns the per-line cache so it can be reused on the next call. |
|
| 180 | + | pub fn into_cache(self) -> BlobCache { |
|
| 181 | + | self.cache |
|
| 165 | 182 | } |
|
| 166 | 183 | ||
| 167 | 184 | /// Replaces the blob text and clears cached line states. |
|
| 168 | 185 | pub fn reset_text(&mut self, text: &'text str) { |
|
| 169 | 186 | self.text = text; |
|
| 170 | - | self.rebuild_caches(); |
|
| 171 | - | } |
|
| 172 | - | ||
| 173 | - | /// Rebuilds line metadata and clears cached highlighting results. |
|
| 174 | - | fn rebuild_caches(&mut self) { |
|
| 175 | - | self.line_starts = line_starts(self.text); |
|
| 176 | - | self.states = vec![None; self.line_starts.len() + 1]; |
|
| 177 | - | self.states[0] = Some(LineState::default()); |
|
| 178 | - | self.scopes = vec![None; self.line_starts.len()]; |
|
| 187 | + | self.cache.reset_for(text); |
|
| 179 | 188 | } |
|
| 180 | 189 | ||
| 181 | 190 | /// Returns the number of highlightable lines in the blob. |
|
| 182 | 191 | pub fn line_count(&self) -> usize { |
|
| 183 | - | self.line_starts.len() |
|
| 192 | + | self.cache.line_starts.len() |
|
| 184 | 193 | } |
|
| 185 | 194 | ||
| 186 | 195 | /// Returns a line by index, excluding line terminators. |
|
| 187 | 196 | pub fn line(&self, line: usize) -> Option<&'text str> { |
|
| 188 | 197 | let range = self.line_byte_range(line)?; |
| 194 | 203 | (line < self.line_count()).then(|| self.line_range_unchecked(line)) |
|
| 195 | 204 | } |
|
| 196 | 205 | ||
| 197 | 206 | /// Returns whether a start state for `line` is already cached. |
|
| 198 | 207 | pub fn is_state_cached(&self, line: usize) -> bool { |
|
| 199 | - | self.states.get(line).is_some_and(Option::is_some) |
|
| 208 | + | self.cache.states.get(line).is_some_and(Option::is_some) |
|
| 200 | 209 | } |
|
| 201 | 210 | ||
| 202 | 211 | /// Invalidates cached states after a changed line. |
|
| 203 | 212 | pub fn invalidate_from(&mut self, line: usize) { |
|
| 204 | - | let start = line.saturating_add(1).min(self.states.len()); |
|
| 205 | - | for state in &mut self.states[start..] { |
|
| 213 | + | let start = line.saturating_add(1).min(self.cache.states.len()); |
|
| 214 | + | for state in &mut self.cache.states[start..] { |
|
| 206 | 215 | *state = None; |
|
| 207 | 216 | } |
|
| 208 | - | let start = line.min(self.scopes.len()); |
|
| 209 | - | for scopes in &mut self.scopes[start..] { |
|
| 217 | + | let start = line.min(self.cache.scopes.len()); |
|
| 218 | + | for scopes in &mut self.cache.scopes[start..] { |
|
| 210 | 219 | *scopes = None; |
|
| 211 | 220 | } |
|
| 212 | 221 | } |
|
| 213 | 222 | ||
| 214 | 223 | /// Ensures the parser state at the start of `line` is cached. |
|
| 215 | 224 | pub fn ensure_state(&mut self, line: usize) -> Option<&LineState> { |
|
| 216 | 225 | if line > self.line_count() { |
|
| 217 | 226 | return None; |
|
| 218 | 227 | } |
|
| 219 | - | if self.states[line].is_none() { |
|
| 228 | + | if self.cache.states[line].is_none() { |
|
| 220 | 229 | let state = self.compute_state(line)?; |
|
| 221 | - | self.states[line] = Some(state); |
|
| 230 | + | self.cache.states[line] = Some(state); |
|
| 222 | 231 | } |
|
| 223 | - | self.states[line].as_ref() |
|
| 232 | + | self.cache.states[line].as_ref() |
|
| 224 | 233 | } |
|
| 225 | 234 | ||
| 226 | 235 | /// Tokenizes one line into a caller-owned buffer. |
|
| 227 | 236 | pub fn highlight_line_into(&mut self, line: usize, scopes: &mut Vec<ScopeSpan>) -> bool { |
|
| 228 | 237 | if line >= self.line_count() { |
| 236 | 245 | let range = self.line_range_unchecked(line); |
|
| 237 | 246 | let text = &self.text[range]; |
|
| 238 | 247 | ||
| 239 | 248 | tokenize_or_cache_into( |
|
| 240 | 249 | &mut self.tokenizer, |
|
| 241 | - | &mut self.states, |
|
| 242 | - | &mut self.scopes, |
|
| 250 | + | &mut self.cache.states, |
|
| 251 | + | &mut self.cache.scopes, |
|
| 243 | 252 | &mut state, |
|
| 244 | 253 | line, |
|
| 245 | 254 | text, |
|
| 246 | 255 | scopes, |
|
| 247 | 256 | ); |
| 267 | 276 | let byte_range = self.line_range_unchecked(line_index); |
|
| 268 | 277 | let text = &self.text[byte_range.clone()]; |
|
| 269 | 278 | ||
| 270 | 279 | tokenize_or_cache_into( |
|
| 271 | 280 | &mut self.tokenizer, |
|
| 272 | - | &mut self.states, |
|
| 273 | - | &mut self.scopes, |
|
| 281 | + | &mut self.cache.states, |
|
| 282 | + | &mut self.cache.scopes, |
|
| 274 | 283 | &mut state, |
|
| 275 | 284 | line_index, |
|
| 276 | 285 | text, |
|
| 277 | 286 | &mut scopes, |
|
| 278 | 287 | ); |
| 304 | 313 | let byte_range = self.line_range_unchecked(line_index); |
|
| 305 | 314 | let text = &self.text[byte_range.clone()]; |
|
| 306 | 315 | ||
| 307 | 316 | tokenize_or_cache_into( |
|
| 308 | 317 | &mut self.tokenizer, |
|
| 309 | - | &mut self.states, |
|
| 310 | - | &mut self.scopes, |
|
| 318 | + | &mut self.cache.states, |
|
| 319 | + | &mut self.cache.scopes, |
|
| 311 | 320 | &mut state, |
|
| 312 | 321 | line_index, |
|
| 313 | 322 | text, |
|
| 314 | - | &mut self.buffer.scopes, |
|
| 323 | + | &mut self.cache.buffer.scopes, |
|
| 315 | 324 | ); |
|
| 316 | - | self.buffer.style(grammar, theme, text); |
|
| 325 | + | self.cache.buffer.style(grammar, theme, text); |
|
| 317 | 326 | ||
| 318 | 327 | f(StyledLine { |
|
| 319 | 328 | line_index, |
|
| 320 | 329 | byte_range, |
|
| 321 | 330 | text, |
|
| 322 | - | scopes: &self.buffer.scopes, |
|
| 323 | - | styles: &self.buffer.styles, |
|
| 331 | + | scopes: &self.cache.buffer.scopes, |
|
| 332 | + | styles: &self.cache.buffer.styles, |
|
| 324 | 333 | }); |
|
| 325 | 334 | } |
|
| 326 | 335 | } |
|
| 327 | 336 | ||
| 328 | 337 | /// Tokenizes a line range into an owned output vector. |
| 346 | 355 | } |
|
| 347 | 356 | ||
| 348 | 357 | /// Computes the parser state at the start of `line` from the nearest cached predecessor. |
|
| 349 | 358 | fn compute_state(&mut self, line: usize) -> Option<LineState> { |
|
| 350 | 359 | let mut index = line; |
|
| 351 | - | while index > 0 && self.states[index].is_none() { |
|
| 360 | + | while index > 0 && self.cache.states[index].is_none() { |
|
| 352 | 361 | index -= 1; |
|
| 353 | 362 | } |
|
| 354 | - | let mut state = self.states[index].clone().unwrap_or_default(); |
|
| 363 | + | let mut state = self.cache.states[index].clone().unwrap_or_default(); |
|
| 355 | 364 | let mut scratch = Vec::new(); |
|
| 356 | 365 | ||
| 357 | 366 | while index < line { |
|
| 358 | 367 | let range = self.line_range_unchecked(index); |
|
| 359 | 368 | let text = &self.text[range]; |
|
| 360 | 369 | ||
| 361 | 370 | self.tokenizer |
|
| 362 | 371 | .tokenize_line_into(&mut state, text, &mut scratch); |
|
| 363 | 372 | ||
| 364 | 373 | index += 1; |
|
| 365 | - | self.states[index] = Some(state.clone()); |
|
| 374 | + | self.cache.states[index] = Some(state.clone()); |
|
| 366 | 375 | } |
|
| 367 | 376 | Some(state) |
|
| 368 | 377 | } |
|
| 369 | 378 | ||
| 370 | 379 | /// Returns a line's byte range without checking that the line index exists. |
|
| 371 | 380 | fn line_range_unchecked(&self, line: usize) -> Range<usize> { |
|
| 372 | - | let start = self.line_starts[line]; |
|
| 381 | + | let start = self.cache.line_starts[line]; |
|
| 373 | 382 | let mut end = self |
|
| 383 | + | .cache |
|
| 374 | 384 | .line_starts |
|
| 375 | 385 | .get(line + 1) |
|
| 376 | 386 | .copied() |
|
| 377 | 387 | .unwrap_or(self.text.len()); |
|
| 378 | 388 | let bytes = self.text.as_bytes(); |
| 384 | 394 | } |
|
| 385 | 395 | start..end |
|
| 386 | 396 | } |
|
| 387 | 397 | } |
|
| 388 | 398 | ||
| 399 | + | impl BlobCache { |
|
| 400 | + | /// Rebuilds this cache if `text` has a different line layout. |
|
| 401 | + | fn reset_for(&mut self, text: &str) { |
|
| 402 | + | let line_starts = line_starts(text); |
|
| 403 | + | if self.line_starts == line_starts { |
|
| 404 | + | return; |
|
| 405 | + | } |
|
| 406 | + | self.line_starts = line_starts; |
|
| 407 | + | self.states.clear(); |
|
| 408 | + | self.states.resize(self.line_starts.len() + 1, None); |
|
| 409 | + | self.states[0] = Some(LineState::default()); |
|
| 410 | + | self.scopes.clear(); |
|
| 411 | + | self.scopes.resize(self.line_starts.len(), None); |
|
| 412 | + | self.buffer.clear(); |
|
| 413 | + | } |
|
| 414 | + | } |
|
| 415 | + | ||
| 389 | 416 | /// Tokenizes a line or copies its cached scopes and following parser state. |
|
| 390 | 417 | fn tokenize_or_cache_into( |
|
| 391 | 418 | tokenizer: &mut LineTokenizer<'_>, |
|
| 392 | 419 | states: &mut [Option<LineState>], |
|
| 393 | 420 | scopes_cache: &mut [Option<Vec<ScopeSpan>>], |
crates/highlight/src/lib.rs
+1 -1
| 27 | 27 | pub mod json; |
|
| 28 | 28 | ||
| 29 | 29 | #[cfg(feature = "syntaxes")] |
|
| 30 | 30 | pub mod syntaxes; |
|
| 31 | 31 | ||
| 32 | - | pub use blob::{BlobHighlighter, LineBuffer, LineTokens, OwnedLineTokens, StyledLine}; |
|
| 32 | + | pub use blob::{BlobCache, BlobHighlighter, LineBuffer, LineTokens, OwnedLineTokens, StyledLine}; |
|
| 33 | 33 | pub use error::Error; |
|
| 34 | 34 | pub use grammar::{Grammar, GrammarKind, LineState, LineTokenizer, ScopeId, ScopeSpan}; |
|
| 35 | 35 | pub use raw::{RawCapture, RawGrammar, RawPattern, RawStyle, RawTheme, RawThemeRule}; |
|
| 36 | 36 | pub use registry::{GrammarQuery, Registry}; |
|
| 37 | 37 | pub use theme::{FontStyle, Rgb, Style, StyleSpan, Theme}; |
crates/highlight/src/tests.rs
+14 -0
| 753 | 753 | assert!(inside_comment); |
|
| 754 | 754 | assert!(blob.is_state_cached(2)); |
|
| 755 | 755 | assert!(blob.is_state_cached(4)); |
|
| 756 | 756 | } |
|
| 757 | 757 | ||
| 758 | + | #[test] |
|
| 759 | + | fn blob_cache_can_be_reused_across_highlighters() { |
|
| 760 | + | let grammar = test_grammar(); |
|
| 761 | + | let text = "let a\n/* comment\ninside\n*/ let b\nlet c"; |
|
| 762 | + | let mut first = BlobHighlighter::new(&grammar, text); |
|
| 763 | + | ||
| 764 | + | first.highlight_range(2..4, |_| {}); |
|
| 765 | + | let cache = first.into_cache(); |
|
| 766 | + | let second = BlobHighlighter::with_cache(&grammar, text, cache); |
|
| 767 | + | ||
| 768 | + | assert!(second.is_state_cached(2)); |
|
| 769 | + | assert!(second.is_state_cached(4)); |
|
| 770 | + | } |
|
| 771 | + | ||
| 758 | 772 | #[test] |
|
| 759 | 773 | fn blob_highlighter_collects_owned_ranges() { |
|
| 760 | 774 | let grammar = test_grammar(); |
|
| 761 | 775 | let mut blob = BlobHighlighter::new(&grammar, "let a\nlet b\n"); |
|
| 762 | 776 | let lines = blob.highlighted_range(1..3); |