scrive_core/highlight.rs
1//! Syntax highlighting — a GUI-free public surface over a private syntect
2//! engine. **Syntect is named only inside this module**; nothing from it
3//! crosses the `pub` line, so the GUI crate never has to pin syntect's version.
4//!
5//! The core is **language-agnostic**: the grammar is an app-supplied
6//! `.sublime-syntax`, injected as text (`SyntaxDef::from_sublime_syntax`), and
7//! the theme an app-supplied `.tmTheme` (`TokenTheme::from_tm_theme`);
8//! scrive-core ships neither.
9//!
10//! # Two entry points
11//!
12//! [`Highlighter::highlight`] tokenizes the whole document top-to-bottom on each
13//! call (state carried line to line) — correct but O(lines), used as the
14//! convergence oracle in tests. Production reads go through [`HighlightCache`],
15//! the incremental engine: geometric shift on edit ([`HighlightCache::on_commit`]),
16//! lazy end-state convergence ([`HighlightCache::tokenize_until`]), and full
17//! invalidation on theme change ([`HighlightCache::set_theme`]). Untokenized
18//! lines return `None` and render in the default style — never an error or a
19//! stall. Each drive tokenizes at most [`HIGHLIGHT_MAX_LINES_PER_CALL`] lines,
20//! so no single call can stall a frame however far a cascade wants to run.
21//!
22//! Retention is **virtualized** so RAM does not grow with the idle sweep:
23//! spans + per-line states live only in a window around the viewport
24//! ([`HighlightCache::set_window`]); everywhere else, sparse checkpoints
25//! ([`HIGHLIGHT_CHECKPOINT_STRIDE`]) keep every row re-derivable. A fully swept
26//! document holds `O(window + lines/stride)`, not `O(lines)` — see
27//! [`HighlightCache`] for the mechanics.
28
29use core::ops::Range;
30use std::io::Cursor;
31use std::sync::Arc;
32
33use crate::buffer::Snapshot;
34use crate::sum_tree::{Dimension, Item, Summary, SumTree};
35
36use syntect::highlighting::{
37 FontStyle, HighlightState, Highlighter as SyntectHighlighter, RangedHighlightIterator, Style,
38 Theme, ThemeSet,
39};
40use syntect::parsing::{ParseState, ScopeStack, SyntaxDefinition, SyntaxReference, SyntaxSet, SyntaxSetBuilder};
41
42/// A GUI-free color; scrive-iced maps it to `iced::Color` at render time.
43#[derive(Copy, Clone, PartialEq, Eq, Debug)]
44pub struct Rgba {
45 /// Red.
46 pub r: u8,
47 /// Green.
48 pub g: u8,
49 /// Blue.
50 pub b: u8,
51 /// Alpha.
52 pub a: u8,
53}
54
55/// Resolved inline style for one run — the theme is consulted at tokenize time
56/// (syntect's highlight iterator already yields resolved styles), so nothing
57/// downstream re-touches syntect.
58#[derive(Copy, Clone, PartialEq, Eq, Debug)]
59pub struct SpanStyle {
60 /// Foreground color.
61 pub fg: Rgba,
62 /// Bold.
63 pub bold: bool,
64 /// Italic.
65 pub italic: bool,
66}
67
68/// One styled run within a single buffer line. `range` is **bytes within the
69/// line** (not document offsets), so it survives line-local repair and drops
70/// straight onto a display chunk; byte→cell conversion happens only at render.
71#[derive(Clone, PartialEq, Eq, Debug)]
72pub struct HighlightSpan {
73 /// Byte range within the line.
74 pub range: Range<u32>,
75 /// The run's resolved style.
76 pub style: SpanStyle,
77}
78
79/// Failed to parse an injected `.sublime-syntax` grammar.
80#[derive(Debug, thiserror::Error)]
81#[error("invalid .sublime-syntax grammar: {0}")]
82pub struct SyntaxError(String);
83
84/// Failed to parse a `.tmTheme`.
85#[derive(Debug, thiserror::Error)]
86#[error("invalid .tmTheme: {0}")]
87pub struct ThemeError(String);
88
89/// A parsed grammar. The app supplies a validated `.sublime-syntax` definition;
90/// scrive-core ships no grammar of its own and stays language-agnostic.
91pub struct SyntaxDef {
92 set: SyntaxSet,
93 name: String,
94}
95
96impl SyntaxDef {
97 /// Parse an injected `.sublime-syntax` grammar (LF-only lines, no trailing
98 /// newline in the regexes).
99 pub fn from_sublime_syntax(s: &str) -> Result<Self, SyntaxError> {
100 let syntax =
101 SyntaxDefinition::load_from_str(s, false, None).map_err(|e| SyntaxError(e.to_string()))?;
102 let name = syntax.name.clone();
103 let mut builder = SyntaxSetBuilder::new();
104 builder.add(syntax);
105 Ok(Self { set: builder.build(), name })
106 }
107
108 /// The syntax reference to parse with — the one injected grammar.
109 fn reference(&self) -> &SyntaxReference {
110 self.set
111 .find_syntax_by_name(&self.name)
112 .or_else(|| self.set.syntaxes().first())
113 .expect("the injected grammar is in its own set")
114 }
115}
116
117/// Convert a syntect `(Style, byte range)` to a public [`HighlightSpan`] — the
118/// one place a resolved style crosses out of syntect.
119fn span_from(style: Style, range: Range<usize>) -> HighlightSpan {
120 HighlightSpan {
121 range: range.start as u32..range.end as u32,
122 style: SpanStyle {
123 fg: Rgba {
124 r: style.foreground.r,
125 g: style.foreground.g,
126 b: style.foreground.b,
127 a: style.foreground.a,
128 },
129 bold: style.font_style.contains(FontStyle::BOLD),
130 italic: style.font_style.contains(FontStyle::ITALIC),
131 },
132 }
133}
134
135/// A parsed highlight theme — opaque over syntect's `Theme`. `Clone` is cheap
136/// (a syntect `Theme` is a small style table), so an integrating widget can
137/// retain a theme and re-apply it across a document reload or grammar swap.
138#[derive(Clone)]
139pub struct TokenTheme(Theme);
140
141impl TokenTheme {
142 /// Parse a `.tmTheme` (plist).
143 pub fn from_tm_theme(s: &str) -> Result<Self, ThemeError> {
144 ThemeSet::load_from_reader(&mut Cursor::new(s))
145 .map(TokenTheme)
146 .map_err(|e| ThemeError(e.to_string()))
147 }
148}
149
150/// A whole-document highlighter over a grammar + theme. Owns both; syntect stays
151/// private behind it.
152pub struct Highlighter {
153 syntax: SyntaxDef,
154 theme: TokenTheme,
155}
156
157impl Highlighter {
158 /// A highlighter over an injected grammar and theme.
159 #[must_use]
160 pub fn new(syntax: SyntaxDef, theme: TokenTheme) -> Self {
161 Self { syntax, theme }
162 }
163
164 /// Tokenize `text` (LF-only) into per-line spans — one `Vec` per line
165 /// (including the trailing empty final line), each span a byte range within
166 /// its line. State is carried line to line, so multi-line constructs resolve.
167 #[must_use]
168 pub fn highlight(&self, text: &str) -> Vec<Vec<HighlightSpan>> {
169 let syntect = SyntectHighlighter::new(&self.theme.0);
170 let mut state = LineState {
171 parse: ParseState::new(self.syntax.reference()),
172 highlight: HighlightState::new(&syntect, ScopeStack::new()),
173 };
174 text.split('\n')
175 .map(|line| {
176 let (spans, next) = tokenize_line(&syntect, &self.syntax.set, &state, line);
177 state = next;
178 spans
179 })
180 .collect()
181 }
182}
183
184/// The per-line carry state — syntect's `(ParseState, HighlightState)`. Its `==`
185/// is the convergence probe: equal end states mean identical tokens downstream
186/// (both halves are `Clone + PartialEq`). Private: no syntect type crosses the
187/// module boundary.
188#[derive(Clone, PartialEq)]
189struct LineState {
190 parse: ParseState,
191 highlight: HighlightState,
192}
193
194/// Tokenize one line from `start`, returning its spans and its **end** state
195/// (the start state for the next line). A parse error falls back to no spans,
196/// carrying the start state forward unchanged so the tokenize loop cannot spin.
197fn tokenize_line(
198 syntect: &SyntectHighlighter<'_>,
199 set: &SyntaxSet,
200 start: &LineState,
201 line: &str,
202) -> (Vec<HighlightSpan>, LineState) {
203 let mut end = start.clone();
204 let ops = end.parse.parse_line(line, set).unwrap_or_default();
205 let spans = RangedHighlightIterator::new(&mut end.highlight, &ops, line, syntect)
206 .map(|(style, _text, range)| span_from(style, range))
207 .collect();
208 (spans, end)
209}
210
211/// Per-call tokenize budget, expressed as an op count — deterministic and
212/// testable, unlike wall-clock. At ~2–20 µs of syntect per line this is
213/// roughly 0.5–5 ms per call, so one drive can never stall a frame however
214/// far a state-changing cascade wants to run; the idle sweep resumes where
215/// the budget stopped.
216pub const HIGHLIGHT_MAX_LINES_PER_CALL: u32 = 256;
217
218/// Sparse-checkpoint stride, in rows: outside the retention window the cache
219/// keeps one end state per this many tokenized rows (plus each budget-stop
220/// resume point), so any row's start state is re-derivable by tokenizing at
221/// most a stride forward from the checkpoint above it. Memory per fully-swept
222/// document: `lines / stride` states instead of `lines`.
223pub const HIGHLIGHT_CHECKPOINT_STRIDE: u32 = 256;
224
225/// Retention slack, in rows, kept on EACH side of the window handed to
226/// [`HighlightCache::set_window`] — scrolling within the slack costs nothing;
227/// beyond it, evicted rows refill from the nearest checkpoint (budgeted).
228pub const HIGHLIGHT_WINDOW_SLACK: u32 = 512;
229
230/// Hard cap on the retention window's total length, in rows. A collapsed
231/// mega-fold makes the reported visible range span the fold's hidden interior;
232/// capping the window keeps retention bounded there instead of re-growing to
233/// O(document). Rows past the cap render in the fallback style until scrolled
234/// to (which re-aims the window at them); a fold hiding fewer than ~3k rows
235/// still fits entirely.
236pub const HIGHLIGHT_MAX_WINDOW_ROWS: u32 = 4096;
237
238/// The retention/paint window for a viewport: `viewport` padded by
239/// [`HIGHLIGHT_WINDOW_SLACK`] on each side, its length capped at
240/// [`HIGHLIGHT_MAX_WINDOW_ROWS`], and clamped to `[0, n_lines]`. The **one**
241/// owner of this formula: [`HighlightCache::set_window`] (what the cache
242/// *retains*) and any parallel-highlight worker pool (what it speculatively
243/// *paints* and *tokenizes*) must aim at the SAME rows, so both call this
244/// instead of re-deriving it — an integrator running the core's speculative
245/// tokenizer on worker threads cannot drift from the core's retention rule. The
246/// cap is load-bearing: a collapsed mega-fold makes the reported visible range
247/// span the fold's hidden interior, and without it retention (or a pool's
248/// synchronous speculate) would re-grow to O(document).
249#[must_use]
250pub fn padded_highlight_window(viewport: Range<u32>, n_lines: u32) -> Range<u32> {
251 let start = viewport.start.saturating_sub(HIGHLIGHT_WINDOW_SLACK);
252 let end = viewport
253 .end
254 .saturating_add(HIGHLIGHT_WINDOW_SLACK)
255 .min(start.saturating_add(HIGHLIGHT_MAX_WINDOW_ROWS))
256 .min(n_lines)
257 .max(start);
258 start..end
259}
260
261/// Disjoint, ascending dirty-line ranges: the set of lines whose highlight
262/// state has not yet converged. Storing runs (not individual rows) keeps a
263/// commit O(edit + #runs) even when a large file carries a long dirty tail.
264/// All operations are front-biased: `tokenize_until` always consumes the first
265/// dirty row, and edits splice near the front of whatever tail remains, so the
266/// run list stays single-digit in practice (a canary pins that).
267#[derive(Clone, Debug, Default, PartialEq, Eq)]
268struct DirtyRanges(Vec<Range<u32>>);
269
270impl DirtyRanges {
271 /// Every row of an `n`-line document dirty (load / theme change) — ONE
272 /// run covering the document (a `Vec` holding a single `Range` element,
273 /// which is exactly the point of the range-run representation).
274 fn all(n: u32) -> Self {
275 Self((n > 0).then_some(0..n).into_iter().collect())
276 }
277
278 /// The first dirty row, if any — the tokenize frontier.
279 fn first(&self) -> Option<u32> {
280 self.0.first().map(|r| r.start)
281 }
282
283 /// Remove `row`, which MUST be the current first dirty row (the only
284 /// consumption order `tokenize_until` uses). O(1) amortized.
285 fn remove_first(&mut self, row: u32) {
286 debug_assert_eq!(self.first(), Some(row), "consumption is front-only");
287 let r = &mut self.0[0];
288 r.start += 1;
289 if r.start >= r.end {
290 self.0.remove(0);
291 }
292 }
293
294 /// Mark one row dirty (the cascade step) — merging into a neighbouring
295 /// run so the list stays disjoint and non-adjacent. O(log + shift), and
296 /// the cascade inserts at/near the front in practice.
297 fn insert(&mut self, row: u32) {
298 let i = self.0.partition_point(|r| r.end < row);
299 if i < self.0.len() {
300 let r = &mut self.0[i];
301 if r.start <= row && row < r.end {
302 return; // already dirty
303 }
304 if r.end == row {
305 r.end += 1; // extend this run right…
306 if i + 1 < self.0.len() && self.0[i].end == self.0[i + 1].start {
307 let next_end = self.0[i + 1].end;
308 self.0[i].end = next_end; // …merging into the next run
309 self.0.remove(i + 1);
310 }
311 return;
312 }
313 if r.start == row + 1 {
314 r.start = row; // extend this run left
315 return;
316 }
317 }
318 self.0.insert(i, row..row + 1);
319 }
320
321 /// The commit splice: `spans` is the per-edit list of pre-edit line
322 /// spans `(pre_start, old_lines, new_lines)`, ascending and disjoint. Shifts
323 /// existing runs through the combined splices and marks ONLY each edit's own
324 /// post-edit line span dirty — so a scattered multi-caret transaction marks
325 /// O(carets) lines, not the whole first-to-last covering range. One pass and
326 /// one sort of the O(runs + edits) boundary set. A single covering span
327 /// reproduces the classic clip-shift-mark commit splice exactly.
328 fn apply_splices(&mut self, spans: &[(u32, u32, u32)]) {
329 if spans.is_empty() {
330 return;
331 }
332 // `pref[i]` = accumulated line delta of `spans[..i]`. `shift_at(pre)` is
333 // the post-edit displacement of a pre-edit row *not inside* any edit
334 // (rows inside an edit are covered by that edit's new span below), which
335 // is the delta of all edits entirely above it.
336 let mut pref: Vec<i64> = Vec::with_capacity(spans.len() + 1);
337 pref.push(0);
338 for &(_, o, n) in spans {
339 pref.push(pref[pref.len() - 1] + i64::from(n) - i64::from(o));
340 }
341 let shift_at = |pre: u32| -> i64 {
342 let i = spans.partition_point(|s| s.0 + s.1 <= pre);
343 pref[i]
344 };
345 let old_runs = std::mem::take(&mut self.0);
346 let mut out: Vec<Range<u32>> = Vec::with_capacity(old_runs.len() + spans.len());
347 // Existing runs, shifted. `[a + shift(a), b + shift(b))` is a superset
348 // of the shifted gap rows and any spanned edit region (shift is
349 // non-decreasing), which is safe: over-marking dirty only costs re-work,
350 // under-marking would leave a stale color.
351 for r in &old_runs {
352 let a = (i64::from(r.start) + shift_at(r.start)) as u32;
353 let b = (i64::from(r.end) + shift_at(r.end)) as u32;
354 if a < b {
355 out.push(a..b);
356 }
357 }
358 // Each edit's own post-edit new span.
359 for (j, &(ps, _o, n)) in spans.iter().enumerate() {
360 if n > 0 {
361 let post_start = (i64::from(ps) + pref[j]) as u32;
362 out.push(post_start..post_start + n);
363 }
364 }
365 out.sort_unstable_by_key(|r| r.start);
366 // Coalesce touching/overlapping runs back into the ascending-disjoint
367 // invariant `splice`/`clear_range` maintain.
368 let mut merged: Vec<Range<u32>> = Vec::with_capacity(out.len());
369 for r in out {
370 match merged.last_mut() {
371 Some(last) if last.end >= r.start => last.end = last.end.max(r.end),
372 _ => merged.push(r),
373 }
374 }
375 self.0 = merged;
376 }
377
378 /// Total dirty rows (sum of run lengths) — the invalidation size a commit
379 /// scheduled, which the sweep must eventually walk.
380 #[cfg(test)]
381 fn total_rows(&self) -> u32 {
382 self.0.iter().map(|r| r.end - r.start).sum()
383 }
384
385 /// Whether `row` is dirty. Binary search over the ascending disjoint runs.
386 fn contains(&self, row: u32) -> bool {
387 let i = self.0.partition_point(|r| r.end <= row);
388 i < self.0.len() && self.0[i].start <= row
389 }
390
391 /// Clear rows `[range)` from the dirty set — the verified-absorb path: those
392 /// rows' states are proven, so they leave the frontier without being walked.
393 /// Clips each run around the range; the output stays ascending, disjoint,
394 /// and non-adjacent (inputs are, and clipping only shrinks), so front-biased
395 /// consumption is preserved.
396 fn clear_range(&mut self, range: Range<u32>) {
397 if range.start >= range.end {
398 return;
399 }
400 let old = std::mem::take(&mut self.0);
401 let mut out: Vec<Range<u32>> = Vec::with_capacity(old.len() + 1);
402 for r in old {
403 let lo = r.start..r.end.min(range.start); // part below the cleared span
404 let hi = r.start.max(range.end)..r.end; // part at/above it
405 if lo.start < lo.end {
406 out.push(lo);
407 }
408 if hi.start < hi.end {
409 out.push(hi);
410 }
411 }
412 self.0 = out;
413 }
414
415 /// Number of disjoint runs — the canary probe.
416 #[cfg(test)]
417 fn runs(&self) -> usize {
418 self.0.len()
419 }
420}
421
422/// The document-owned **incremental, virtualized** highlight cache.
423///
424/// The *correctness* model is end-state convergence over `DirtyRanges`:
425/// a line is re-tokenized only while its computed end state differs from the
426/// stored one, so an edit repaints just the lines whose state actually
427/// changed. It is driven lazily and budgeted by
428/// [`HighlightCache::tokenize_until`]. **Retention** is what keeps memory
429/// bounded — two facts make it work:
430///
431/// - **Spans are draw output** — nothing but visible rows reads them, so they
432/// are retained only inside a *dense window* (the viewport ±
433/// [`HIGHLIGHT_WINDOW_SLACK`], set via [`HighlightCache::set_window`]),
434/// together with per-line end states there (so a keystroke at the caret
435/// still converges per-line).
436/// - **States exist to be resumed from** — and any row's state is
437/// re-derivable by tokenizing forward, so outside the window only sparse
438/// *checkpoints* survive: one per [`HIGHLIGHT_CHECKPOINT_STRIDE`] tokenized
439/// rows plus each budget-stop resume point. A cold jump refills the window
440/// from the nearest checkpoint (≤ a stride of warm-up, budgeted; the rows
441/// render in the fallback style until filled).
442///
443/// Convergence verification is per-line inside the window and
444/// checkpoint-grain outside (an out-of-window cascade may run up to one
445/// stride past where a fully-dense cache would have stopped — bounded, and
446/// such edits are rare: you edit what you see). Memory for a fully swept
447/// document: `O(window + lines / stride)` instead of `O(lines)`.
448pub struct HighlightCache {
449 /// `Arc`-shared so [`HighlightCache::engine`] hands an off-thread worker
450 /// the SAME immutable grammar/theme without a deep `SyntaxSet` clone.
451 syntax: Arc<SyntaxDef>,
452 theme: Arc<TokenTheme>,
453 /// Everything the walks mutate — split from the grammar/theme so the
454 /// borrow of `theme` inside a live `SyntectHighlighter` stays disjoint
455 /// from the retention mutations.
456 ret: Retention,
457}
458
459/// The virtualized retention state (see [`HighlightCache`]).
460struct Retention {
461 /// Buffer line count (the commit path keeps it in step).
462 n_lines: u32,
463 /// Dirty-line runs — the correctness frontier: lines not yet converged.
464 invalid: DirtyRanges,
465 /// The last window AIM (the rows handed to `set_window`, pre-padding) —
466 /// preserved across grammar swaps so `set_syntax` keeps retention aimed at
467 /// the viewport instead of silently resetting to the document top.
468 aim: Range<u32>,
469 /// The dense retention window: rows `[win.start, win.end)`.
470 win: Range<u32>,
471 /// Spans for window rows (`None` ⇒ fallback / not yet filled).
472 win_spans: Vec<Option<Vec<HighlightSpan>>>,
473 /// End states for window rows — the per-line convergence probes.
474 win_states: Vec<Option<Box<LineState>>>,
475 /// Sparse end-state checkpoints, ascending by row — a delta-gap
476 /// [`SumTree`]: reads are an O(log) seek and the per-keystroke
477 /// [`Checkpoints::shift`] mover rewrites one seam gap rather than the whole
478 /// list. Holds stride rows plus budget-stop resume points; splices shift
479 /// them like every other line-indexed structure.
480 checkpoints: Checkpoints,
481}
482
483// Manual (syntect's `Theme`/state aren't all `Debug`, and they'd be noise
484// anyway); lets `Document` keep its `#[derive(Debug)]`.
485impl core::fmt::Debug for HighlightCache {
486 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
487 f.debug_struct("HighlightCache")
488 .field("lines", &self.ret.n_lines)
489 .field("window", &self.ret.win)
490 .field("checkpoints", &self.ret.checkpoints.len())
491 .field("dirty", &self.ret.invalid)
492 .finish_non_exhaustive()
493 }
494}
495
496// ======================================================================
497// Sparse end-state checkpoints — a delta-gap `SumTree`.
498//
499// One of the delta-gap `SumTree` structures (shared with decorations, folds,
500// and brackets): every read is an O(log) seek, the per-keystroke mover
501// (`shift`) shifts a suffix by rewriting ONE seam gap, and only a scattered
502// MULTI-edit commit falls back to the correctness-first O(#checkpoints) walk.
503// `row_gap` is this checkpoint's row minus the previous one's (a prefix sum
504// over `RowDim` recovers the absolute row); `state` is the end state after
505// that row — opaque and heavy (a syntect `LineState`), the copy-on-write cost
506// the `benches/perf.rs` checkpoint case pins.
507// ======================================================================
508
509/// One sparse checkpoint leaf. `row_gap` = this checkpoint's row minus the
510/// previous checkpoint's row (delta-gap, so a suffix shift rewrites just one
511/// gap); `state` = the end state after that row.
512struct CkptItem {
513 row_gap: u32,
514 state: Box<LineState>,
515}
516
517impl Clone for CkptItem {
518 fn clone(&self) -> Self {
519 Self { row_gap: self.row_gap, state: self.state.clone() }
520 }
521}
522
523// `LineState` is deliberately not `Debug` (syntect's parse/highlight state is
524// noise) — the same reason `HighlightCache`'s `Debug` is manual. `Item` demands
525// `Debug`, so show the shape without the state.
526impl core::fmt::Debug for CkptItem {
527 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
528 f.debug_struct("CkptItem").field("row_gap", &self.row_gap).finish_non_exhaustive()
529 }
530}
531
532/// Subtree aggregate: `rows` = Σ row_gaps (the [`RowDim`] absolute-row extent),
533/// `count` = item count (the [`CkptIx`] index extent). Both additive monoids, so
534/// a suffix shift is invariant under a uniform row displacement.
535#[derive(Clone, Copy, Debug, Default)]
536struct CkptSummary {
537 rows: u32,
538 count: u32,
539}
540
541impl Summary for CkptSummary {
542 fn add_summary(&mut self, o: &Self) {
543 self.rows += o.rows;
544 self.count += o.count;
545 }
546}
547
548impl Item for CkptItem {
549 type Summary = CkptSummary;
550 fn summary(&self) -> CkptSummary {
551 CkptSummary { rows: self.row_gap, count: 1 }
552 }
553}
554
555/// Dimension: absolute row — accumulates each item's `row_gap` (a prefix sum),
556/// so an item's `RowDim`-end is its absolute checkpoint row.
557#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
558struct RowDim(u32);
559impl Dimension<CkptSummary> for RowDim {
560 fn add_summary(&mut self, s: &CkptSummary) {
561 self.0 += s.rows;
562 }
563}
564
565/// Dimension: item index — accumulates `count`. Writes split/replace by index
566/// (a delta-gap item is located at its row, not a byte offset), mirroring the
567/// decoration and bracket trees.
568#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
569struct CkptIx(u32);
570impl Dimension<CkptSummary> for CkptIx {
571 fn add_summary(&mut self, s: &CkptSummary) {
572 self.0 += s.count;
573 }
574}
575
576/// Re-anchor `suffix`'s first item onto a rebuilt head: its absolute row becomes
577/// `old_row + delta` and its predecessor is now at `prev_row`, so its single
578/// `row_gap` is rewritten while every later gap stays relative and untouched — a
579/// whole-suffix shift in O(log). `k_hi` is that item's index in `orig` (read
580/// only for its old absolute row). A port of the decoration tree's `reanchor`
581/// (oracle-proven there); the heavy `state` is cloned exactly once.
582fn reanchor(
583 suffix: &SumTree<CkptItem>,
584 k_hi: u32,
585 orig: &SumTree<CkptItem>,
586 delta: i64,
587 prev_row: u32,
588) -> SumTree<CkptItem> {
589 if suffix.is_empty() {
590 return suffix.clone();
591 }
592 let (item, _c, RowDim(r)) = orig
593 .seek::<CkptIx, RowDim>(&CkptIx(k_hi))
594 .expect("suffix non-empty ⇒ a k_hi-th item exists");
595 let first_old_row = r + item.row_gap;
596 let new_gap = (i64::from(first_old_row) + delta - i64::from(prev_row)) as u32;
597 let fixed = CkptItem { row_gap: new_gap, state: item.state.clone() };
598 suffix.replace(CkptIx(0)..CkptIx(1), std::iter::once(fixed))
599}
600
601/// Sparse end-state checkpoints as a delta-gap [`SumTree`]. See the module
602/// section header above for the structure and its cost model.
603struct Checkpoints {
604 tree: SumTree<CkptItem>,
605}
606
607impl Checkpoints {
608 fn new() -> Self {
609 Self { tree: SumTree::new() }
610 }
611
612 /// Number of checkpoints — an O(1) root-summary read.
613 fn len(&self) -> usize {
614 self.tree.summary().count as usize
615 }
616
617 #[cfg(test)]
618 fn is_empty(&self) -> bool {
619 self.tree.is_empty()
620 }
621
622 fn clear(&mut self) {
623 self.tree = SumTree::new();
624 }
625
626 /// The state stored EXACTLY at `row`, or `None`. O(log). The `stored_state_after`
627 /// checkpoint probe.
628 fn state_at(&self, row: u32) -> Option<&LineState> {
629 let n_le = self.tree.summary_before(&RowDim(row.saturating_add(1))).count; // abs_row <= row
630 let n_lt = self.tree.summary_before(&RowDim(row)).count; // abs_row < row
631 if n_le == n_lt {
632 return None; // nothing sits at exactly `row`
633 }
634 let (item, _ix, RowDim(before)) = self.tree.seek::<CkptIx, RowDim>(&CkptIx(n_lt))?;
635 debug_assert_eq!(before + item.row_gap, row, "state_at must land exactly on `row`");
636 Some(&*item.state)
637 }
638
639 /// The nearest checkpoint at or before `row`: `(abs_row, &state)`, or `None`.
640 /// O(log). The warm-up floor.
641 fn floor(&self, row: u32) -> Option<(u32, &LineState)> {
642 let n_le = self.tree.summary_before(&RowDim(row.saturating_add(1))).count; // abs_row <= row
643 let idx = n_le.checked_sub(1)?; // none at or before `row`
644 let (item, _ix, RowDim(before)) = self.tree.seek::<CkptIx, RowDim>(&CkptIx(idx))?;
645 Some((before + item.row_gap, &*item.state))
646 }
647
648 /// Replace the state of the checkpoint at index `i`, keeping its `row_gap`
649 /// (its position). O(log).
650 fn replace_state_at_index(&mut self, i: u32, state: LineState) {
651 let gap = {
652 let (item, _ix, _rd) =
653 self.tree.seek::<CkptIx, RowDim>(&CkptIx(i)).expect("index in range");
654 item.row_gap
655 };
656 self.tree = self
657 .tree
658 .replace(CkptIx(i)..CkptIx(i + 1), std::iter::once(CkptItem { row_gap: gap, state: Box::new(state) }));
659 }
660
661 /// Insert a new checkpoint at absolute `row` (which must NOT already exist)
662 /// at index `i`: mint its delta-gap onto its predecessor and re-relativize the
663 /// successor's now-orphaned gap at one seam. Insertion moves no rows, so the
664 /// suffix re-anchors with `delta = 0`. O(log).
665 fn insert_at(&mut self, i: u32, row: u32, state: LineState) {
666 let (left, right) = self.tree.split_at(&CkptIx(i));
667 let pred = left.extent::<RowDim>().0; // abs_row of item i-1 (0 if none)
668 let mid = SumTree::from_items(std::iter::once(CkptItem {
669 row_gap: row - pred,
670 state: Box::new(state),
671 }));
672 // The successor keeps its absolute row; only its predecessor changed to
673 // `row`, so it re-anchors with delta 0.
674 let right_fixed = reanchor(&right, i, &self.tree, 0, row);
675 self.tree = left.append(&mid).append(&right_fixed);
676 }
677
678 /// Insert a checkpoint at `row`, or refresh the state if one already sits
679 /// there. O(log).
680 fn upsert(&mut self, row: u32, state: LineState) {
681 let n_le = self.tree.summary_before(&RowDim(row.saturating_add(1))).count; // abs_row <= row
682 let n_lt = self.tree.summary_before(&RowDim(row)).count; // abs_row < row
683 if n_le > n_lt {
684 self.replace_state_at_index(n_lt, state); // exact match at index n_lt
685 } else {
686 self.insert_at(n_lt, row, state);
687 }
688 }
689
690 /// Refresh the state at `row` ONLY if a checkpoint already sits there (a
691 /// drifted off-grid pin a fresh tokenize just re-derived); a no-op otherwise.
692 /// O(log).
693 fn refresh_if_present(&mut self, row: u32, state: LineState) {
694 let n_le = self.tree.summary_before(&RowDim(row.saturating_add(1))).count;
695 let n_lt = self.tree.summary_before(&RowDim(row)).count;
696 if n_le > n_lt {
697 self.replace_state_at_index(n_lt, state);
698 }
699 }
700
701 /// Insert/refresh a stride-aligned checkpoint at `row`, then drop the
702 /// off-grid pins within one stride behind it (drifted pins and old resume
703 /// points, redundant once this one lands). THE one owner of the
704 /// sparse-checkpoint rule. O(log + pruned).
705 fn set_stride(&mut self, row: u32, state: LineState) {
706 self.upsert(row, state);
707 self.prune_behind(row);
708 }
709
710 /// Drop the off-grid checkpoints strictly between `row - stride` and `row`
711 /// (exclusive of both an exact-`floor` pin and `row` itself) — redundant once
712 /// a stride checkpoint lands at `row`. `row`'s checkpoint keeps its absolute
713 /// position; only its `row_gap` re-relativizes onto the surviving predecessor.
714 /// O(log + pruned).
715 fn prune_behind(&mut self, row: u32) {
716 let floor = row.saturating_sub(HIGHLIGHT_CHECKPOINT_STRIDE);
717 let k_lo = self.tree.summary_before(&RowDim(floor.saturating_add(1))).count; // abs_row <= floor
718 let k_hi = self.tree.summary_before(&RowDim(row)).count; // abs_row < row
719 if k_hi <= k_lo {
720 return; // nothing off-grid behind `row`
721 }
722 let (left, rest) = self.tree.split_at(&CkptIx(k_lo));
723 let (_dropped, right) = rest.split_at(&CkptIx(k_hi - k_lo));
724 // `right` starts with `row`'s checkpoint (abs_row == row); it stays put
725 // (delta 0), re-gapped onto the last surviving item at/below `floor`.
726 let right_fixed = reanchor(&right, k_hi, &self.tree, 0, left.extent::<RowDim>().0);
727 self.tree = left.append(&right_fixed);
728 }
729
730 /// Shift checkpoints through a commit's per-edit line splices `(pre_start,
731 /// old_lines, new_lines)` (ascending, disjoint) — the per-keystroke mover,
732 /// run on EVERY commit and every undo step (`on_commit_patch`). A single
733 /// edit takes the O(edit + log) windowed path; a scattered multi-edit
734 /// commit falls back to the correctness-first O(#checkpoints) walk.
735 fn shift(&mut self, spans: &[(u32, u32, u32)]) {
736 if spans.is_empty() {
737 return;
738 }
739 if spans.len() == 1 {
740 self.shift_single(spans[0]);
741 } else {
742 self.shift_walk(spans);
743 }
744 }
745
746 /// The single-edit fast path: drop the (usually 0) checkpoints inside the
747 /// replaced rows `[s, s+o)` and shift the suffix `[s+o, ∞)` by the line delta
748 /// at ONE seam. O(edit + log). Charges only the checkpoints actually TOUCHED
749 /// (dropped band + the one re-anchor seam), so a keystroke far from any
750 /// checkpoint is flat in the checkpoint count.
751 fn shift_single(&mut self, (s, o, n): (u32, u32, u32)) {
752 let d = i64::from(n) - i64::from(o);
753 let k_lo = self.tree.summary_before(&RowDim(s)).count; // abs_row < s
754 let k_hi = self.tree.summary_before(&RowDim(s + o)).count; // abs_row < s+o
755 let dropped = k_hi - k_lo;
756 crate::perf::charge(u64::from(dropped) + 1);
757 if dropped == 0 && d == 0 {
758 return; // nothing dropped, nothing shifts — tree untouched
759 }
760 let (left, rest) = self.tree.split_at(&CkptIx(k_lo));
761 let (_dropped, suffix) = rest.split_at(&CkptIx(k_hi - k_lo));
762 let pred = left.extent::<RowDim>().0;
763 let suffix_fixed = reanchor(&suffix, k_hi, &self.tree, d, pred);
764 self.tree = left.append(&suffix_fixed);
765 }
766
767 /// The multi-edit fallback: decode to absolute `(row, state)`, run the
768 /// merge (drop checkpoints inside any edit, shift the rest by the cumulative
769 /// delta of all edits entirely above them), rebuild. O(#checkpoints +
770 /// edits). Charges per checkpoint walked — the cost the perf gate meters, so
771 /// the single-edit seam path stays the norm.
772 fn shift_walk(&mut self, spans: &[(u32, u32, u32)]) {
773 let old = self.tree.items();
774 let mut out: Vec<CkptItem> = Vec::with_capacity(old.len());
775 let mut si = 0usize;
776 let mut acc = 0i64;
777 let mut abs = 0u32; // running absolute row of the current checkpoint
778 let mut prev_out = 0u32; // last emitted absolute row (delta-gap re-encode)
779 for item in old {
780 crate::perf::charge(1); // walks every checkpoint — the O(#checkpoints) cost
781 abs += item.row_gap;
782 while si < spans.len() && spans[si].0 + spans[si].1 <= abs {
783 acc += i64::from(spans[si].2) - i64::from(spans[si].1);
784 si += 1;
785 }
786 if si < spans.len() && abs >= spans[si].0 {
787 continue; // inside a replaced span → the stored state is stale
788 }
789 let new_abs = (i64::from(abs) + acc) as u32;
790 out.push(CkptItem { row_gap: new_abs - prev_out, state: item.state });
791 prev_out = new_abs;
792 }
793 self.tree = SumTree::from_items(out);
794 }
795
796 /// Build a checkpoint tree from ascending absolute `rows` sharing one `state`
797 /// — the perf-cell / oracle seed (no real sweep required).
798 #[cfg(test)]
799 fn from_rows(rows: &[u32], state: &LineState) -> Self {
800 let mut prev = 0u32;
801 let items: Vec<CkptItem> = rows
802 .iter()
803 .map(|&r| {
804 let gap = r - prev;
805 prev = r;
806 CkptItem { row_gap: gap, state: Box::new(state.clone()) }
807 })
808 .collect();
809 Self { tree: SumTree::from_items(items) }
810 }
811
812 /// The absolute checkpoint rows, ascending — the oracle handle.
813 #[cfg(test)]
814 fn rows(&self) -> Vec<u32> {
815 let mut abs = 0u32;
816 self.tree
817 .items()
818 .iter()
819 .map(|it| {
820 abs += it.row_gap;
821 abs
822 })
823 .collect()
824 }
825}
826
827/// How [`Retention::start_state_for`] answers: the start state is stored, is
828/// the fresh document-top state, or must be warmed up by tokenizing forward
829/// from the nearest earlier stored state (`WarmupFresh` ⇒ from row 0).
830enum StartState {
831 Ready(LineState),
832 Fresh,
833 WarmupStored(u32, LineState),
834 WarmupFresh,
835}
836
837impl HighlightCache {
838 /// A cache for an `n_lines` document over an injected grammar + theme:
839 /// every line invalid, nothing retained. The retention window defaults to
840 /// the document top (2 × [`HIGHLIGHT_WINDOW_SLACK`] rows) — right for a
841 /// freshly opened view; the app re-aims it per viewport report via
842 /// [`HighlightCache::set_window`].
843 #[must_use]
844 pub fn new(syntax: SyntaxDef, theme: TokenTheme, n_lines: u32) -> Self {
845 let win = 0..(2 * HIGHLIGHT_WINDOW_SLACK).min(n_lines);
846 let len = win.len();
847 Self {
848 syntax: Arc::new(syntax),
849 theme: Arc::new(theme),
850 ret: Retention {
851 n_lines,
852 invalid: DirtyRanges::all(n_lines),
853 aim: win.clone(),
854 win,
855 win_spans: vec![None; len],
856 win_states: vec![None; len],
857 checkpoints: Checkpoints::new(),
858 },
859 }
860 }
861
862 /// The first dirty row, if any — `None` means every line's state has
863 /// converged (spans may still be evicted outside the window; see
864 /// [`HighlightCache::pending`], which the sweep polls instead).
865 #[must_use]
866 pub fn first_dirty(&self) -> Option<u32> {
867 self.ret.invalid.first()
868 }
869
870 /// The next row a budgeted [`HighlightCache::tokenize_until`] call would
871 /// work on: the first dirty row, or — once states have converged — the
872 /// first window row whose spans await a refill (a window move over
873 /// already-swept rows). `None` = nothing to do (the idle-zero-work probe;
874 /// the app's sweep keys its subscription off this).
875 #[must_use]
876 pub fn pending(&self) -> Option<u32> {
877 let dirt = self.ret.invalid.first();
878 let gap = self.ret.first_window_gap(dirt.unwrap_or(u32::MAX));
879 match (dirt, gap) {
880 (Some(d), Some(g)) => Some(d.min(g)),
881 (d, g) => d.or(g),
882 }
883 }
884
885 /// The cached spans for a line, or `None` if the row is outside the
886 /// retention window or not yet tokenized/refilled (the caller renders
887 /// that line in the default style — never an error, never a stall).
888 #[must_use]
889 pub fn line_spans(&self, row: u32) -> Option<&[HighlightSpan]> {
890 self.ret.win_spans[self.ret.win_idx(row)?].as_deref()
891 }
892
893 /// How many lines the cache is sized for — must track the buffer's line
894 /// count (the commit path keeps them equal).
895 #[must_use]
896 pub fn line_count(&self) -> u32 {
897 self.ret.n_lines
898 }
899
900 /// The last rows handed to [`HighlightCache::set_window`] (pre-padding) —
901 /// `Document::set_syntax` re-aims a replacement cache with this so a
902 /// grammar swap keeps retention at the viewport instead of silently
903 /// resetting to the document top.
904 #[must_use]
905 pub fn window_aim(&self) -> Range<u32> {
906 self.ret.aim.clone()
907 }
908
909 /// Aim the retention window at `rows` (the viewport, in buffer rows) —
910 /// the cache retains `rows` ± [`HIGHLIGHT_WINDOW_SLACK`] and evicts
911 /// outside. Repositioning is O(window); rows entering the window refill
912 /// on the next [`HighlightCache::tokenize_until`] (see
913 /// [`HighlightCache::pending`]).
914 pub fn set_window(&mut self, rows: Range<u32>) {
915 let r = &mut self.ret;
916 r.aim = rows.clone();
917 // The padded, length-capped window through the ONE owner
918 // (`padded_highlight_window`), shared with any parallel-highlight pool so
919 // the rows the cache retains and the rows a pool paints cannot drift.
920 let win = padded_highlight_window(rows, r.n_lines);
921 let (start, end) = (win.start, win.end);
922 if (start..end) == r.win {
923 return;
924 }
925 let len = (end - start) as usize;
926 let mut spans = vec![None; len];
927 let mut states = vec![None; len];
928 for row in start.max(r.win.start)..end.min(r.win.end) {
929 let old_i = (row - r.win.start) as usize;
930 let new_i = (row - start) as usize;
931 spans[new_i] = r.win_spans[old_i].take();
932 states[new_i] = r.win_states[old_i].take();
933 }
934 r.win = start..end;
935 r.win_spans = spans;
936 r.win_states = states;
937 }
938
939 /// The commit hook: buffer lines `[start, start+old)` became `new` lines.
940 /// Splices the window (keeping the **old end state of the last edited
941 /// line** as the convergence probe in the new last slot), drops replaced
942 /// checkpoints and shifts the rest, and marks `[start, start+new)` dirty.
943 /// O(edit + window + #checkpoints); the cascade waits for `tokenize_until`.
944 pub fn on_commit(&mut self, start: u32, old: u32, new: u32) {
945 // A single edit as one line splice. Multi-edit commits use the per-edit
946 // spans directly (see `on_commit_patch`).
947 self.on_commit_patch(&[(start, old, new)]);
948 }
949
950 /// The commit hook, given the **per-edit** pre-edit line spans `(pre_start,
951 /// old_lines, new_lines)` (ascending, disjoint). Checkpoints, the dense
952 /// window, and the dirty runs all ride the per-edit spans — NOT the whole
953 /// transaction's first-to-last covering range. A scattered multi-caret
954 /// transaction has a document-scale covering range but O(carets) tiny spans,
955 /// so this keeps the commit (and the sweep it schedules) O(carets + window +
956 /// checkpoints), and — critically — leaves the retention window aimed at the
957 /// viewport: only the actually-edited in-window rows are invalidated, so the
958 /// visible rows recolor on the next tokenize instead of going stale until a
959 /// scroll re-aims the window.
960 pub fn on_commit_patch(&mut self, spans: &[(u32, u32, u32)]) {
961 if spans.is_empty() {
962 return;
963 }
964 let r = &mut self.ret;
965 let delta: i64 = spans.iter().map(|&(_, o, n)| i64::from(n) - i64::from(o)).sum();
966 // Checkpoints: drop only those inside an actual edit and shift the rest
967 // by the per-edit deltas — scattered carets must not wipe every
968 // checkpoint between the first and last (a cold-jump refill needs them).
969 r.checkpoints.shift(spans);
970 // Window: shift through the per-edit spans, staying aimed at the viewport.
971 r.shift_window(spans);
972 // Dirty runs: mark ONLY each edit's own post-edit line span.
973 r.invalid.apply_splices(spans);
974 r.n_lines = (r.n_lines as i64 + delta) as u32;
975 }
976
977 /// Tokenize toward `target` (inclusive), lazily and budgeted, and return
978 /// **how many lines were tokenized** (warm-up included) — the op count
979 /// the perf canaries assert on. Two phases share the `max_lines` budget:
980 ///
981 /// 1. **The dirty walk** — dense convergence semantics: each first-dirty
982 /// line tokenizes from its start state (stored, or warmed up from the
983 /// nearest checkpoint); if its new end state differs from the stored
984 /// one the cascade continues, otherwise it stops (convergence).
985 /// Where no state is stored to compare against (outside the window,
986 /// between checkpoints) the cascade keeps going until one is — at
987 /// most a stride more than a fully-dense cache would have done.
988 /// 2. **The window refill** — rows inside the retention window whose
989 /// spans were evicted (a window move over already-swept text) are
990 /// re-derived from the nearest checkpoint. Only rows below the dirty
991 /// frontier are fillable (states past dirt are unverified).
992 ///
993 /// `line(i)` hands back line i's text — an ACCESSOR, never an all-lines
994 /// Vec, so this never materializes the whole document. A budget stop
995 /// records a resume checkpoint so the next call continues without re-warming.
996 pub fn tokenize_until<S: AsRef<str>>(
997 &mut self,
998 target: u32,
999 max_lines: u32,
1000 mut line: impl FnMut(u32) -> S,
1001 ) -> u32 {
1002 let syntect = SyntectHighlighter::new(&self.theme.0);
1003 let syntax = &*self.syntax;
1004 let fresh = || LineState {
1005 parse: ParseState::new(syntax.reference()),
1006 highlight: HighlightState::new(&syntect, ScopeStack::new()),
1007 };
1008 let ret = &mut self.ret;
1009 let mut work = 0u32;
1010
1011 // Phase 1 — the dirty walk.
1012 'walk: while work < max_lines {
1013 let Some(first) = ret.invalid.first() else { break };
1014 if first > target {
1015 break;
1016 }
1017 let started = match ret.start_state_for(first) {
1018 StartState::Ready(s) => Some(s),
1019 StartState::Fresh => Some(fresh()),
1020 StartState::WarmupStored(r, s) => ret
1021 .warm_up(Some(r), first, s, &mut work, max_lines, &syntect, &syntax.set, &mut line),
1022 StartState::WarmupFresh => ret
1023 .warm_up(None, first, fresh(), &mut work, max_lines, &syntect, &syntax.set, &mut line),
1024 };
1025 let Some(mut state) = started else { break 'walk }; // budget died mid-warm-up
1026 let mut row = first;
1027 loop {
1028 if work >= max_lines {
1029 ret.keep_resume_checkpoint(row.checked_sub(1), &state);
1030 break 'walk;
1031 }
1032 let (spans, end) = tokenize_line(&syntect, &syntax.set, &state, line(row).as_ref());
1033 // Probe BEFORE retain overwrites; nothing stored ⇒ unverifiable
1034 // ⇒ keep cascading.
1035 let converged = ret.stored_state_after(row).is_some_and(|old| *old == end);
1036 ret.retain(row, spans, &end);
1037 ret.invalid.remove_first(row);
1038 work += 1;
1039 state = end;
1040 if converged || row + 1 >= ret.n_lines {
1041 break;
1042 }
1043 ret.invalid.insert(row + 1);
1044 if row + 1 > target {
1045 break; // beyond the caller's viewport — the sweep's job
1046 }
1047 row += 1;
1048 }
1049 }
1050
1051 // Phase 2 — the window refill.
1052 'fill: while work < max_lines {
1053 let dirt = ret.invalid.first().unwrap_or(u32::MAX);
1054 let Some(gap) = ret.first_window_gap(dirt) else { break };
1055 let started = match ret.start_state_for(gap) {
1056 StartState::Ready(s) => Some(s),
1057 StartState::Fresh => Some(fresh()),
1058 StartState::WarmupStored(r, s) => ret
1059 .warm_up(Some(r), gap, s, &mut work, max_lines, &syntect, &syntax.set, &mut line),
1060 StartState::WarmupFresh => ret
1061 .warm_up(None, gap, fresh(), &mut work, max_lines, &syntect, &syntax.set, &mut line),
1062 };
1063 let Some(mut state) = started else { break 'fill };
1064 let end_row = ret.win.end.min(ret.n_lines).min(dirt);
1065 let mut row = gap;
1066 while row < end_row {
1067 if work >= max_lines {
1068 ret.keep_resume_checkpoint(row.checked_sub(1), &state);
1069 break 'fill;
1070 }
1071 if ret.win_spans[(row - ret.win.start) as usize].is_some() {
1072 if let Some(s) = ret.stored_state_after(row) {
1073 state = s.clone(); // hop an already-filled row
1074 row += 1;
1075 continue;
1076 }
1077 }
1078 let (spans, end) = tokenize_line(&syntect, &syntax.set, &state, line(row).as_ref());
1079 ret.retain(row, spans, &end);
1080 work += 1;
1081 state = end;
1082 row += 1;
1083 }
1084 }
1085 work
1086 }
1087
1088 /// Swap the theme and invalidate the whole cache: a theme change is a full
1089 /// invalidation because syntect resolves colors at tokenize time, so every
1090 /// line's styles change and must be re-tokenized. States and checkpoints
1091 /// are dropped and every line marked dirty; the **old window spans are kept
1092 /// as a stale fallback** so the view keeps showing the outgoing theme's
1093 /// colors (not a flash to default) until the frontier repaints them on the
1094 /// next `tokenize_until`.
1095 pub fn set_theme(&mut self, theme: TokenTheme) {
1096 self.theme = Arc::new(theme);
1097 self.ret.win_states.fill(None);
1098 self.ret.checkpoints.clear();
1099 self.ret.invalid = DirtyRanges::all(self.ret.n_lines);
1100 }
1101
1102 /// A cheap-to-clone, `Send + Sync` handle to this cache's grammar + theme,
1103 /// for off-thread bulk tokenization (the parallel/speculative sweep).
1104 /// Shares the `Arc`-held grammar/theme — no `SyntaxSet` deep clone.
1105 #[must_use]
1106 pub fn engine(&self) -> HighlightEngine {
1107 HighlightEngine { syntax: self.syntax.clone(), theme: self.theme.clone() }
1108 }
1109
1110 /// Ingest a segment tokenized off-thread (parallel/speculative sweep). The
1111 /// caller ([`crate::Document::absorb_highlight`]) guarantees the segment
1112 /// was computed at the current revision, so `rows`/checkpoints align with
1113 /// this cache.
1114 ///
1115 /// - `verified` — the coordinator chained this segment from row 0, so its
1116 /// start state (and thus its whole result) is TRUE. Merge its stride
1117 /// checkpoints (through the one [`Checkpoints::set_stride`]
1118 /// owner, so the set matches a sync walk), write its window spans+states
1119 /// into the current retention window, and **clear `rows` from the dirty
1120 /// set** — this replaces the foreground dirty walk for that span.
1121 /// - `!verified` — viewport speculation from a GUESSED fresh start. Write
1122 /// window spans+states ONLY into window rows that are still dirty (never
1123 /// clobber verified data), and **never plant a checkpoint**: an
1124 /// unverified state outside the window would poison a later warm-up.
1125 /// Dirt is untouched, so the frontier re-verifies
1126 /// these rows per-line and converges in O(1) if the guess was right; a
1127 /// dirty row's state is only ever read as a convergence probe, never as
1128 /// a warm-up source (that reads `first_dirty − 1`, which is clean).
1129 pub(crate) fn absorb(&mut self, seg: SegmentTokens, verified: bool) {
1130 let r = &mut self.ret;
1131 let SegmentTokens { rows, checkpoints, win, win_spans, win_states, .. } = seg;
1132 if verified {
1133 for (row, state) in checkpoints {
1134 r.checkpoints.set_stride(row, *state);
1135 }
1136 // Evict window rows this segment COVERS but did not SUPPLY spans
1137 // for: they are about to be marked clean, so any speculative span
1138 // there would survive as trusted-but-unverified (poison). `None`
1139 // renders as fallback and is refilled from the (correct)
1140 // checkpoints by the sync window sweep. Supplied rows are written
1141 // below, so they show correct colors with no flash.
1142 let cover = rows.start.max(r.win.start)..rows.end.min(r.win.end);
1143 for row in cover {
1144 if !win.contains(&row) {
1145 let i = (row - r.win.start) as usize;
1146 r.win_spans[i] = None;
1147 r.win_states[i] = None;
1148 }
1149 }
1150 for ((row, spans), state) in win.zip(win_spans).zip(win_states) {
1151 if let Some(i) = r.win_idx(row) {
1152 r.win_spans[i] = Some(spans);
1153 r.win_states[i] = Some(Box::new(state));
1154 }
1155 }
1156 r.invalid.clear_range(rows);
1157 } else {
1158 for ((row, spans), state) in win.zip(win_spans).zip(win_states) {
1159 // Only still-dirty window rows: never clobber verified spans,
1160 // and a dirty row's state is a probe, not a warm-up source.
1161 if r.invalid.contains(row) {
1162 if let Some(i) = r.win_idx(row) {
1163 r.win_spans[i] = Some(spans);
1164 r.win_states[i] = Some(Box::new(state));
1165 }
1166 }
1167 }
1168 }
1169 }
1170
1171 // Test-only retention probes — the memory canaries count entries, the
1172 // deterministic op-count analog of an RSS measurement.
1173 #[cfg(test)]
1174 fn retained_span_rows(&self) -> usize {
1175 self.ret.win_spans.iter().filter(|s| s.is_some()).count()
1176 }
1177 #[cfg(test)]
1178 fn window_len(&self) -> usize {
1179 debug_assert_eq!(self.ret.win_spans.len(), self.ret.win_states.len());
1180 self.ret.win_spans.len()
1181 }
1182 #[cfg(test)]
1183 fn dirty_row_count(&self) -> u32 {
1184 self.ret.invalid.total_rows()
1185 }
1186 #[cfg(test)]
1187 fn retained_state_rows(&self) -> usize {
1188 self.ret.win_states.iter().filter(|s| s.is_some()).count() + self.ret.checkpoints.len()
1189 }
1190}
1191
1192// ======================================================================
1193// Off-thread bulk tokenization (parallel + speculative sweep).
1194//
1195// The retention cache above serves the UI thread synchronously. On a
1196// multi-million-line document the top-down state chain would make a
1197// jump-to-bottom render fall back to plain text for ~16-20s of single-core
1198// work. Instead the app tokenizes SEGMENTS off-thread over an O(1) `Snapshot`
1199// clone, from GUESSED fresh states, and STITCHES boundaries with the same
1200// convergence rule the cache uses per line: segment i's true end state equals
1201// segment i+1's guessed (fresh) start iff everything downstream is provably
1202// identical. A viewport segment is shown immediately (speculative); the full
1203// document is verified left-to-right and absorbed. All threading is the APP's;
1204// this layer is pure and sync, syntect stays sealed.
1205// ======================================================================
1206
1207/// A cheap-to-clone, `Send + Sync` handle to a grammar + theme for off-thread
1208/// bulk tokenization. Nothing syntect crosses its surface; [`SegmentBoundary`]
1209/// and [`SegmentTokens`] are opaque. Obtain via [`HighlightCache::engine`] (to
1210/// share the cache's exact grammar/theme) or [`HighlightEngine::new`], and move
1211/// clones to worker threads.
1212#[derive(Clone)]
1213pub struct HighlightEngine {
1214 syntax: Arc<SyntaxDef>,
1215 theme: Arc<TokenTheme>,
1216}
1217
1218impl HighlightEngine {
1219 /// An engine over an injected grammar + theme (mirrors [`Highlighter::new`]).
1220 #[must_use]
1221 pub fn new(syntax: SyntaxDef, theme: TokenTheme) -> Self {
1222 Self { syntax: Arc::new(syntax), theme: Arc::new(theme) }
1223 }
1224
1225 /// The document-top fresh start state, as a boundary. The coordinator
1226 /// compares a segment's guessed `Fresh` start against a prior segment's
1227 /// true end with this: equal => the guess was right, the segment verifies
1228 /// as-is; unequal => re-run from the true end.
1229 #[must_use]
1230 pub fn fresh_boundary(&self) -> SegmentBoundary {
1231 SegmentBoundary(Box::new(self.fresh_state()))
1232 }
1233
1234 fn fresh_state(&self) -> LineState {
1235 let syntect = SyntectHighlighter::new(&self.theme.0);
1236 LineState {
1237 parse: ParseState::new(self.syntax.reference()),
1238 highlight: HighlightState::new(&syntect, ScopeStack::new()),
1239 }
1240 }
1241}
1242
1243/// The per-line carry state at a segment edge - opaque, comparable, sendable.
1244/// Two edges compare equal iff everything downstream is provably identical
1245/// (the convergence theorem: same state + same text => same tokens).
1246#[derive(Clone, PartialEq)]
1247pub struct SegmentBoundary(Box<LineState>);
1248
1249/// Where a segment's tokenization begins.
1250pub enum SegmentStart {
1251 /// From the document-top fresh state - a speculative guess, or genuinely
1252 /// row 0.
1253 Fresh,
1254 /// From a known boundary (a prior segment's verified end state).
1255 After(SegmentBoundary),
1256}
1257
1258/// One segment tokenized off-thread - opaque; ingested by
1259/// [`crate::Document::absorb_highlight`]. Carries stride checkpoints, the end
1260/// boundary, and (for a requested sub-range) dense window spans+states.
1261pub struct SegmentTokens {
1262 rows: Range<u32>,
1263 started_fresh: bool,
1264 /// Stride-aligned end-state checkpoints within `rows` (rows where
1265 /// `(row + 1) % HIGHLIGHT_CHECKPOINT_STRIDE == 0`) - the SAME rows the
1266 /// sync walk would pick, so [`HighlightCache::absorb`] merges them cleanly.
1267 checkpoints: Vec<(u32, Box<LineState>)>,
1268 /// End state after `rows.end - 1` (equals the start state if `rows` empty).
1269 end: SegmentBoundary,
1270 /// The captured window sub-range (subset of `rows`) and its dense data.
1271 win: Range<u32>,
1272 win_spans: Vec<Vec<HighlightSpan>>,
1273 win_states: Vec<LineState>,
1274 /// How many rows were actually tokenized (a converging re-run splices the
1275 /// rest from the old segment): `rows.len()` on a full run, less on an
1276 /// early-stop repair. The op-count the repair-bound canary asserts on, and
1277 /// a progress signal for the app.
1278 tokenized: u32,
1279}
1280
1281impl SegmentTokens {
1282 /// The rows this segment covers.
1283 #[must_use]
1284 pub fn rows(&self) -> Range<u32> {
1285 self.rows.clone()
1286 }
1287
1288 /// How many rows this segment actually tokenized (`< rows().len()` when a
1289 /// converging re-run spliced a proven-identical tail from the old segment).
1290 #[must_use]
1291 pub fn tokenized_rows(&self) -> u32 {
1292 self.tokenized
1293 }
1294
1295 /// The end-of-segment boundary (the true state after `rows.end - 1` once
1296 /// this segment is verified) - what the coordinator chains the next
1297 /// segment's verification against.
1298 #[must_use]
1299 pub fn end_boundary(&self) -> &SegmentBoundary {
1300 &self.end
1301 }
1302
1303 /// Whether this segment started from the fresh (guessed) state.
1304 #[must_use]
1305 pub fn started_fresh(&self) -> bool {
1306 self.started_fresh
1307 }
1308
1309 fn checkpoint_at(&self, row: u32) -> Option<&LineState> {
1310 self.checkpoints.binary_search_by_key(&row, |(r, _)| *r).ok().map(|i| &*self.checkpoints[i].1)
1311 }
1312}
1313
1314/// Tokenize `rows` of `snapshot` off-thread - pure, sync, unbudgeted (the app
1315/// runs it on a worker over an O(1) [`Snapshot`] clone). Records stride
1316/// checkpoints and, for `spans_for` intersected with `rows`, dense
1317/// spans+states.
1318///
1319/// `converge_against`: when RE-running a segment from a corrected start (a
1320/// speculative guess proved wrong), pass the old result. At each stride
1321/// checkpoint the new end state is compared with the old's; on the first match
1322/// the tail is spliced verbatim from the old (provably identical downstream) -
1323/// so repair costs O(distance to the construct's close), not O(segment). Pass
1324/// it on a re-run whose `rows` match the old segment's; **the window is forced
1325/// to the old segment's** (the passed `spans_for` is ignored when
1326/// `converge_against` is `Some`), so the caller need not track which window
1327/// the old segment was tokenized with — the splice stays internally consistent
1328/// even if the viewport moved since.
1329#[must_use]
1330pub fn tokenize_segment(
1331 engine: &HighlightEngine,
1332 snapshot: &Snapshot,
1333 rows: Range<u32>,
1334 start: SegmentStart,
1335 spans_for: Option<Range<u32>>,
1336 converge_against: Option<&SegmentTokens>,
1337) -> SegmentTokens {
1338 let syntect = SyntectHighlighter::new(&engine.theme.0);
1339 let set = &engine.syntax.set;
1340 let started_fresh = matches!(start, SegmentStart::Fresh);
1341 let mut state = match start {
1342 SegmentStart::Fresh => engine.fresh_state(),
1343 SegmentStart::After(b) => *b.0,
1344 };
1345
1346 let n = snapshot.line_count();
1347 let lo = rows.start.min(n);
1348 let hi = rows.end.min(n);
1349 // A converging re-run splices the old segment's window tail, so its window
1350 // MUST equal the old segment's — enforce that here regardless of the
1351 // caller's `spans_for`. The coordinator can dispatch a re-run with a moved
1352 // viewport's `spans_for` while `converge_against` still carries the original
1353 // window; honoring the moved one would splice mismatched rows. When
1354 // re-running, the window IS the old segment's window.
1355 let win = match converge_against {
1356 Some(old) => old.win.clone(),
1357 None => spans_for
1358 .map(|w| w.start.max(lo)..w.end.min(hi))
1359 .filter(|w| w.start < w.end)
1360 .unwrap_or(lo..lo),
1361 };
1362
1363 let mut checkpoints: Vec<(u32, Box<LineState>)> = Vec::new();
1364 let mut win_spans: Vec<Vec<HighlightSpan>> = Vec::with_capacity(win.len());
1365 let mut win_states: Vec<LineState> = Vec::with_capacity(win.len());
1366
1367 let mut row = lo;
1368 while row < hi {
1369 let line = snapshot.line(row);
1370 let (spans, end) = tokenize_line(&syntect, set, &state, line.as_ref());
1371 if win.contains(&row) {
1372 win_spans.push(spans);
1373 win_states.push(end.clone());
1374 }
1375 state = end;
1376 if (row + 1).is_multiple_of(HIGHLIGHT_CHECKPOINT_STRIDE) {
1377 checkpoints.push((row, Box::new(state.clone())));
1378 // Early-stop against the old segment on a corrected re-run: the
1379 // new state after `row` matching the old's checkpoint there means
1380 // every later row is provably identical - splice the old tail.
1381 if let Some(old) = converge_against {
1382 if old.checkpoint_at(row).is_some_and(|s| *s == state) {
1383 debug_assert_eq!(win, old.win, "the window was forced to old.win above");
1384 for (r, s) in &old.checkpoints {
1385 if *r > row {
1386 checkpoints.push((*r, s.clone()));
1387 }
1388 }
1389 for (k, wr) in old.win.clone().enumerate() {
1390 if wr > row {
1391 win_spans.push(old.win_spans[k].clone());
1392 win_states.push(old.win_states[k].clone());
1393 }
1394 }
1395 return SegmentTokens {
1396 rows,
1397 started_fresh,
1398 checkpoints,
1399 end: old.end.clone(),
1400 win,
1401 win_spans,
1402 win_states,
1403 tokenized: row - lo + 1, // rows lo..=row were run
1404 };
1405 }
1406 }
1407 }
1408 row += 1;
1409 }
1410
1411 SegmentTokens {
1412 rows,
1413 started_fresh,
1414 checkpoints,
1415 end: SegmentBoundary(Box::new(state)),
1416 win,
1417 win_spans,
1418 win_states,
1419 tokenized: hi - lo,
1420 }
1421}
1422
1423impl Retention {
1424 /// The window slot for `row`, if it is inside the retention window (and
1425 /// the document).
1426 fn win_idx(&self, row: u32) -> Option<usize> {
1427 (self.win.contains(&row) && row < self.n_lines).then(|| (row - self.win.start) as usize)
1428 }
1429
1430 /// Move the dense retention window through the per-edit line splices,
1431 /// keeping it aimed at the same buffer rows: a row above an edit shifts by
1432 /// that edit's line delta, a row inside an edit loses its now-stale span but
1433 /// keeps a convergence probe (the edit's old end state) so a state-neutral
1434 /// keystroke still converges in O(1), and rows below are untouched. Because
1435 /// it rides the per-edit spans (not one covering range), a SCATTERED
1436 /// multi-caret edit whose first-to-last span engulfs the window neither
1437 /// drains nor repositions it — the visible rows stay in the window and
1438 /// recolor on the next tokenize, rather than going stale until a scroll
1439 /// fires `set_window`. Bounded to [`HIGHLIGHT_MAX_WINDOW_ROWS`];
1440 /// O(window + edits).
1441 fn shift_window(&mut self, spans: &[(u32, u32, u32)]) {
1442 if spans.is_empty() {
1443 return;
1444 }
1445 let b = HIGHLIGHT_MAX_WINDOW_ROWS as usize;
1446 let mut pref: Vec<i64> = Vec::with_capacity(spans.len() + 1);
1447 pref.push(0);
1448 for &(_, o, n) in spans {
1449 pref.push(pref[pref.len() - 1] + i64::from(n) - i64::from(o));
1450 }
1451 // Displacement of a pre-edit row NOT inside any edit = delta of edits
1452 // entirely above it.
1453 let shift_at = |pre: u32| -> i64 { pref[spans.partition_point(|s| s.0 + s.1 <= pre)] };
1454 let edited = |pre: u32| -> bool {
1455 let i = spans.partition_point(|s| s.0 + s.1 <= pre);
1456 i < spans.len() && pre >= spans[i].0
1457 };
1458 // Convergence probes: each edit's OLD end state (of its last old row),
1459 // read BEFORE the window moves, keyed by the post row it lands on.
1460 let mut probes: Vec<(u32, Box<LineState>)> = Vec::new();
1461 for (j, &(ps, o, n)) in spans.iter().enumerate() {
1462 if n == 0 {
1463 continue;
1464 }
1465 if let Some(st) = self.stored_state_after(ps + o - 1) {
1466 let post = (i64::from(ps) + pref[j]) as u32 + n - 1;
1467 probes.push((post, Box::new(st.clone())));
1468 }
1469 }
1470 let old_start = self.win.start;
1471 let new_start = (i64::from(old_start) + shift_at(old_start)) as u32;
1472 let old_spans = std::mem::take(&mut self.win_spans);
1473 let old_states = std::mem::take(&mut self.win_states);
1474 // Survivors: window rows not inside an edit, at their post positions —
1475 // `(post row, spans, end state)`.
1476 type Survivor = (u32, Option<Vec<HighlightSpan>>, Option<Box<LineState>>);
1477 let mut max_post = new_start;
1478 let mut survivors: Vec<Survivor> = Vec::with_capacity(old_spans.len());
1479 for (idx, (sp, st)) in old_spans.into_iter().zip(old_states).enumerate() {
1480 let pre = old_start + idx as u32;
1481 if edited(pre) {
1482 continue; // edited row → span stale (a probe below drives convergence)
1483 }
1484 let post = (i64::from(pre) + shift_at(pre)) as u32;
1485 max_post = max_post.max(post);
1486 survivors.push((post, sp, st));
1487 }
1488 for (r, _) in &probes {
1489 max_post = max_post.max(*r);
1490 }
1491 let len = ((max_post + 1).saturating_sub(new_start) as usize).min(b);
1492 let mut spans_v: Vec<Option<Vec<HighlightSpan>>> = vec![None; len];
1493 let mut states_v: Vec<Option<Box<LineState>>> = vec![None; len];
1494 for (post, sp, st) in survivors {
1495 if let Some(i) = post.checked_sub(new_start).map(|d| d as usize) {
1496 if i < len {
1497 spans_v[i] = sp;
1498 states_v[i] = st;
1499 }
1500 }
1501 }
1502 for (post, probe) in probes {
1503 if let Some(i) = post.checked_sub(new_start).map(|d| d as usize) {
1504 if i < len && states_v[i].is_none() {
1505 states_v[i] = Some(probe);
1506 }
1507 }
1508 }
1509 self.win = new_start..new_start + len as u32;
1510 self.win_spans = spans_v;
1511 self.win_states = states_v;
1512 }
1513
1514 /// The stored end state after `row`: its window slot, else an exact
1515 /// checkpoint. Trustworthy only when `first_dirty()` is above `row` — the
1516 /// invariant that the first dirty line implies every line above it is
1517 /// valid.
1518 fn stored_state_after(&self, row: u32) -> Option<&LineState> {
1519 if let Some(i) = self.win_idx(row) {
1520 if let Some(s) = &self.win_states[i] {
1521 return Some(s);
1522 }
1523 }
1524 self.checkpoints.state_at(row)
1525 }
1526
1527 /// The nearest stored state at or before `row` (window slot or
1528 /// checkpoint), for warm-up.
1529 fn nearest_state_at_or_before(&self, row: u32) -> Option<(u32, &LineState)> {
1530 let cp = self.checkpoints.floor(row);
1531 // A window state can only beat the checkpoint in (cp_row, row] — scan
1532 // down just that far.
1533 let mut ws = None;
1534 if !self.win.is_empty() && self.win.start <= row {
1535 let hi = row.min(self.win.end - 1);
1536 let lo = cp.map_or(self.win.start, |(r, _)| (r + 1).max(self.win.start));
1537 let mut r = hi;
1538 while r >= lo {
1539 if let Some(s) = &self.win_states[(r - self.win.start) as usize] {
1540 ws = Some((r, &**s));
1541 break;
1542 }
1543 if r == lo {
1544 break;
1545 }
1546 r -= 1;
1547 }
1548 }
1549 match (cp, ws) {
1550 (Some(c), Some(w)) => Some(if w.0 >= c.0 { w } else { c }),
1551 (c, w) => w.or(c),
1552 }
1553 }
1554
1555 /// The start state for tokenizing `row`.
1556 fn start_state_for(&self, row: u32) -> StartState {
1557 if row == 0 {
1558 return StartState::Fresh;
1559 }
1560 if let Some(s) = self.stored_state_after(row - 1) {
1561 return StartState::Ready(s.clone());
1562 }
1563 match self.nearest_state_at_or_before(row - 1) {
1564 Some((r, s)) => StartState::WarmupStored(r, s.clone()),
1565 None => StartState::WarmupFresh,
1566 }
1567 }
1568
1569 /// Tokenize the clean rows between `from` (the row whose end state
1570 /// `state` is; `None` ⇒ fresh before row 0) and `to` (exclusive) to
1571 /// re-derive `to`'s start state, retaining as it goes. `None` if the
1572 /// budget dies first (a resume checkpoint is recorded).
1573 #[allow(clippy::too_many_arguments)]
1574 fn warm_up<S: AsRef<str>>(
1575 &mut self,
1576 from: Option<u32>,
1577 to: u32,
1578 mut state: LineState,
1579 work: &mut u32,
1580 max_lines: u32,
1581 syntect: &SyntectHighlighter<'_>,
1582 set: &SyntaxSet,
1583 line: &mut impl FnMut(u32) -> S,
1584 ) -> Option<LineState> {
1585 let mut r = from;
1586 loop {
1587 let next = r.map_or(0, |r| r + 1);
1588 if next >= to {
1589 return Some(state);
1590 }
1591 if *work >= max_lines {
1592 if let Some(r) = r {
1593 self.keep_resume_checkpoint(Some(r), &state);
1594 }
1595 return None;
1596 }
1597 let (spans, end) = tokenize_line(syntect, set, &state, line(next).as_ref());
1598 self.retain(next, spans, &end);
1599 *work += 1;
1600 r = Some(next);
1601 state = end;
1602 }
1603 }
1604
1605 /// Retain one tokenized row: spans + state in the window, a checkpoint at
1606 /// stride rows — and, crucially, a freshly tokenized row REFRESHES any
1607 /// checkpoint already sitting at it. Checkpoints drift off the stride grid
1608 /// (edits shift them; budget stops pin arbitrary rows), and a stale one
1609 /// left below the frontier would poison later warm-ups into permanently
1610 /// wrong colors. Stride inserts also prune the now-redundant off-grid
1611 /// checkpoints in the stride behind them, so drift and old resume pins
1612 /// cannot accumulate.
1613 fn retain(&mut self, row: u32, spans: Vec<HighlightSpan>, end: &LineState) {
1614 if let Some(i) = self.win_idx(row) {
1615 self.win_spans[i] = Some(spans);
1616 self.win_states[i] = Some(Box::new(end.clone()));
1617 }
1618 if (row + 1).is_multiple_of(HIGHLIGHT_CHECKPOINT_STRIDE) {
1619 self.checkpoints.set_stride(row, end.clone());
1620 } else {
1621 // A drifted (off-grid) checkpoint sitting on this freshly tokenized
1622 // row is refreshed so a stale state can't poison a later warm-up; a
1623 // no-op when none is there. Do not prune (it is not stride-aligned).
1624 self.checkpoints.refresh_if_present(row, end.clone());
1625 }
1626 }
1627
1628 /// A budget stop about to abandon the state after `row`: pin it as a
1629 /// checkpoint if nothing stores it, so the next call resumes without
1630 /// re-warming.
1631 fn keep_resume_checkpoint(&mut self, row: Option<u32>, state: &LineState) {
1632 let Some(row) = row else { return }; // before row 0 — fresh is free
1633 if self.stored_state_after(row).is_none() {
1634 self.checkpoints.upsert(row, state.clone());
1635 }
1636 }
1637
1638 /// The first window row below `before` whose spans await a (re)fill.
1639 fn first_window_gap(&self, before: u32) -> Option<u32> {
1640 let end = self.win.end.min(self.n_lines).min(before);
1641 (self.win.start..end).find(|&r| self.win_spans[(r - self.win.start) as usize].is_none())
1642 }
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647 use super::*;
1648
1649 // A one-rule grammar: the word `kw` is a keyword.
1650 const GRAMMAR: &str = "%YAML 1.2\n\
1651 ---\n\
1652 name: Test\n\
1653 scope: source.test\n\
1654 contexts:\n\
1655 \x20 main:\n\
1656 \x20 - match: '\\bkw\\b'\n\
1657 \x20 scope: keyword.control.test\n";
1658
1659 // A minimal theme: default white, keyword red.
1660 const THEME: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
1661<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1662<plist version="1.0"><dict>
1663<key>name</key><string>Test</string>
1664<key>settings</key><array>
1665<dict><key>settings</key><dict><key>background</key><string>#000000</string><key>foreground</key><string>#ffffff</string></dict></dict>
1666<dict><key>scope</key><string>keyword</string><key>settings</key><dict><key>foreground</key><string>#ff0000</string></dict></dict>
1667</array></dict></plist>"#;
1668
1669 fn highlighter() -> Highlighter {
1670 Highlighter::new(
1671 SyntaxDef::from_sublime_syntax(GRAMMAR).expect("grammar parses"),
1672 TokenTheme::from_tm_theme(THEME).expect("theme parses"),
1673 )
1674 }
1675
1676 #[test]
1677 fn keyword_gets_the_keyword_color() {
1678 let lines = highlighter().highlight("kw x");
1679 assert_eq!(lines.len(), 1);
1680 // The `kw` at bytes 0..2 is red; something else is white.
1681 let red = Rgba { r: 0xff, g: 0, b: 0, a: 0xff };
1682 let white = Rgba { r: 0xff, g: 0xff, b: 0xff, a: 0xff };
1683 let kw = lines[0].iter().find(|s| s.range == (0..2)).expect("a span at 0..2");
1684 assert_eq!(kw.style.fg, red);
1685 assert!(lines[0].iter().any(|s| s.style.fg == white), "non-keyword text is default white");
1686 }
1687
1688 #[test]
1689 fn per_line_spans_and_a_trailing_empty_line() {
1690 let lines = highlighter().highlight("kw\nx\n");
1691 assert_eq!(lines.len(), 3); // "kw", "x", "" (trailing)
1692 assert!(lines[0].iter().any(|s| s.range == (0..2))); // "kw" on line 0
1693 assert!(lines[2].is_empty()); // the empty final line has no spans
1694 }
1695
1696 fn cache(n: u32) -> HighlightCache {
1697 HighlightCache::new(
1698 SyntaxDef::from_sublime_syntax(GRAMMAR).unwrap(),
1699 TokenTheme::from_tm_theme(THEME).unwrap(),
1700 n,
1701 )
1702 }
1703
1704 fn lines(text: &str) -> Vec<&str> {
1705 text.split('\n').collect()
1706 }
1707
1708 /// After tokenizing, every cached line must equal a fresh whole-document
1709 /// highlight of the same text — the convergence invariant, whatever the
1710 /// edit path.
1711 fn assert_matches_full(cache: &HighlightCache, text: &str) {
1712 let full = highlighter().highlight(text);
1713 for (row, expected) in full.iter().enumerate() {
1714 assert_eq!(cache.line_spans(row as u32), Some(expected.as_slice()), "line {row}");
1715 }
1716 }
1717
1718 #[test]
1719 fn fresh_cache_matches_whole_document_highlight() {
1720 let text = "kw a\nb kw\nc";
1721 let ls = lines(text);
1722 let mut c = cache(ls.len() as u32);
1723 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1724 assert_matches_full(&c, text);
1725 }
1726
1727 #[test]
1728 fn in_place_edit_reconverges() {
1729 let before = "kw a\nb b\nkw c";
1730 let ls0 = lines(before);
1731 let mut c = cache(ls0.len() as u32);
1732 c.tokenize_until(ls0.len() as u32, u32::MAX, |r| ls0[r as usize]);
1733 // Edit line 1 in place ("b b" -> "b kw"); old == new == 1 line.
1734 let after = "kw a\nb kw\nkw c";
1735 let ls1 = lines(after);
1736 c.on_commit(1, 1, 1);
1737 c.tokenize_until(ls1.len() as u32, u32::MAX, |r| ls1[r as usize]);
1738 assert_matches_full(&c, after);
1739 }
1740
1741 #[test]
1742 fn insert_line_splices_and_reconverges() {
1743 let before = "kw\nx";
1744 let ls0 = lines(before);
1745 let mut c = cache(ls0.len() as u32);
1746 c.tokenize_until(ls0.len() as u32, u32::MAX, |r| ls0[r as usize]);
1747 // Insert a line: line 0 ("kw") becomes two lines ("kw", "y").
1748 let after = "kw\ny\nx";
1749 let ls1 = lines(after);
1750 c.on_commit(0, 1, 2);
1751 c.tokenize_until(ls1.len() as u32, u32::MAX, |r| ls1[r as usize]);
1752 assert_matches_full(&c, after);
1753 }
1754
1755 #[test]
1756 fn theme_swap_invalidates_all_keeps_stale_colors_then_recolors() {
1757 // The same minimal theme, but the keyword is blue instead of red.
1758 const THEME_BLUE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
1759<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1760<plist version="1.0"><dict>
1761<key>name</key><string>Blue</string>
1762<key>settings</key><array>
1763<dict><key>settings</key><dict><key>background</key><string>#000000</string><key>foreground</key><string>#ffffff</string></dict></dict>
1764<dict><key>scope</key><string>keyword</string><key>settings</key><dict><key>foreground</key><string>#0000ff</string></dict></dict>
1765</array></dict></plist>"#;
1766 let red = Rgba { r: 0xff, g: 0, b: 0, a: 0xff };
1767 let blue = Rgba { r: 0, g: 0, b: 0xff, a: 0xff };
1768 let has = |c: &HighlightCache, row: u32, col: Rgba| {
1769 c.line_spans(row).unwrap().iter().any(|s| s.style.fg == col)
1770 };
1771 // Two keyword lines, both tokenized (red).
1772 let ls = lines("kw a\nb kw");
1773 let mut c = cache(ls.len() as u32);
1774 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1775 assert!(has(&c, 0, red) && has(&c, 1, red));
1776 // Swap the theme: every line goes dirty, but the OLD (red) spans stay as
1777 // a stale fallback — no flash to default before the repaint.
1778 c.set_theme(TokenTheme::from_tm_theme(THEME_BLUE).unwrap());
1779 assert!(has(&c, 0, red) && has(&c, 1, red), "stale colors until repainted");
1780 // Repaint the whole cache: the keyword is now blue on every line, no red left.
1781 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1782 assert!(has(&c, 0, blue) && has(&c, 1, blue), "both lines recolored");
1783 assert!(!has(&c, 0, red) && !has(&c, 1, red), "no stale red survives repaint");
1784 }
1785
1786 #[test]
1787 fn convergence_stops_early_below_an_edit() {
1788 // A grammar with no multi-line state ⇒ every line's end state is equal,
1789 // so an in-place edit converges at the edited line and never re-tokenizes
1790 // the (unchanged) line below it. We prove that by leaving the line below
1791 // deliberately WRONG in `lines` — if it were re-tokenized it would change.
1792 let ls0 = lines("kw\nkw\nkw");
1793 let mut c = cache(3);
1794 c.tokenize_until(3, u32::MAX, |r| ls0[r as usize]);
1795 c.on_commit(0, 1, 1); // edit line 0 only
1796 // Pass a lines slice whose line 2 is a sentinel that must NOT be touched.
1797 let probe_lines = ["kw", "kw", "SHOULD-NOT-RETOKENIZE"];
1798 c.tokenize_until(3, u32::MAX, |r| probe_lines[r as usize]);
1799 // Line 2 kept its original "kw" spans (convergence stopped at line 0).
1800 assert_eq!(c.line_spans(2), Some(highlighter().highlight("kw").pop().unwrap().as_slice()));
1801 }
1802
1803 #[test]
1804 fn perf_canary_state_neutral_keystroke_is_o1_regardless_of_size() {
1805 // Op-count canary (not timing): the test grammar has no multi-line
1806 // state, so editing any line converges at that line — a keystroke
1807 // re-tokenizes ~1 line no matter how big the document is. The "no
1808 // O(file) stacking" guarantee: the number is independent of the
1809 // 2000-line size.
1810 let big = vec!["kw x"; 2000].join("\n");
1811 let ls = lines(&big);
1812 let mut c = cache(ls.len() as u32);
1813 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]); // full initial pass
1814 c.on_commit(1000, 1, 1); // a keystroke deep in the document
1815 let n = c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1816 assert!(n <= 2, "state-neutral keystroke re-tokenized {n} lines in a 2000-line doc (expected O(1))");
1817 }
1818
1819 #[test]
1820 fn perf_canary_target_bounds_work_to_the_viewport() {
1821 // Perf canary 1 (the viewport-targeting tooth): tokenizing to a viewport
1822 // target does ≤ viewport work, never O(file) — even with every line dirty
1823 // (a fresh cache, or a top-of-file state cascade). 2000 lines dirty,
1824 // target row 50 → exactly 51 lines tokenized, nothing below.
1825 let big = vec!["kw x"; 2000].join("\n");
1826 let ls = lines(&big);
1827 let mut c = cache(ls.len() as u32); // all 2000 lines dirty
1828 let n = c.tokenize_until(50, u32::MAX, |r| ls[r as usize]);
1829 assert_eq!(n, 51, "target must bound tokenization to the viewport (rows 0..=50)");
1830 assert!(c.line_spans(50).is_some(), "the viewport is tokenized");
1831 assert!(c.line_spans(51).is_none(), "nothing past the viewport target is tokenized");
1832 }
1833
1834 #[test]
1835 fn perf_canary_budget_caps_a_call_and_resumes() {
1836 // The per-call budget: one call does at most `max_lines` of work, the
1837 // frontier records where it stopped, and the next call resumes there —
1838 // total work conserved.
1839 let big = vec!["kw x"; 300].join("\n");
1840 let ls = lines(&big);
1841 let mut c = cache(ls.len() as u32);
1842 let n = c.tokenize_until(u32::MAX, 100, |r| ls[r as usize]);
1843 assert_eq!(n, 100, "the budget caps the call");
1844 assert_eq!(c.first_dirty(), Some(100), "the frontier records the resume point");
1845 let n = c.tokenize_until(u32::MAX, u32::MAX, |r| ls[r as usize]);
1846 assert_eq!(n, 200, "the next call finishes the remainder");
1847 assert_eq!(c.first_dirty(), None, "converged");
1848 }
1849
1850 #[test]
1851 fn perf_canary_deep_dirty_tail_commit_is_cheap() {
1852 // A commit must be O(edit + #runs), independent of how long a dirty
1853 // tail the document carries — storing runs (not individual rows) is
1854 // what makes that hold. Generous wall-clock bound (the one in-test
1855 // timing allowed): 1000 commits against a 1M-line dirty tail must be
1856 // near-instant; a per-commit rebuild of the whole dirty set would take
1857 // tens of seconds.
1858 let mut c = cache(1_000_000); // every line dirty, one run
1859 let t0 = std::time::Instant::now();
1860 for _ in 0..1_000 {
1861 c.on_commit(500_000, 1, 1);
1862 }
1863 assert!(
1864 t0.elapsed() < std::time::Duration::from_secs(1),
1865 "1000 deep-dirty-tail commits took {:?} — the dirty set is being rebuilt per commit",
1866 t0.elapsed()
1867 );
1868 assert!(c.ret.invalid.runs() <= 3, "the run list stays compact: {}", c.ret.invalid.runs());
1869 }
1870
1871 #[test]
1872 fn dirty_runs_stay_small_under_a_typing_run() {
1873 let mut c = cache(2_000);
1874 // Converge everything first.
1875 let big = vec!["kw x"; 2000].join("\n");
1876 let ls = lines(&big);
1877 c.tokenize_until(u32::MAX, u32::MAX, |r| ls[r as usize]);
1878 // A typing run at one spot, plus a couple of scattered edits.
1879 for _ in 0..50 {
1880 c.on_commit(700, 1, 1);
1881 }
1882 c.on_commit(100, 1, 2);
1883 c.on_commit(1500, 2, 1);
1884 assert!(c.ret.invalid.runs() <= 4, "scattered typing produced {} runs", c.ret.invalid.runs());
1885 }
1886
1887 // ------------------------------------------------------------------
1888 // Highlight virtualization: a STATEFUL grammar — an unterminated `"` flips
1889 // every following line into the `string` context — so checkpoints,
1890 // warm-ups, and cross-stride convergence are exercised for real (the `kw`
1891 // grammar above is stateless: every end state is equal, which can never
1892 // distinguish a right checkpoint from a wrong one).
1893 // ------------------------------------------------------------------
1894 const GRAMMAR_STR: &str = "%YAML 1.2\n\
1895 ---\n\
1896 name: TestStr\n\
1897 scope: source.tstr\n\
1898 contexts:\n\
1899 \x20 main:\n\
1900 \x20 - match: '\"'\n\
1901 \x20 scope: punctuation.definition.string.begin\n\
1902 \x20 push: string\n\
1903 \x20 - match: '\\bkw\\b'\n\
1904 \x20 scope: keyword.control.test\n\
1905 \x20 string:\n\
1906 \x20 - match: '\"'\n\
1907 \x20 scope: punctuation.definition.string.end\n\
1908 \x20 pop: true\n\
1909 \x20 - match: '.'\n\
1910 \x20 scope: string.quoted.test\n";
1911
1912 // A grammar with an ASYMMETRIC block comment (`/* … */`): unlike the
1913 // symmetric `"` toggle, a wrong guess about being inside a comment
1914 // SELF-HEALS at the next `*/` (which returns to ground unconditionally),
1915 // so a mis-guessed segment re-CONVERGES — the case the stitch's early-stop
1916 // splice exists for. (`/*` only opens from `main`; `*/` only closes from
1917 // `comment`; neither nests.)
1918 const GRAMMAR_CMT: &str = "%YAML 1.2\n\
1919 ---\n\
1920 name: TestCmt\n\
1921 scope: source.tcmt\n\
1922 contexts:\n\
1923 \x20 main:\n\
1924 \x20 - match: '/\\*'\n\
1925 \x20 scope: punctuation.definition.comment.begin\n\
1926 \x20 push: comment\n\
1927 \x20 - match: '\\bkw\\b'\n\
1928 \x20 scope: keyword.control.test\n\
1929 \x20 comment:\n\
1930 \x20 - match: '\\*/'\n\
1931 \x20 scope: punctuation.definition.comment.end\n\
1932 \x20 pop: true\n\
1933 \x20 - match: '.'\n\
1934 \x20 scope: comment.block.test\n";
1935
1936 fn engine_cmt() -> HighlightEngine {
1937 HighlightEngine::new(
1938 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1939 TokenTheme::from_tm_theme(THEME).unwrap(),
1940 )
1941 }
1942
1943 fn cache_cmt(n: u32) -> HighlightCache {
1944 HighlightCache::new(
1945 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1946 TokenTheme::from_tm_theme(THEME).unwrap(),
1947 n,
1948 )
1949 }
1950
1951 fn highlighter_cmt() -> Highlighter {
1952 Highlighter::new(
1953 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1954 TokenTheme::from_tm_theme(THEME).unwrap(),
1955 )
1956 }
1957
1958 fn cache_str(n: u32) -> HighlightCache {
1959 HighlightCache::new(
1960 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
1961 TokenTheme::from_tm_theme(THEME).unwrap(),
1962 n,
1963 )
1964 }
1965
1966 fn highlighter_str() -> Highlighter {
1967 Highlighter::new(
1968 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
1969 TokenTheme::from_tm_theme(THEME).unwrap(),
1970 )
1971 }
1972
1973 /// Drive to full convergence (dirty walk + window refill), budgeted like
1974 /// the real sweep.
1975 fn drive_all(c: &mut HighlightCache, lines: &[String]) -> u32 {
1976 let mut work = 0;
1977 while c.pending().is_some() {
1978 work += c
1979 .tokenize_until(u32::MAX, HIGHLIGHT_MAX_LINES_PER_CALL, |r| lines[r as usize].as_str());
1980 }
1981 work
1982 }
1983
1984 /// The virtualization guarantee: sweeping a 10k-line document with the
1985 /// window aimed at the top retains a bounded number of rows, not the whole
1986 /// document — spans and states outside the window are evicted, so RAM does
1987 /// not grow with the sweep.
1988 #[test]
1989 fn virtualized_sweep_retains_bounded_rows() {
1990 let lines: Vec<String> = (0..10_000).map(|i| format!("kw line {i}")).collect();
1991 let mut c = cache(10_000);
1992 c.set_window(0..64);
1993 drive_all(&mut c, &lines);
1994 let window_bound = (64 + 2 * HIGHLIGHT_WINDOW_SLACK) as usize;
1995 assert!(
1996 c.retained_span_rows() <= window_bound,
1997 "span retention must be windowed: {} rows kept (bound {window_bound})",
1998 c.retained_span_rows()
1999 );
2000 let state_bound = window_bound + 3 * (10_000 / HIGHLIGHT_CHECKPOINT_STRIDE as usize);
2001 assert!(
2002 c.retained_state_rows() <= state_bound,
2003 "state retention must be window + sparse checkpoints: {} kept (bound {state_bound})",
2004 c.retained_state_rows()
2005 );
2006 // Retention is bounded but the window is still CORRECT…
2007 let full = highlighter().highlight(&lines.join("\n"));
2008 assert_eq!(c.line_spans(10), Some(full[10].as_slice()));
2009 // …and out-of-window rows honestly report nothing (fallback render).
2010 assert_eq!(c.line_spans(5_000), None);
2011 }
2012
2013 /// A window move over already-swept rows refills from the nearest
2014 /// checkpoint: correct spans (stateful grammar — a wrong warm-up state
2015 /// would color the string region wrong), bounded work.
2016 #[test]
2017 fn window_move_refills_from_checkpoints() {
2018 let mut lines: Vec<String> = (0..3_000).map(|i| format!("x {i} kw")).collect();
2019 lines[1_000] = "\"open".into(); // unterminated: rows 1001.. are in-string
2020 lines[2_000] = "close\"".into(); // …until the string pops here
2021 let full = highlighter_str().highlight(&lines.join("\n"));
2022 let mut c = cache_str(3_000);
2023 c.set_window(0..40);
2024 drive_all(&mut c, &lines);
2025 assert!(c.line_spans(1_600).is_none(), "deep rows evicted after the sweep");
2026
2027 // Cold jump into the middle of the multi-line string.
2028 c.set_window(1_500..1_540);
2029 let fill_work = drive_all(&mut c, &lines);
2030 for r in 1_500..1_540 {
2031 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2032 }
2033 assert_eq!(c.line_spans(10), None, "the old window was evicted");
2034 // ≤ one stride of warm-up + the retained window (+ a little dust).
2035 let bound = HIGHLIGHT_CHECKPOINT_STRIDE + 40 + 2 * HIGHLIGHT_WINDOW_SLACK + 8;
2036 assert!(fill_work <= bound, "cold-jump refill did {fill_work} lines (bound {bound})");
2037 }
2038
2039 /// A state-neutral edit OUTSIDE the window re-converges at checkpoint
2040 /// grain: bounded by strides (+ warm-up), never by the document — and
2041 /// the far-away window's rows stay correct.
2042 #[test]
2043 fn out_of_window_edit_reconverges_within_a_stride() {
2044 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2045 let mut c = cache_str(2_000);
2046 c.set_window(1_500..1_540);
2047 drive_all(&mut c, &lines);
2048 lines[100] = "kw edited".into(); // state-neutral, far above the window
2049 c.on_commit(100, 1, 1);
2050 let work = drive_all(&mut c, &lines);
2051 let bound = 2 * HIGHLIGHT_CHECKPOINT_STRIDE + 2;
2052 assert!(work <= bound, "out-of-window keystroke re-tokenized {work} lines (bound {bound})");
2053 let full = highlighter_str().highlight(&lines.join("\n"));
2054 assert_eq!(c.line_spans(1_520), Some(full[1_520].as_slice()));
2055 }
2056
2057 /// An in-window state-neutral keystroke stays O(1) under the STATEFUL
2058 /// grammar too — per-line convergence probes live in the window.
2059 #[test]
2060 fn in_window_keystroke_stays_o1_with_stateful_grammar() {
2061 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2062 lines[300] = "\"open".into();
2063 lines[600] = "shut\"".into();
2064 let mut c = cache_str(2_000);
2065 c.set_window(900..940);
2066 drive_all(&mut c, &lines);
2067 lines[920] = "kw retyped".into();
2068 c.on_commit(920, 1, 1);
2069 let work = drive_all(&mut c, &lines);
2070 assert!(work <= 2, "in-window keystroke re-tokenized {work} lines (expected O(1))");
2071 }
2072
2073 /// The randomized battering ram: seeded edits, window moves, and
2074 /// budget-starved drives in any order — after convergence, every retained
2075 /// row equals the whole-document oracle, wherever the window lands.
2076 #[test]
2077 fn randomized_edits_and_window_moves_match_the_oracle() {
2078 let mut lines: Vec<String> = (0..1_200)
2079 .map(|i| match i % 97 {
2080 13 => "\"".to_string(),
2081 51 => "shut\" kw".to_string(),
2082 _ => format!("kw word {i}"),
2083 })
2084 .collect();
2085 let mut c = cache_str(1_200);
2086 let mut state = 0xDEADBEEF_u64;
2087 let mut rand = move |bound: usize| {
2088 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2089 ((state >> 33) as usize) % bound.max(1)
2090 };
2091 for _step in 0..120 {
2092 match rand(3) {
2093 0 => {
2094 let s = rand(lines.len());
2095 let old = (1 + rand(3)).min(lines.len() - s);
2096 let n = 1 + rand(3);
2097 let repl: Vec<String> = (0..n)
2098 .map(|k| match rand(5) {
2099 0 => "\"".to_string(),
2100 1 => "q\" kw".to_string(),
2101 _ => format!("e{k} kw"),
2102 })
2103 .collect();
2104 lines.splice(s..s + old, repl);
2105 c.on_commit(s as u32, old as u32, n as u32);
2106 }
2107 1 => {
2108 let s = rand(lines.len());
2109 c.set_window(s as u32..(s + 40).min(lines.len()) as u32);
2110 }
2111 _ => {
2112 let target = rand(lines.len()) as u32;
2113 let budget = 32 + rand(200) as u32;
2114 c.tokenize_until(target, budget, |r| lines[r as usize].as_str());
2115 }
2116 }
2117 assert_eq!(c.line_count() as usize, lines.len(), "line count in step");
2118 }
2119 // Converge, then check every retained row — and re-aim the window at
2120 // several places so refill paths get checked against the oracle too.
2121 let full = highlighter_str().highlight(&lines.join("\n"));
2122 drive_all(&mut c, &lines);
2123 let mut checked = 0usize;
2124 for r in 0..lines.len() as u32 {
2125 if let Some(spans) = c.line_spans(r) {
2126 assert_eq!(spans, full[r as usize].as_slice(), "row {r}");
2127 checked += 1;
2128 }
2129 }
2130 assert!(checked >= 40, "the window retained rows to check ({checked})");
2131 for &probe in &[0usize, 400, 800, lines.len().saturating_sub(45)] {
2132 c.set_window(probe as u32..(probe + 40).min(lines.len()) as u32);
2133 drive_all(&mut c, &lines);
2134 for (r, expected) in
2135 full.iter().enumerate().take((probe + 40).min(lines.len())).skip(probe)
2136 {
2137 assert_eq!(c.line_spans(r as u32), Some(expected.as_slice()), "probe {probe} row {r}");
2138 }
2139 }
2140 }
2141
2142 #[test]
2143 fn scattered_multi_caret_marks_only_edited_lines_dirty() {
2144 // A scattered multi-caret keystroke folds into ONE covering line range
2145 // (first caret .. last caret). The dirty set must hold only the EDITED
2146 // lines (per-edit spans), not the whole covering span — else the sweep
2147 // re-tokenizes O(document) between the carets.
2148 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2149 let mut c = cache_str(2_000);
2150 c.set_window(0..40);
2151 drive_all(&mut c, &lines);
2152 assert_eq!(c.dirty_row_count(), 0, "swept clean");
2153 // Two carets, rows 10 and 1_500, one char each (state-neutral, 1→1).
2154 lines[10] = "kw a".into();
2155 lines[1_500] = "kw b".into();
2156 c.on_commit_patch(&[(10, 1, 1), (1_500, 1, 1)]);
2157 assert_eq!(
2158 c.dirty_row_count(),
2159 2,
2160 "a scattered 2-caret edit must mark 2 lines dirty, not the ~1491-row covering span"
2161 );
2162 // …and the highlight is still correct after the sweep.
2163 drive_all(&mut c, &lines);
2164 let full = highlighter_str().highlight(&lines.join("\n"));
2165 for r in 0..40 {
2166 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2167 }
2168 }
2169
2170 #[test]
2171 fn scattered_edit_keeps_the_window_aimed_at_the_viewport() {
2172 // Select-all-occurrences of a word + delete is a scattered multi-edit
2173 // whose covering range engulfs the viewport window. The window must
2174 // stay aimed at the viewport (only the edited rows invalidated), so the
2175 // VISIBLE rows recolor on the next tokenize — not only after a scroll
2176 // fires set_window and re-aims it. A splice that rode the covering range
2177 // would drain or reposition the window, dropping the visible rows to
2178 // fallback until a scrollwheel tick.
2179 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2180 let mut c = cache_str(2_000);
2181 c.set_window(940..980);
2182 drive_all(&mut c, &lines);
2183 assert!(c.line_spans(960).is_some(), "the viewport window is filled");
2184 // Delete a word at scattered occurrences: rows 10, 960 (in view), 1_500,
2185 // one transaction, all state-neutral (1→1). Covering range 10..1_500
2186 // engulfs the window at 940..980.
2187 for r in [10usize, 960, 1_500] {
2188 lines[r] = "kw w".into();
2189 }
2190 c.on_commit_patch(&[(10, 1, 1), (960, 1, 1), (1_500, 1, 1)]);
2191 // Tokenize WITHOUT re-aiming the window (no set_window / no scroll).
2192 drive_all(&mut c, &lines);
2193 let full = highlighter_str().highlight(&lines.join("\n"));
2194 for r in 940..980u32 {
2195 assert_eq!(
2196 c.line_spans(r),
2197 Some(full[r as usize].as_slice()),
2198 "viewport row {r} did not recolor without a scroll to re-aim the window",
2199 );
2200 }
2201 }
2202
2203 /// The multi-edit analogue of the randomized oracle: each step commits a
2204 /// TRANSACTION of several disjoint edits at once via `on_commit_patch` (the
2205 /// scattered multi-caret path), and after convergence every retained row
2206 /// must still equal the whole-document oracle. Guards the per-edit
2207 /// checkpoint/dirty merge walks against any shift or coalescing bug.
2208 #[test]
2209 fn randomized_multi_edit_commits_match_the_oracle() {
2210 let mut lines: Vec<String> = (0..1_200)
2211 .map(|i| match i % 97 {
2212 13 => "\"".to_string(),
2213 51 => "shut\" kw".to_string(),
2214 _ => format!("kw word {i}"),
2215 })
2216 .collect();
2217 let mut c = cache_str(1_200);
2218 let mut state = 0x1234_5678_9ABC_DEF0_u64;
2219 let mut rand = move |bound: usize| {
2220 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2221 ((state >> 33) as usize) % bound.max(1)
2222 };
2223 for _step in 0..80 {
2224 if rand(3) == 2 {
2225 // Sometimes just tokenize a budget, leaving dirt around.
2226 let target = rand(lines.len()) as u32;
2227 c.tokenize_until(target, 32 + rand(200) as u32, |r| lines[r as usize].as_str());
2228 assert_eq!(c.line_count() as usize, lines.len());
2229 continue;
2230 }
2231 // Build up to 4 disjoint edits, ascending with a gap between each.
2232 let k = 1 + rand(4);
2233 let mut sites: Vec<(usize, usize, Vec<String>)> = Vec::new();
2234 let mut cursor = rand(20);
2235 for _ in 0..k {
2236 let s = cursor + rand(30);
2237 if s >= lines.len() {
2238 break;
2239 }
2240 let old = (1 + rand(3)).min(lines.len() - s);
2241 let n = 1 + rand(3);
2242 let repl: Vec<String> = (0..n)
2243 .map(|j| match rand(5) {
2244 0 => "\"".to_string(),
2245 1 => "q\" kw".to_string(),
2246 _ => format!("m{j} kw"),
2247 })
2248 .collect();
2249 sites.push((s, old, repl));
2250 cursor = s + old + 1; // a gap ⇒ the next start is strictly after
2251 }
2252 if sites.is_empty() {
2253 continue;
2254 }
2255 // Per-edit spans (pre-edit, disjoint) + the covering splice.
2256 let spans: Vec<(u32, u32, u32)> =
2257 sites.iter().map(|(s, o, r)| (*s as u32, *o as u32, r.len() as u32)).collect();
2258 c.on_commit_patch(&spans);
2259 // Apply to `lines` back-to-front so earlier indices stay valid.
2260 for (s, o, repl) in sites.iter().rev() {
2261 lines.splice(*s..*s + *o, repl.clone());
2262 }
2263 assert_eq!(c.line_count() as usize, lines.len(), "line count after multi-edit");
2264 }
2265 let full = highlighter_str().highlight(&lines.join("\n"));
2266 drive_all(&mut c, &lines);
2267 let mut checked = 0usize;
2268 for r in 0..lines.len() as u32 {
2269 if let Some(spans) = c.line_spans(r) {
2270 assert_eq!(spans, full[r as usize].as_slice(), "row {r}");
2271 checked += 1;
2272 }
2273 }
2274 assert!(checked >= 40, "retained rows to check ({checked})");
2275 for &probe in &[0usize, 300, 700, lines.len().saturating_sub(45)] {
2276 c.set_window(probe as u32..(probe + 40).min(lines.len()) as u32);
2277 drive_all(&mut c, &lines);
2278 for (r, expected) in
2279 full.iter().enumerate().take((probe + 40).min(lines.len())).skip(probe)
2280 {
2281 assert_eq!(c.line_spans(r as u32), Some(expected.as_slice()), "probe {probe} row {r}");
2282 }
2283 }
2284 }
2285
2286 /// Checkpoints drift off the stride grid (any line-delta edit shifts them),
2287 /// and a state-changing cascade crossing an off-stride checkpoint must
2288 /// REFRESH it — a stale one left below the frontier poisons a later
2289 /// cold-jump warm-up into permanently wrong highlighting. Fails against a
2290 /// `retain` that only writes stride-aligned checkpoints.
2291 #[test]
2292 fn shifted_checkpoints_are_refreshed_by_a_crossing_cascade() {
2293 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2294 let mut c = cache_str(2_000);
2295 c.set_window(0..40);
2296 drive_all(&mut c, &lines);
2297 // A single Enter above everything: every checkpoint shifts off-stride.
2298 lines.insert(10, "kw split".to_string());
2299 c.on_commit(10, 1, 2);
2300 drive_all(&mut c, &lines);
2301 // A state-changing edit near the top: the cascade repaints the tail,
2302 // crossing every shifted checkpoint.
2303 lines[12] = "\"open".to_string(); // unterminated → everything below is in-string
2304 c.on_commit(12, 1, 1);
2305 drive_all(&mut c, &lines);
2306 // Cold-jump far below: the refill warms up from whatever checkpoint
2307 // is nearest — which must hold the POST-cascade (in-string) state.
2308 c.set_window(1_285..1_325);
2309 drive_all(&mut c, &lines);
2310 let full = highlighter_str().highlight(&lines.join("\n"));
2311 for r in 1_285..1_325u32 {
2312 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2313 }
2314 }
2315
2316 /// Off-stride and orphaned resume checkpoints must be pruned as fresh
2317 /// stride checkpoints land, or they accumulate without bound across
2318 /// edit/cascade cycles — slowly re-growing the RAM virtualization keeps
2319 /// bounded.
2320 #[test]
2321 fn checkpoints_do_not_accumulate_across_edit_cycles() {
2322 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw {i}")).collect();
2323 let mut c = cache_str(4_000);
2324 c.set_window(0..40);
2325 drive_all(&mut c, &lines);
2326 for cycle in 0..16 {
2327 // Shift the grid…
2328 lines.insert(5, format!("kw cycle {cycle}"));
2329 c.on_commit(5, 1, 2);
2330 // …and flip the whole tail's state, twice (open then close).
2331 lines[7] = "\"open".to_string();
2332 c.on_commit(7, 1, 1);
2333 drive_all(&mut c, &lines);
2334 lines[7] = "kw closed".to_string();
2335 c.on_commit(7, 1, 1);
2336 drive_all(&mut c, &lines);
2337 }
2338 let bound = 2 * (c.line_count() / HIGHLIGHT_CHECKPOINT_STRIDE) as usize + 8;
2339 assert!(
2340 c.ret.checkpoints.len() <= bound,
2341 "checkpoints accumulate: {} after 16 cycles (bound {bound})",
2342 c.ret.checkpoints.len()
2343 );
2344 }
2345
2346 // ── The checkpoint delta-gap `SumTree` ──────────────────────────────────
2347
2348 /// A fresh (document-top) `LineState` for seeding checkpoint trees without a
2349 /// real sweep — the `main`-context start state.
2350 fn fresh_state() -> LineState {
2351 engine_str().fresh_state()
2352 }
2353
2354 /// A distinct `LineState`: the parser left INSIDE a string context (after an
2355 /// unclosed `"`), so it compares unequal to [`fresh_state`] — lets the oracle
2356 /// pin the `(row, state)` sequence, not just the rows.
2357 fn str_state() -> LineState {
2358 let eng = engine_str();
2359 let syntect = SyntectHighlighter::new(&eng.theme.0);
2360 let (_spans, end) = tokenize_line(&syntect, &eng.syntax.set, &eng.fresh_state(), "\"");
2361 end
2362 }
2363
2364 /// A straightforward flat-Vec checkpoint shift — the ORACLE reference the
2365 /// delta-gap tree's `shift` must match, edit for edit. Drift in a
2366 /// checkpoint row poisons later warm-ups (a wrong start state → permanently
2367 /// wrong colors), so this equivalence is load-bearing.
2368 fn vec_shift_reference(cps: &mut Vec<(u32, Box<LineState>)>, spans: &[(u32, u32, u32)]) {
2369 if spans.is_empty() {
2370 return;
2371 }
2372 let old = std::mem::take(cps);
2373 let mut si = 0;
2374 let mut acc = 0i64;
2375 for (row, state) in old {
2376 while si < spans.len() && spans[si].0 + spans[si].1 <= row {
2377 acc += i64::from(spans[si].2) - i64::from(spans[si].1);
2378 si += 1;
2379 }
2380 if si < spans.len() && row >= spans[si].0 {
2381 continue; // inside a replaced span → stale
2382 }
2383 cps.push(((row as i64 + acc) as u32, state));
2384 }
2385 }
2386
2387 /// ORACLE: the checkpoint tree's `shift` equals the flat-Vec reference under
2388 /// random single- AND multi-edit patches, after EVERY commit. Single-edit
2389 /// patches drive `shift_single` (the windowed seam surgery — the real risk);
2390 /// multi-edit patches drive `shift_walk`. States alternate between two
2391 /// distinct values so a mismapped payload (not just a wrong row) is caught.
2392 #[test]
2393 fn checkpoint_tree_equals_the_vec_reference_under_random_edits() {
2394 let (st_a, st_b) = (fresh_state(), str_state());
2395 assert!(st_a != st_b, "seed states must differ for the state check to bite");
2396 let mut rng = 0x1234_5678u32;
2397 let mut next = || {
2398 rng ^= rng << 13;
2399 rng ^= rng >> 17;
2400 rng ^= rng << 5;
2401 rng
2402 };
2403 for trial in 0..200 {
2404 // A fresh random ascending, distinct checkpoint set per trial.
2405 let mut n_lines = 400u32 + next() % 4_000;
2406 let k = 4 + next() % 60;
2407 let mut rows: Vec<u32> = Vec::new();
2408 let mut r = next() % 40;
2409 for _ in 0..k {
2410 if r >= n_lines {
2411 break;
2412 }
2413 rows.push(r);
2414 r += 1 + next() % 90;
2415 }
2416 let seed = |i: usize| if i.is_multiple_of(2) { st_a.clone() } else { st_b.clone() };
2417 let init: Vec<(u32, Box<LineState>)> =
2418 rows.iter().enumerate().map(|(i, &r)| (r, Box::new(seed(i)))).collect();
2419 let mut tree = {
2420 let items = init.iter().scan(0u32, |prev, (r, s)| {
2421 let gap = r - *prev;
2422 *prev = *r;
2423 Some(CkptItem { row_gap: gap, state: s.clone() })
2424 });
2425 Checkpoints { tree: SumTree::from_items(items) }
2426 };
2427 let mut reference = init;
2428
2429 for step in 0..12 {
2430 // A valid ascending, disjoint patch of 1..=3 edits (mixes the paths).
2431 let n_edits = 1 + (next() % 3) as usize;
2432 let mut spans: Vec<(u32, u32, u32)> = Vec::new();
2433 let mut cursor = 0u32;
2434 for _ in 0..n_edits {
2435 if cursor >= n_lines {
2436 break;
2437 }
2438 let span = (n_lines - cursor).clamp(1, 120);
2439 let s = cursor + next() % span;
2440 if s >= n_lines {
2441 break;
2442 }
2443 let o = (next() % 5).min(n_lines - s);
2444 let nw = next() % 5;
2445 spans.push((s, o, nw));
2446 cursor = s + o + 1; // keep replaced spans disjoint + ascending
2447 }
2448 if spans.is_empty() {
2449 continue;
2450 }
2451 let delta: i64 = spans.iter().map(|&(_, o, n)| i64::from(n) - i64::from(o)).sum();
2452
2453 tree.shift(&spans);
2454 vec_shift_reference(&mut reference, &spans);
2455 n_lines = (n_lines as i64 + delta) as u32;
2456
2457 let got = tree.rows();
2458 let want: Vec<u32> = reference.iter().map(|(r, _)| *r).collect();
2459 assert_eq!(got, want, "trial {trial} step {step}: rows diverge for {spans:?}");
2460 let states_ok = tree
2461 .tree
2462 .items()
2463 .iter()
2464 .zip(&reference)
2465 .all(|(it, (_, s))| *it.state == **s);
2466 assert!(states_ok, "trial {trial} step {step}: a checkpoint state was mismapped");
2467 }
2468 }
2469 }
2470
2471 /// PERF CELL: one 1-line keystroke's checkpoint shift is independent of the
2472 /// checkpoint count. A flat-Vec walk would charge K (take + rebuild every
2473 /// commit and undo step); the windowed seam touches O(1). FLIP-VERIFY:
2474 /// force `shift` down the `shift_walk` fallback (change its dispatch to
2475 /// `if false`) and this trips — the meter reads ≈K → 2K instead of a flat 1.
2476 #[test]
2477 fn checkpoint_shift_is_checkpoint_count_independent() {
2478 let st = fresh_state();
2479 let meter = |k: u32| -> u64 {
2480 // K stride checkpoints; the edit (row 5, 1→1) sits far below the first
2481 // (row 255), so the windowed shift drops nothing and shifts nothing.
2482 let rows: Vec<u32> =
2483 (0..k).map(|i| (i + 1) * HIGHLIGHT_CHECKPOINT_STRIDE - 1).collect();
2484 let mut cps = Checkpoints::from_rows(&rows, &st);
2485 crate::perf::reset();
2486 cps.shift(&[(5, 1, 1)]);
2487 crate::perf::meter()
2488 };
2489 let (small, big) = (meter(1000), meter(2000));
2490 eprintln!("[perf_gate] checkpoint shift charge {small:>7} -> {big:>7}");
2491 assert!(
2492 big <= small + small / 4 + 256,
2493 "checkpoint shift charged {small} -> {big}: it walked every checkpoint, not the seam",
2494 );
2495 }
2496
2497 /// A collapsed mega-fold makes the widget report a visible range spanning
2498 /// the fold's hidden interior — the retention window must CAP its length,
2499 /// or a fold re-grows retention to O(document).
2500 #[test]
2501 fn window_length_is_capped() {
2502 let lines: Vec<String> = (0..200_000).map(|i| format!("kw {i}")).collect();
2503 let mut c = cache(200_000);
2504 c.set_window(0..150_000); // a viewport straddling a huge collapsed fold
2505 drive_all(&mut c, &lines);
2506 assert!(
2507 c.retained_span_rows() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize,
2508 "the window must be capped: {} rows retained",
2509 c.retained_span_rows()
2510 );
2511 }
2512
2513 #[test]
2514 fn in_window_commit_with_a_document_scale_span_stays_bounded() {
2515 // A scattered multi-caret transaction folds into ONE covering line span
2516 // (first caret .. last caret), so on_commit's in-window branch sees a
2517 // document-scale `new` even though the window is small. The dense splice
2518 // must stay bounded — splicing `vec![None; new]` would regrow `win` to
2519 // O(new), an O(document) per-keystroke allocation.
2520 let mut c = cache(200_000);
2521 c.set_window(100..140); // small window near the top; the first caret is in it
2522 assert!(c.window_len() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize);
2523 // The covering splice of an edit spanning rows 100..150_000 (top+bottom
2524 // carets, one char each → +150k covering lines, say).
2525 c.on_commit(100, 1, 150_000);
2526 assert!(
2527 c.window_len() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize,
2528 "in-window covering splice regrew the window to {} rows",
2529 c.window_len()
2530 );
2531 // The dirty set and line count still track the (over-wide) splice, so
2532 // the covered rows are refilled correctly on the sweep.
2533 assert_eq!(c.line_count(), 200_000 + 150_000 - 1);
2534 }
2535
2536 // ------------------------------------------------------------------
2537 // Off-thread bulk tokenization: parallel sweep + viewport speculation.
2538 // All under the STATEFUL GRAMMAR_STR so a wrong guess (a cut inside a
2539 // multi-line string) produces genuinely different colors that the stitch
2540 // must repair - the whole point.
2541 // ------------------------------------------------------------------
2542
2543 fn engine_str() -> HighlightEngine {
2544 HighlightEngine::new(
2545 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
2546 TokenTheme::from_tm_theme(THEME).unwrap(),
2547 )
2548 }
2549
2550 fn snap(lines: &[String]) -> Snapshot {
2551 crate::buffer::Buffer::new(&lines.join("\n")).unwrap().snapshot()
2552 }
2553
2554 fn drive_all_snap(c: &mut HighlightCache, s: &Snapshot) {
2555 while c.pending().is_some() {
2556 c.tokenize_until(u32::MAX, HIGHLIGHT_MAX_LINES_PER_CALL, |r| s.line(r));
2557 }
2558 }
2559
2560 /// Simulate the app's coordinator: tokenize every segment Fresh (as the
2561 /// worker pool would, order-independently), then stitch left to right -
2562 /// re-running (with the early-stop `converge_against`) any segment whose
2563 /// Fresh guess mismatched the true prior end. Returns the verified chain
2564 /// and how many segments needed a re-run.
2565 fn parallel_verify(
2566 engine: &HighlightEngine,
2567 snapshot: &Snapshot,
2568 cuts: &[u32],
2569 spans_for: Option<Range<u32>>,
2570 ) -> (Vec<SegmentTokens>, usize) {
2571 let n = snapshot.line_count();
2572 let mut bounds = vec![0u32];
2573 bounds.extend(cuts.iter().copied().filter(|&c| c > 0 && c < n));
2574 bounds.sort_unstable();
2575 bounds.dedup();
2576 bounds.push(n);
2577 // Pass 1 - all Fresh (the parallel workers; order irrelevant).
2578 let segs: Vec<SegmentTokens> = bounds
2579 .windows(2)
2580 .map(|w| {
2581 tokenize_segment(engine, snapshot, w[0]..w[1], SegmentStart::Fresh, spans_for.clone(), None)
2582 })
2583 .collect();
2584 // Pass 2 - sequential stitch.
2585 let fresh = engine.fresh_boundary();
2586 let mut verified: Vec<SegmentTokens> = Vec::with_capacity(segs.len());
2587 let mut prev_end: Option<SegmentBoundary> = None;
2588 let mut reruns = 0;
2589 for (idx, seg) in segs.into_iter().enumerate() {
2590 let corrected = if idx == 0 {
2591 seg // Fresh at row 0 is the true start
2592 } else {
2593 let true_start = prev_end.clone().unwrap();
2594 if true_start == fresh {
2595 seg // the Fresh guess happened to be right
2596 } else {
2597 reruns += 1;
2598 let rows = seg.rows();
2599 tokenize_segment(
2600 engine,
2601 snapshot,
2602 rows,
2603 SegmentStart::After(true_start),
2604 spans_for.clone(),
2605 Some(&seg),
2606 )
2607 }
2608 };
2609 prev_end = Some(corrected.end_boundary().clone());
2610 verified.push(corrected);
2611 }
2612 (verified, reruns)
2613 }
2614
2615 /// THE correctness spine (property test): under random stateful documents
2616 /// and random segment cuts - including cuts deliberately inside multi-line
2617 /// strings - the parallel-verified + absorbed cache must equal a
2618 /// whole-document `Highlighter::highlight` on every row, and its checkpoint
2619 /// rows must match a sync-swept cache. Fails against any stitch that does
2620 /// not repair a wrong-guessed boundary.
2621 #[test]
2622 fn parallel_stitch_equals_the_whole_document_oracle() {
2623 let engine = engine_str();
2624 let mut state = 0x1234_5678_9ABC_DEF0_u64;
2625 let mut rng = move |bound: usize| {
2626 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2627 ((state >> 33) as usize) % bound.max(1)
2628 };
2629 for round in 0..24 {
2630 let n = 200 + rng(1_200);
2631 let lines: Vec<String> = (0..n)
2632 .map(|i| match rng(11) {
2633 0 => "\"".to_string(), // open a multi-line string
2634 1 => "text\" kw".to_string(), // close it, then a keyword
2635 2 => "\" and \" kw".to_string(),
2636 _ => format!("kw word {i}"),
2637 })
2638 .collect();
2639 let s = snap(&lines);
2640 let ln = s.line_count();
2641 // 1-6 random cuts, some likely inside string regions.
2642 let cuts: Vec<u32> = (0..1 + rng(6)).map(|_| rng(ln as usize) as u32).collect();
2643 let win_start = rng(ln as usize) as u32;
2644 let win = win_start..(win_start + 40).min(ln);
2645
2646 let (verified, _reruns) = parallel_verify(&engine, &s, &cuts, None);
2647 let mut c = cache_str(ln);
2648 c.set_window(win.clone());
2649 for seg in verified {
2650 c.absorb(seg, true);
2651 }
2652 assert_eq!(c.first_dirty(), None, "round {round}: verified sweep must clear all dirt");
2653 // Spans-less segments left window gaps - the sync refill (from the
2654 // absorbed checkpoints) fills them; then every window row is exact.
2655 drive_all_snap(&mut c, &s);
2656 let full = highlighter_str().highlight(&lines.join("\n"));
2657 for r in win.clone() {
2658 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "round {round} row {r}");
2659 }
2660 // Checkpoint ROWS must match a purely sync sweep (the absorb path
2661 // may not fabricate off-grid checkpoints the sync path lacks).
2662 let mut sync = cache_str(ln);
2663 sync.set_window(win.clone());
2664 drive_all(&mut sync, &lines);
2665 let got: Vec<u32> = c.ret.checkpoints.rows();
2666 let want: Vec<u32> = sync.ret.checkpoints.rows();
2667 assert_eq!(got, want, "round {round}: checkpoint rows diverge from a sync sweep");
2668 }
2669 }
2670
2671 /// A wrong-guessed boundary (a cut deep inside a block comment) repairs in
2672 /// O(distance to the comment's close), NOT O(segment): the re-run's
2673 /// early-stop splices the proven-identical tail, tokenizing only up to one
2674 /// stride past the closing line. (Uses the self-healing GRAMMAR_CMT — a
2675 /// symmetric-toggle string never re-converges, so it can't exercise the
2676 /// splice; that is the degenerate case tested separately.)
2677 #[test]
2678 fn wrong_guess_repair_stops_within_a_stride() {
2679 let engine = engine_cmt();
2680 // A comment opens at row 100 and closes at row 300; the rest is plain.
2681 // A cut at 1500 is far PAST the comment, so both the fresh guess and
2682 // the truth are in the ground state there — to force a genuine
2683 // mis-guess, cut at 200 (inside the comment).
2684 let mut lines: Vec<String> = (0..8_000).map(|i| format!("kw word {i}")).collect();
2685 lines[100] = "/*".to_string();
2686 lines[300] = "*/ kw".to_string();
2687 let s = snap(&lines);
2688 // The tail segment 200..8000, guessed Fresh (ground) — wrong, row 200
2689 // is inside the comment.
2690 let seg_rows = 200u32..8_000;
2691 let guessed = tokenize_segment(&engine, &s, seg_rows.clone(), SegmentStart::Fresh, None, None);
2692 let truth_prefix = tokenize_segment(&engine, &s, 0..200, SegmentStart::Fresh, None, None);
2693 let true_start = SegmentStart::After(truth_prefix.end_boundary().clone());
2694 let repaired = tokenize_segment(&engine, &s, seg_rows, true_start, None, Some(&guessed));
2695 // Converged: the tail was spliced, so far fewer than 7800 rows ran.
2696 // The comment closes at 300; convergence is detected at the first
2697 // stride checkpoint past it, so tokenized ≤ (300 − 200) + one stride.
2698 let bound = (300 - 200) + HIGHLIGHT_CHECKPOINT_STRIDE;
2699 assert!(
2700 repaired.tokenized_rows() <= bound,
2701 "repair tokenized {} rows (bound {bound}) — early-stop did not fire",
2702 repaired.tokenized_rows()
2703 );
2704 assert!(repaired.tokenized_rows() < 7_800, "a full re-run would tokenize the whole segment");
2705 // …and it is byte-identical to a full correct re-run.
2706 let full_rerun =
2707 tokenize_segment(&engine, &s, 200..8_000, SegmentStart::After(truth_prefix.end_boundary().clone()), None, None);
2708 assert!(repaired.end_boundary() == full_rerun.end_boundary(), "spliced tail must be correct");
2709 // End-to-end oracle around the close, where the guess was wrong.
2710 let (verified, reruns) = parallel_verify(&engine, &s, &[200], None);
2711 assert_eq!(reruns, 1, "the in-comment cut must trigger exactly one re-run");
2712 let mut c = cache_cmt(8_000);
2713 c.set_window(190..600);
2714 for v in verified {
2715 c.absorb(v, true);
2716 }
2717 drive_all_snap(&mut c, &s);
2718 let full = highlighter_cmt().highlight(&lines.join("\n"));
2719 for r in 190..600u32 {
2720 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2721 }
2722 }
2723
2724 /// A converging re-run whose `spans_for` DIFFERS from the old segment's
2725 /// window (the coordinator dispatched the re-run after the viewport moved)
2726 /// must stay internally consistent — the window is forced to the old
2727 /// segment's, so the spliced tail lines up. Were the moved `spans_for`
2728 /// honored instead, the splice would write misaligned spans as clean
2729 /// (viewport poison) or trip the window-equality assertion.
2730 #[test]
2731 fn converging_rerun_ignores_a_moved_spans_for() {
2732 let engine = engine_cmt();
2733 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw word {i}")).collect();
2734 lines[100] = "/*".to_string();
2735 lines[300] = "*/ kw".to_string();
2736 let s = snap(&lines);
2737 let seg_rows = 200u32..2_000;
2738 let old_window = Some(210u32..250); // the window when the guess was made
2739 let guessed =
2740 tokenize_segment(&engine, &s, seg_rows.clone(), SegmentStart::Fresh, old_window.clone(), None);
2741 let prefix = tokenize_segment(&engine, &s, 0..200, SegmentStart::Fresh, None, None);
2742 let after = || SegmentStart::After(prefix.end_boundary().clone());
2743 // Re-run with a MOVED window (1500..1540 — the viewport scrolled).
2744 let moved = tokenize_segment(&engine, &s, seg_rows.clone(), after(), Some(1_500..1_540), Some(&guessed));
2745 // …and a control re-run whose spans_for already matches the old window.
2746 let matched = tokenize_segment(&engine, &s, seg_rows, after(), old_window, Some(&guessed));
2747 // The moved re-run behaves as if it reused the old window: same tail,
2748 // same window range, same end — no panic, no misalignment.
2749 assert!(moved.end_boundary() == matched.end_boundary(), "same converged end");
2750 assert_eq!(moved.rows, matched.rows);
2751 assert_eq!(moved.win, matched.win, "window forced to the old segment's");
2752 assert_eq!(moved.win_spans.len(), moved.win.len(), "spans line up with the window");
2753 assert_eq!(moved.win_states.len(), moved.win.len());
2754 // And absorbing it colours the old window's rows correctly.
2755 let full = highlighter_cmt().highlight(&lines.join("\n"));
2756 let mut c = cache_cmt(4_000);
2757 c.set_window(210..250);
2758 c.absorb(prefix, true);
2759 c.absorb(moved, true);
2760 drive_all_snap(&mut c, &s);
2761 for r in 210..250u32 {
2762 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2763 }
2764 }
2765
2766 /// Degenerate honesty: a document that is one never-closed multi-line
2767 /// string makes every boundary mismatch (full sequential re-run) — the
2768 /// result is still byte-identical to the oracle.
2769 #[test]
2770 fn one_giant_string_falls_back_to_sequential_but_stays_correct() {
2771 let engine = engine_str();
2772 let mut lines: Vec<String> = (0..2_000).map(|i| format!("body {i}")).collect();
2773 lines[0] = "\"".to_string(); // opened, never closed
2774 let s = snap(&lines);
2775 let (verified, reruns) = parallel_verify(&engine, &s, &[400, 800, 1_200, 1_600], None);
2776 assert_eq!(reruns, 4, "every mid-string boundary mismatches");
2777 let mut c = cache_str(2_000);
2778 c.set_window(900..980);
2779 for v in verified {
2780 c.absorb(v, true);
2781 }
2782 drive_all_snap(&mut c, &s);
2783 let full = highlighter_str().highlight(&lines.join("\n"));
2784 for r in 900..980u32 {
2785 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2786 }
2787 }
2788
2789 /// Verified absorb clears the segment's rows from the frontier and the
2790 /// spans it carries (spans_for) render immediately - no sync walk needed.
2791 #[test]
2792 fn verified_absorb_clears_dirt_and_shows_spans() {
2793 let engine = engine_str();
2794 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2795 let s = snap(&lines);
2796 let win = 900u32..940;
2797 // One verified segment covering the viewport, carrying its spans.
2798 let seg = tokenize_segment(&engine, &s, 0..2_000, SegmentStart::Fresh, Some(win.clone()), None);
2799 let mut c = cache_str(2_000);
2800 c.set_window(win.clone());
2801 c.absorb(seg, true);
2802 assert_eq!(c.first_dirty(), None, "verified absorb clears the whole frontier");
2803 // The requested spans render immediately — no sync walk. (The window
2804 // pads ±SLACK beyond `spans_for`, so pending() may still report a
2805 // slack gap; that is the sync refill's cheap job, tested elsewhere.)
2806 let full = highlighter_str().highlight(&lines.join("\n"));
2807 for r in win {
2808 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2809 }
2810 }
2811
2812 /// Speculative absorb (a GUESSED fresh start) shows spans in the window
2813 /// immediately, but plants NO checkpoints (unverified states would poison
2814 /// warm-ups) and leaves the rows dirty (the frontier re-verifies them).
2815 #[test]
2816 fn speculative_absorb_shows_spans_without_checkpoints_or_clearing_dirt() {
2817 let engine = engine_str();
2818 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2819 let s = snap(&lines);
2820 let win = 900u32..940;
2821 // A viewport-first speculative segment: back off 128 rows, Fresh guess.
2822 let seg = tokenize_segment(&engine, &s, 772..940, SegmentStart::Fresh, Some(win.clone()), None);
2823 let mut c = cache_str(2_000);
2824 c.set_window(win.clone());
2825 c.absorb(seg, false);
2826 // Spans are visible now (the guess is right here - no multi-line state).
2827 let full = highlighter_str().highlight(&lines.join("\n"));
2828 for r in win.clone() {
2829 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "speculative row {r}");
2830 }
2831 // But nothing is verified: the frontier is untouched and no checkpoint
2832 // was planted (retained_state_rows counts window states + checkpoints;
2833 // the window states are the harmless per-line probes).
2834 assert_eq!(c.first_dirty(), Some(0), "speculation must not clear dirt");
2835 assert!(c.ret.checkpoints.is_empty(), "speculation must not plant checkpoints");
2836 }
2837
2838 /// End to end: speculative colors first, then the frontier's dirty walk
2839 /// reaches the window and CONVERGES in O(1) against the correct
2840 /// speculative state (the guess was right) - the whole window consumed by
2841 /// tokenizing a single row.
2842 #[test]
2843 fn speculative_then_frontier_converges_o1_when_the_guess_was_right() {
2844 let engine = engine_str();
2845 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2846 let s = snap(&lines);
2847 let win = 900u32..940;
2848 let seg = tokenize_segment(&engine, &s, 772..940, SegmentStart::Fresh, Some(win.clone()), None);
2849 let mut c = cache_str(2_000);
2850 c.set_window(win.clone());
2851 c.absorb(seg, false);
2852 // Now drive the frontier from row 0 (as the idle sweep would). When it
2853 // reaches the window, each row's freshly-tokenized state matches the
2854 // stored speculative state, so it converges immediately and the whole
2855 // window's spans are proven correct.
2856 drive_all_snap(&mut c, &s);
2857 assert_eq!(c.first_dirty(), None);
2858 let full = highlighter_str().highlight(&lines.join("\n"));
2859 for r in win {
2860 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2861 }
2862 }
2863
2864 /// The poison guard: a WRONG speculative span (guessed fresh inside a
2865 /// multi-line comment) must never survive as clean when a verified
2866 /// spans-less segment clears its dirt. Verified absorb evicts it; the sync
2867 /// refill (from the correct checkpoints) repaints it right.
2868 #[test]
2869 fn verified_absorb_evicts_wrong_speculative_spans_no_poison() {
2870 let engine = engine_cmt();
2871 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw word {i}")).collect();
2872 lines[100] = "/*".to_string(); // a comment that stays open…
2873 lines[3_000] = "*/ kw".to_string(); // …until here
2874 let s = snap(&lines);
2875 let win = 1_500u32..1_540; // deep inside the comment
2876 let full = highlighter_cmt().highlight(&lines.join("\n"));
2877 let mut c = cache_cmt(4_000);
2878 c.set_window(win.clone());
2879 // Speculate from a FRESH (ground) start — WRONG here, the truth is
2880 // in-comment.
2881 let spec = tokenize_segment(&engine, &s, 1_400..1_540, SegmentStart::Fresh, Some(win.clone()), None);
2882 c.absorb(spec, false);
2883 assert_ne!(
2884 c.line_spans(1_520),
2885 Some(full[1_520].as_slice()),
2886 "the speculative guess must actually be wrong here (else the test proves nothing)"
2887 );
2888 // The correct verified sweep (one segment, Fresh at row 0 = true).
2889 let (verified, _) = parallel_verify(&engine, &s, &[], None);
2890 for v in verified {
2891 c.absorb(v, true);
2892 }
2893 // The wrong speculative span is GONE — evicted, not left clean.
2894 assert_eq!(c.line_spans(1_520), None, "wrong speculative spans must be evicted, never trusted");
2895 // …and the sync refill repaints the window correctly.
2896 drive_all_snap(&mut c, &s);
2897 for r in win {
2898 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r} corrected");
2899 }
2900 }
2901
2902 #[test]
2903 fn dirty_ranges_shift_merge_unit() {
2904 let mut d = DirtyRanges::default();
2905 d.insert(5);
2906 d.insert(7);
2907 d.insert(6); // bridges 5..6 and 7..8 into one run
2908 assert_eq!(d.0, vec![5..8]);
2909 d.insert(4); // extends left
2910 assert_eq!(d.0, vec![4..8]);
2911 // Splice via a single covering span: rows [5,7) became 3 rows → tail
2912 // shifts by +1 (apply_splices reproduces the classic commit splice).
2913 d.apply_splices(&[(5, 2, 3)]);
2914 assert_eq!(d.0, vec![4..9], "clip + shift + new-block merge into one run");
2915 // A pure delete ahead of the run shifts it left.
2916 d.apply_splices(&[(0, 2, 0)]);
2917 assert_eq!(d.0, vec![2..7]);
2918 // Front consumption.
2919 assert_eq!(d.first(), Some(2));
2920 d.remove_first(2);
2921 assert_eq!(d.0, vec![3..7]);
2922 }
2923}