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 for s in &mut self.ret.win_states {
1098 *s = None;
1099 }
1100 self.ret.checkpoints.clear();
1101 self.ret.invalid = DirtyRanges::all(self.ret.n_lines);
1102 }
1103
1104 /// A cheap-to-clone, `Send + Sync` handle to this cache's grammar + theme,
1105 /// for off-thread bulk tokenization (the parallel/speculative sweep).
1106 /// Shares the `Arc`-held grammar/theme — no `SyntaxSet` deep clone.
1107 #[must_use]
1108 pub fn engine(&self) -> HighlightEngine {
1109 HighlightEngine { syntax: self.syntax.clone(), theme: self.theme.clone() }
1110 }
1111
1112 /// Ingest a segment tokenized off-thread (parallel/speculative sweep). The
1113 /// caller ([`crate::Document::absorb_highlight`]) guarantees the segment
1114 /// was computed at the current revision, so `rows`/checkpoints align with
1115 /// this cache.
1116 ///
1117 /// - `verified` — the coordinator chained this segment from row 0, so its
1118 /// start state (and thus its whole result) is TRUE. Merge its stride
1119 /// checkpoints (through the one [`Checkpoints::set_stride`]
1120 /// owner, so the set matches a sync walk), write its window spans+states
1121 /// into the current retention window, and **clear `rows` from the dirty
1122 /// set** — this replaces the foreground dirty walk for that span.
1123 /// - `!verified` — viewport speculation from a GUESSED fresh start. Write
1124 /// window spans+states ONLY into window rows that are still dirty (never
1125 /// clobber verified data), and **never plant a checkpoint**: an
1126 /// unverified state outside the window would poison a later warm-up.
1127 /// Dirt is untouched, so the frontier re-verifies
1128 /// these rows per-line and converges in O(1) if the guess was right; a
1129 /// dirty row's state is only ever read as a convergence probe, never as
1130 /// a warm-up source (that reads `first_dirty − 1`, which is clean).
1131 pub(crate) fn absorb(&mut self, seg: SegmentTokens, verified: bool) {
1132 let r = &mut self.ret;
1133 let SegmentTokens { rows, checkpoints, win, win_spans, win_states, .. } = seg;
1134 if verified {
1135 for (row, state) in checkpoints {
1136 r.checkpoints.set_stride(row, *state);
1137 }
1138 // Evict window rows this segment COVERS but did not SUPPLY spans
1139 // for: they are about to be marked clean, so any speculative span
1140 // there would survive as trusted-but-unverified (poison). `None`
1141 // renders as fallback and is refilled from the (correct)
1142 // checkpoints by the sync window sweep. Supplied rows are written
1143 // below, so they show correct colors with no flash.
1144 let cover = rows.start.max(r.win.start)..rows.end.min(r.win.end);
1145 for row in cover {
1146 if !win.contains(&row) {
1147 let i = (row - r.win.start) as usize;
1148 r.win_spans[i] = None;
1149 r.win_states[i] = None;
1150 }
1151 }
1152 for ((row, spans), state) in win.zip(win_spans).zip(win_states) {
1153 if let Some(i) = r.win_idx(row) {
1154 r.win_spans[i] = Some(spans);
1155 r.win_states[i] = Some(Box::new(state));
1156 }
1157 }
1158 r.invalid.clear_range(rows);
1159 } else {
1160 for ((row, spans), state) in win.zip(win_spans).zip(win_states) {
1161 // Only still-dirty window rows: never clobber verified spans,
1162 // and a dirty row's state is a probe, not a warm-up source.
1163 if r.invalid.contains(row) {
1164 if let Some(i) = r.win_idx(row) {
1165 r.win_spans[i] = Some(spans);
1166 r.win_states[i] = Some(Box::new(state));
1167 }
1168 }
1169 }
1170 }
1171 }
1172
1173 // Test-only retention probes — the memory canaries count entries, the
1174 // deterministic op-count analog of an RSS measurement.
1175 #[cfg(test)]
1176 fn retained_span_rows(&self) -> usize {
1177 self.ret.win_spans.iter().filter(|s| s.is_some()).count()
1178 }
1179 #[cfg(test)]
1180 fn window_len(&self) -> usize {
1181 debug_assert_eq!(self.ret.win_spans.len(), self.ret.win_states.len());
1182 self.ret.win_spans.len()
1183 }
1184 #[cfg(test)]
1185 fn dirty_row_count(&self) -> u32 {
1186 self.ret.invalid.total_rows()
1187 }
1188 #[cfg(test)]
1189 fn retained_state_rows(&self) -> usize {
1190 self.ret.win_states.iter().filter(|s| s.is_some()).count() + self.ret.checkpoints.len()
1191 }
1192}
1193
1194// ======================================================================
1195// Off-thread bulk tokenization (parallel + speculative sweep).
1196//
1197// The retention cache above serves the UI thread synchronously. On a
1198// multi-million-line document the top-down state chain would make a
1199// jump-to-bottom render fall back to plain text for ~16-20s of single-core
1200// work. Instead the app tokenizes SEGMENTS off-thread over an O(1) `Snapshot`
1201// clone, from GUESSED fresh states, and STITCHES boundaries with the same
1202// convergence rule the cache uses per line: segment i's true end state equals
1203// segment i+1's guessed (fresh) start iff everything downstream is provably
1204// identical. A viewport segment is shown immediately (speculative); the full
1205// document is verified left-to-right and absorbed. All threading is the APP's;
1206// this layer is pure and sync, syntect stays sealed.
1207// ======================================================================
1208
1209/// A cheap-to-clone, `Send + Sync` handle to a grammar + theme for off-thread
1210/// bulk tokenization. Nothing syntect crosses its surface; [`SegmentBoundary`]
1211/// and [`SegmentTokens`] are opaque. Obtain via [`HighlightCache::engine`] (to
1212/// share the cache's exact grammar/theme) or [`HighlightEngine::new`], and move
1213/// clones to worker threads.
1214#[derive(Clone)]
1215pub struct HighlightEngine {
1216 syntax: Arc<SyntaxDef>,
1217 theme: Arc<TokenTheme>,
1218}
1219
1220impl HighlightEngine {
1221 /// An engine over an injected grammar + theme (mirrors [`Highlighter::new`]).
1222 #[must_use]
1223 pub fn new(syntax: SyntaxDef, theme: TokenTheme) -> Self {
1224 Self { syntax: Arc::new(syntax), theme: Arc::new(theme) }
1225 }
1226
1227 /// The document-top fresh start state, as a boundary. The coordinator
1228 /// compares a segment's guessed `Fresh` start against a prior segment's
1229 /// true end with this: equal => the guess was right, the segment verifies
1230 /// as-is; unequal => re-run from the true end.
1231 #[must_use]
1232 pub fn fresh_boundary(&self) -> SegmentBoundary {
1233 SegmentBoundary(Box::new(self.fresh_state()))
1234 }
1235
1236 fn fresh_state(&self) -> LineState {
1237 let syntect = SyntectHighlighter::new(&self.theme.0);
1238 LineState {
1239 parse: ParseState::new(self.syntax.reference()),
1240 highlight: HighlightState::new(&syntect, ScopeStack::new()),
1241 }
1242 }
1243}
1244
1245/// The per-line carry state at a segment edge - opaque, comparable, sendable.
1246/// Two edges compare equal iff everything downstream is provably identical
1247/// (the convergence theorem: same state + same text => same tokens).
1248#[derive(Clone, PartialEq)]
1249pub struct SegmentBoundary(Box<LineState>);
1250
1251/// Where a segment's tokenization begins.
1252pub enum SegmentStart {
1253 /// From the document-top fresh state - a speculative guess, or genuinely
1254 /// row 0.
1255 Fresh,
1256 /// From a known boundary (a prior segment's verified end state).
1257 After(SegmentBoundary),
1258}
1259
1260/// One segment tokenized off-thread - opaque; ingested by
1261/// [`crate::Document::absorb_highlight`]. Carries stride checkpoints, the end
1262/// boundary, and (for a requested sub-range) dense window spans+states.
1263pub struct SegmentTokens {
1264 rows: Range<u32>,
1265 started_fresh: bool,
1266 /// Stride-aligned end-state checkpoints within `rows` (rows where
1267 /// `(row + 1) % HIGHLIGHT_CHECKPOINT_STRIDE == 0`) - the SAME rows the
1268 /// sync walk would pick, so [`HighlightCache::absorb`] merges them cleanly.
1269 checkpoints: Vec<(u32, Box<LineState>)>,
1270 /// End state after `rows.end - 1` (equals the start state if `rows` empty).
1271 end: SegmentBoundary,
1272 /// The captured window sub-range (subset of `rows`) and its dense data.
1273 win: Range<u32>,
1274 win_spans: Vec<Vec<HighlightSpan>>,
1275 win_states: Vec<LineState>,
1276 /// How many rows were actually tokenized (a converging re-run splices the
1277 /// rest from the old segment): `rows.len()` on a full run, less on an
1278 /// early-stop repair. The op-count the repair-bound canary asserts on, and
1279 /// a progress signal for the app.
1280 tokenized: u32,
1281}
1282
1283impl SegmentTokens {
1284 /// The rows this segment covers.
1285 #[must_use]
1286 pub fn rows(&self) -> Range<u32> {
1287 self.rows.clone()
1288 }
1289
1290 /// How many rows this segment actually tokenized (`< rows().len()` when a
1291 /// converging re-run spliced a proven-identical tail from the old segment).
1292 #[must_use]
1293 pub fn tokenized_rows(&self) -> u32 {
1294 self.tokenized
1295 }
1296
1297 /// The end-of-segment boundary (the true state after `rows.end - 1` once
1298 /// this segment is verified) - what the coordinator chains the next
1299 /// segment's verification against.
1300 #[must_use]
1301 pub fn end_boundary(&self) -> &SegmentBoundary {
1302 &self.end
1303 }
1304
1305 /// Whether this segment started from the fresh (guessed) state.
1306 #[must_use]
1307 pub fn started_fresh(&self) -> bool {
1308 self.started_fresh
1309 }
1310
1311 fn checkpoint_at(&self, row: u32) -> Option<&LineState> {
1312 self.checkpoints.binary_search_by_key(&row, |(r, _)| *r).ok().map(|i| &*self.checkpoints[i].1)
1313 }
1314}
1315
1316/// Tokenize `rows` of `snapshot` off-thread - pure, sync, unbudgeted (the app
1317/// runs it on a worker over an O(1) [`Snapshot`] clone). Records stride
1318/// checkpoints and, for `spans_for` intersected with `rows`, dense
1319/// spans+states.
1320///
1321/// `converge_against`: when RE-running a segment from a corrected start (a
1322/// speculative guess proved wrong), pass the old result. At each stride
1323/// checkpoint the new end state is compared with the old's; on the first match
1324/// the tail is spliced verbatim from the old (provably identical downstream) -
1325/// so repair costs O(distance to the construct's close), not O(segment). Pass
1326/// it on a re-run whose `rows` match the old segment's; **the window is forced
1327/// to the old segment's** (the passed `spans_for` is ignored when
1328/// `converge_against` is `Some`), so the caller need not track which window
1329/// the old segment was tokenized with — the splice stays internally consistent
1330/// even if the viewport moved since.
1331#[must_use]
1332pub fn tokenize_segment(
1333 engine: &HighlightEngine,
1334 snapshot: &Snapshot,
1335 rows: Range<u32>,
1336 start: SegmentStart,
1337 spans_for: Option<Range<u32>>,
1338 converge_against: Option<&SegmentTokens>,
1339) -> SegmentTokens {
1340 let syntect = SyntectHighlighter::new(&engine.theme.0);
1341 let set = &engine.syntax.set;
1342 let started_fresh = matches!(start, SegmentStart::Fresh);
1343 let mut state = match start {
1344 SegmentStart::Fresh => engine.fresh_state(),
1345 SegmentStart::After(b) => *b.0,
1346 };
1347
1348 let n = snapshot.line_count();
1349 let lo = rows.start.min(n);
1350 let hi = rows.end.min(n);
1351 // A converging re-run splices the old segment's window tail, so its window
1352 // MUST equal the old segment's — enforce that here regardless of the
1353 // caller's `spans_for`. The coordinator can dispatch a re-run with a moved
1354 // viewport's `spans_for` while `converge_against` still carries the original
1355 // window; honoring the moved one would splice mismatched rows. When
1356 // re-running, the window IS the old segment's window.
1357 let win = match converge_against {
1358 Some(old) => old.win.clone(),
1359 None => spans_for
1360 .map(|w| w.start.max(lo)..w.end.min(hi))
1361 .filter(|w| w.start < w.end)
1362 .unwrap_or(lo..lo),
1363 };
1364
1365 let mut checkpoints: Vec<(u32, Box<LineState>)> = Vec::new();
1366 let mut win_spans: Vec<Vec<HighlightSpan>> = Vec::with_capacity(win.len());
1367 let mut win_states: Vec<LineState> = Vec::with_capacity(win.len());
1368
1369 let mut row = lo;
1370 while row < hi {
1371 let line = snapshot.line(row);
1372 let (spans, end) = tokenize_line(&syntect, set, &state, line.as_ref());
1373 if win.contains(&row) {
1374 win_spans.push(spans);
1375 win_states.push(end.clone());
1376 }
1377 state = end;
1378 if (row + 1).is_multiple_of(HIGHLIGHT_CHECKPOINT_STRIDE) {
1379 checkpoints.push((row, Box::new(state.clone())));
1380 // Early-stop against the old segment on a corrected re-run: the
1381 // new state after `row` matching the old's checkpoint there means
1382 // every later row is provably identical - splice the old tail.
1383 if let Some(old) = converge_against {
1384 if old.checkpoint_at(row).is_some_and(|s| *s == state) {
1385 debug_assert_eq!(win, old.win, "the window was forced to old.win above");
1386 for (r, s) in &old.checkpoints {
1387 if *r > row {
1388 checkpoints.push((*r, s.clone()));
1389 }
1390 }
1391 for (k, wr) in old.win.clone().enumerate() {
1392 if wr > row {
1393 win_spans.push(old.win_spans[k].clone());
1394 win_states.push(old.win_states[k].clone());
1395 }
1396 }
1397 return SegmentTokens {
1398 rows,
1399 started_fresh,
1400 checkpoints,
1401 end: old.end.clone(),
1402 win,
1403 win_spans,
1404 win_states,
1405 tokenized: row - lo + 1, // rows lo..=row were run
1406 };
1407 }
1408 }
1409 }
1410 row += 1;
1411 }
1412
1413 SegmentTokens {
1414 rows,
1415 started_fresh,
1416 checkpoints,
1417 end: SegmentBoundary(Box::new(state)),
1418 win,
1419 win_spans,
1420 win_states,
1421 tokenized: hi - lo,
1422 }
1423}
1424
1425impl Retention {
1426 /// The window slot for `row`, if it is inside the retention window (and
1427 /// the document).
1428 fn win_idx(&self, row: u32) -> Option<usize> {
1429 (self.win.contains(&row) && row < self.n_lines).then(|| (row - self.win.start) as usize)
1430 }
1431
1432 /// Move the dense retention window through the per-edit line splices,
1433 /// keeping it aimed at the same buffer rows: a row above an edit shifts by
1434 /// that edit's line delta, a row inside an edit loses its now-stale span but
1435 /// keeps a convergence probe (the edit's old end state) so a state-neutral
1436 /// keystroke still converges in O(1), and rows below are untouched. Because
1437 /// it rides the per-edit spans (not one covering range), a SCATTERED
1438 /// multi-caret edit whose first-to-last span engulfs the window neither
1439 /// drains nor repositions it — the visible rows stay in the window and
1440 /// recolor on the next tokenize, rather than going stale until a scroll
1441 /// fires `set_window`. Bounded to [`HIGHLIGHT_MAX_WINDOW_ROWS`];
1442 /// O(window + edits).
1443 fn shift_window(&mut self, spans: &[(u32, u32, u32)]) {
1444 if spans.is_empty() {
1445 return;
1446 }
1447 let b = HIGHLIGHT_MAX_WINDOW_ROWS as usize;
1448 let mut pref: Vec<i64> = Vec::with_capacity(spans.len() + 1);
1449 pref.push(0);
1450 for &(_, o, n) in spans {
1451 pref.push(pref[pref.len() - 1] + i64::from(n) - i64::from(o));
1452 }
1453 // Displacement of a pre-edit row NOT inside any edit = delta of edits
1454 // entirely above it.
1455 let shift_at = |pre: u32| -> i64 { pref[spans.partition_point(|s| s.0 + s.1 <= pre)] };
1456 let edited = |pre: u32| -> bool {
1457 let i = spans.partition_point(|s| s.0 + s.1 <= pre);
1458 i < spans.len() && pre >= spans[i].0
1459 };
1460 // Convergence probes: each edit's OLD end state (of its last old row),
1461 // read BEFORE the window moves, keyed by the post row it lands on.
1462 let mut probes: Vec<(u32, Box<LineState>)> = Vec::new();
1463 for (j, &(ps, o, n)) in spans.iter().enumerate() {
1464 if n == 0 {
1465 continue;
1466 }
1467 if let Some(st) = self.stored_state_after(ps + o - 1) {
1468 let post = (i64::from(ps) + pref[j]) as u32 + n - 1;
1469 probes.push((post, Box::new(st.clone())));
1470 }
1471 }
1472 let old_start = self.win.start;
1473 let new_start = (i64::from(old_start) + shift_at(old_start)) as u32;
1474 let old_spans = std::mem::take(&mut self.win_spans);
1475 let old_states = std::mem::take(&mut self.win_states);
1476 // Survivors: window rows not inside an edit, at their post positions —
1477 // `(post row, spans, end state)`.
1478 type Survivor = (u32, Option<Vec<HighlightSpan>>, Option<Box<LineState>>);
1479 let mut max_post = new_start;
1480 let mut survivors: Vec<Survivor> = Vec::with_capacity(old_spans.len());
1481 for (idx, (sp, st)) in old_spans.into_iter().zip(old_states).enumerate() {
1482 let pre = old_start + idx as u32;
1483 if edited(pre) {
1484 continue; // edited row → span stale (a probe below drives convergence)
1485 }
1486 let post = (i64::from(pre) + shift_at(pre)) as u32;
1487 max_post = max_post.max(post);
1488 survivors.push((post, sp, st));
1489 }
1490 for (r, _) in &probes {
1491 max_post = max_post.max(*r);
1492 }
1493 let len = ((max_post + 1).saturating_sub(new_start) as usize).min(b);
1494 let mut spans_v: Vec<Option<Vec<HighlightSpan>>> = vec![None; len];
1495 let mut states_v: Vec<Option<Box<LineState>>> = vec![None; len];
1496 for (post, sp, st) in survivors {
1497 if let Some(i) = post.checked_sub(new_start).map(|d| d as usize) {
1498 if i < len {
1499 spans_v[i] = sp;
1500 states_v[i] = st;
1501 }
1502 }
1503 }
1504 for (post, probe) in probes {
1505 if let Some(i) = post.checked_sub(new_start).map(|d| d as usize) {
1506 if i < len && states_v[i].is_none() {
1507 states_v[i] = Some(probe);
1508 }
1509 }
1510 }
1511 self.win = new_start..new_start + len as u32;
1512 self.win_spans = spans_v;
1513 self.win_states = states_v;
1514 }
1515
1516 /// The stored end state after `row`: its window slot, else an exact
1517 /// checkpoint. Trustworthy only when `first_dirty()` is above `row` — the
1518 /// invariant that the first dirty line implies every line above it is
1519 /// valid.
1520 fn stored_state_after(&self, row: u32) -> Option<&LineState> {
1521 if let Some(i) = self.win_idx(row) {
1522 if let Some(s) = &self.win_states[i] {
1523 return Some(s);
1524 }
1525 }
1526 self.checkpoints.state_at(row)
1527 }
1528
1529 /// The nearest stored state at or before `row` (window slot or
1530 /// checkpoint), for warm-up.
1531 fn nearest_state_at_or_before(&self, row: u32) -> Option<(u32, &LineState)> {
1532 let cp = self.checkpoints.floor(row);
1533 // A window state can only beat the checkpoint in (cp_row, row] — scan
1534 // down just that far.
1535 let mut ws = None;
1536 if !self.win.is_empty() && self.win.start <= row {
1537 let hi = row.min(self.win.end - 1);
1538 let lo = cp.map_or(self.win.start, |(r, _)| (r + 1).max(self.win.start));
1539 let mut r = hi;
1540 while r >= lo {
1541 if let Some(s) = &self.win_states[(r - self.win.start) as usize] {
1542 ws = Some((r, &**s));
1543 break;
1544 }
1545 if r == lo {
1546 break;
1547 }
1548 r -= 1;
1549 }
1550 }
1551 match (cp, ws) {
1552 (Some(c), Some(w)) => Some(if w.0 >= c.0 { w } else { c }),
1553 (c, w) => w.or(c),
1554 }
1555 }
1556
1557 /// The start state for tokenizing `row`.
1558 fn start_state_for(&self, row: u32) -> StartState {
1559 if row == 0 {
1560 return StartState::Fresh;
1561 }
1562 if let Some(s) = self.stored_state_after(row - 1) {
1563 return StartState::Ready(s.clone());
1564 }
1565 match self.nearest_state_at_or_before(row - 1) {
1566 Some((r, s)) => StartState::WarmupStored(r, s.clone()),
1567 None => StartState::WarmupFresh,
1568 }
1569 }
1570
1571 /// Tokenize the clean rows between `from` (the row whose end state
1572 /// `state` is; `None` ⇒ fresh before row 0) and `to` (exclusive) to
1573 /// re-derive `to`'s start state, retaining as it goes. `None` if the
1574 /// budget dies first (a resume checkpoint is recorded).
1575 #[allow(clippy::too_many_arguments)]
1576 fn warm_up<S: AsRef<str>>(
1577 &mut self,
1578 from: Option<u32>,
1579 to: u32,
1580 mut state: LineState,
1581 work: &mut u32,
1582 max_lines: u32,
1583 syntect: &SyntectHighlighter<'_>,
1584 set: &SyntaxSet,
1585 line: &mut impl FnMut(u32) -> S,
1586 ) -> Option<LineState> {
1587 let mut r = from;
1588 loop {
1589 let next = r.map_or(0, |r| r + 1);
1590 if next >= to {
1591 return Some(state);
1592 }
1593 if *work >= max_lines {
1594 if let Some(r) = r {
1595 self.keep_resume_checkpoint(Some(r), &state);
1596 }
1597 return None;
1598 }
1599 let (spans, end) = tokenize_line(syntect, set, &state, line(next).as_ref());
1600 self.retain(next, spans, &end);
1601 *work += 1;
1602 r = Some(next);
1603 state = end;
1604 }
1605 }
1606
1607 /// Retain one tokenized row: spans + state in the window, a checkpoint at
1608 /// stride rows — and, crucially, a freshly tokenized row REFRESHES any
1609 /// checkpoint already sitting at it. Checkpoints drift off the stride grid
1610 /// (edits shift them; budget stops pin arbitrary rows), and a stale one
1611 /// left below the frontier would poison later warm-ups into permanently
1612 /// wrong colors. Stride inserts also prune the now-redundant off-grid
1613 /// checkpoints in the stride behind them, so drift and old resume pins
1614 /// cannot accumulate.
1615 fn retain(&mut self, row: u32, spans: Vec<HighlightSpan>, end: &LineState) {
1616 if let Some(i) = self.win_idx(row) {
1617 self.win_spans[i] = Some(spans);
1618 self.win_states[i] = Some(Box::new(end.clone()));
1619 }
1620 if (row + 1).is_multiple_of(HIGHLIGHT_CHECKPOINT_STRIDE) {
1621 self.checkpoints.set_stride(row, end.clone());
1622 } else {
1623 // A drifted (off-grid) checkpoint sitting on this freshly tokenized
1624 // row is refreshed so a stale state can't poison a later warm-up; a
1625 // no-op when none is there. Do not prune (it is not stride-aligned).
1626 self.checkpoints.refresh_if_present(row, end.clone());
1627 }
1628 }
1629
1630 /// A budget stop about to abandon the state after `row`: pin it as a
1631 /// checkpoint if nothing stores it, so the next call resumes without
1632 /// re-warming.
1633 fn keep_resume_checkpoint(&mut self, row: Option<u32>, state: &LineState) {
1634 let Some(row) = row else { return }; // before row 0 — fresh is free
1635 if self.stored_state_after(row).is_none() {
1636 self.checkpoints.upsert(row, state.clone());
1637 }
1638 }
1639
1640 /// The first window row below `before` whose spans await a (re)fill.
1641 fn first_window_gap(&self, before: u32) -> Option<u32> {
1642 let end = self.win.end.min(self.n_lines).min(before);
1643 (self.win.start..end).find(|&r| self.win_spans[(r - self.win.start) as usize].is_none())
1644 }
1645}
1646
1647#[cfg(test)]
1648mod tests {
1649 use super::*;
1650
1651 // A one-rule grammar: the word `kw` is a keyword.
1652 const GRAMMAR: &str = "%YAML 1.2\n\
1653 ---\n\
1654 name: Test\n\
1655 scope: source.test\n\
1656 contexts:\n\
1657 \x20 main:\n\
1658 \x20 - match: '\\bkw\\b'\n\
1659 \x20 scope: keyword.control.test\n";
1660
1661 // A minimal theme: default white, keyword red.
1662 const THEME: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
1663<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1664<plist version="1.0"><dict>
1665<key>name</key><string>Test</string>
1666<key>settings</key><array>
1667<dict><key>settings</key><dict><key>background</key><string>#000000</string><key>foreground</key><string>#ffffff</string></dict></dict>
1668<dict><key>scope</key><string>keyword</string><key>settings</key><dict><key>foreground</key><string>#ff0000</string></dict></dict>
1669</array></dict></plist>"#;
1670
1671 fn highlighter() -> Highlighter {
1672 Highlighter::new(
1673 SyntaxDef::from_sublime_syntax(GRAMMAR).expect("grammar parses"),
1674 TokenTheme::from_tm_theme(THEME).expect("theme parses"),
1675 )
1676 }
1677
1678 #[test]
1679 fn keyword_gets_the_keyword_color() {
1680 let lines = highlighter().highlight("kw x");
1681 assert_eq!(lines.len(), 1);
1682 // The `kw` at bytes 0..2 is red; something else is white.
1683 let red = Rgba { r: 0xff, g: 0, b: 0, a: 0xff };
1684 let white = Rgba { r: 0xff, g: 0xff, b: 0xff, a: 0xff };
1685 let kw = lines[0].iter().find(|s| s.range == (0..2)).expect("a span at 0..2");
1686 assert_eq!(kw.style.fg, red);
1687 assert!(lines[0].iter().any(|s| s.style.fg == white), "non-keyword text is default white");
1688 }
1689
1690 #[test]
1691 fn per_line_spans_and_a_trailing_empty_line() {
1692 let lines = highlighter().highlight("kw\nx\n");
1693 assert_eq!(lines.len(), 3); // "kw", "x", "" (trailing)
1694 assert!(lines[0].iter().any(|s| s.range == (0..2))); // "kw" on line 0
1695 assert!(lines[2].is_empty()); // the empty final line has no spans
1696 }
1697
1698 fn cache(n: u32) -> HighlightCache {
1699 HighlightCache::new(
1700 SyntaxDef::from_sublime_syntax(GRAMMAR).unwrap(),
1701 TokenTheme::from_tm_theme(THEME).unwrap(),
1702 n,
1703 )
1704 }
1705
1706 fn lines(text: &str) -> Vec<&str> {
1707 text.split('\n').collect()
1708 }
1709
1710 /// After tokenizing, every cached line must equal a fresh whole-document
1711 /// highlight of the same text — the convergence invariant, whatever the
1712 /// edit path.
1713 fn assert_matches_full(cache: &HighlightCache, text: &str) {
1714 let full = highlighter().highlight(text);
1715 for (row, expected) in full.iter().enumerate() {
1716 assert_eq!(cache.line_spans(row as u32), Some(expected.as_slice()), "line {row}");
1717 }
1718 }
1719
1720 #[test]
1721 fn fresh_cache_matches_whole_document_highlight() {
1722 let text = "kw a\nb kw\nc";
1723 let ls = lines(text);
1724 let mut c = cache(ls.len() as u32);
1725 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1726 assert_matches_full(&c, text);
1727 }
1728
1729 #[test]
1730 fn in_place_edit_reconverges() {
1731 let before = "kw a\nb b\nkw c";
1732 let ls0 = lines(before);
1733 let mut c = cache(ls0.len() as u32);
1734 c.tokenize_until(ls0.len() as u32, u32::MAX, |r| ls0[r as usize]);
1735 // Edit line 1 in place ("b b" -> "b kw"); old == new == 1 line.
1736 let after = "kw a\nb kw\nkw c";
1737 let ls1 = lines(after);
1738 c.on_commit(1, 1, 1);
1739 c.tokenize_until(ls1.len() as u32, u32::MAX, |r| ls1[r as usize]);
1740 assert_matches_full(&c, after);
1741 }
1742
1743 #[test]
1744 fn insert_line_splices_and_reconverges() {
1745 let before = "kw\nx";
1746 let ls0 = lines(before);
1747 let mut c = cache(ls0.len() as u32);
1748 c.tokenize_until(ls0.len() as u32, u32::MAX, |r| ls0[r as usize]);
1749 // Insert a line: line 0 ("kw") becomes two lines ("kw", "y").
1750 let after = "kw\ny\nx";
1751 let ls1 = lines(after);
1752 c.on_commit(0, 1, 2);
1753 c.tokenize_until(ls1.len() as u32, u32::MAX, |r| ls1[r as usize]);
1754 assert_matches_full(&c, after);
1755 }
1756
1757 #[test]
1758 fn theme_swap_invalidates_all_keeps_stale_colors_then_recolors() {
1759 // The same minimal theme, but the keyword is blue instead of red.
1760 const THEME_BLUE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
1761<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1762<plist version="1.0"><dict>
1763<key>name</key><string>Blue</string>
1764<key>settings</key><array>
1765<dict><key>settings</key><dict><key>background</key><string>#000000</string><key>foreground</key><string>#ffffff</string></dict></dict>
1766<dict><key>scope</key><string>keyword</string><key>settings</key><dict><key>foreground</key><string>#0000ff</string></dict></dict>
1767</array></dict></plist>"#;
1768 let red = Rgba { r: 0xff, g: 0, b: 0, a: 0xff };
1769 let blue = Rgba { r: 0, g: 0, b: 0xff, a: 0xff };
1770 let has = |c: &HighlightCache, row: u32, col: Rgba| {
1771 c.line_spans(row).unwrap().iter().any(|s| s.style.fg == col)
1772 };
1773 // Two keyword lines, both tokenized (red).
1774 let ls = lines("kw a\nb kw");
1775 let mut c = cache(ls.len() as u32);
1776 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1777 assert!(has(&c, 0, red) && has(&c, 1, red));
1778 // Swap the theme: every line goes dirty, but the OLD (red) spans stay as
1779 // a stale fallback — no flash to default before the repaint.
1780 c.set_theme(TokenTheme::from_tm_theme(THEME_BLUE).unwrap());
1781 assert!(has(&c, 0, red) && has(&c, 1, red), "stale colors until repainted");
1782 // Repaint the whole cache: the keyword is now blue on every line, no red left.
1783 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1784 assert!(has(&c, 0, blue) && has(&c, 1, blue), "both lines recolored");
1785 assert!(!has(&c, 0, red) && !has(&c, 1, red), "no stale red survives repaint");
1786 }
1787
1788 #[test]
1789 fn convergence_stops_early_below_an_edit() {
1790 // A grammar with no multi-line state ⇒ every line's end state is equal,
1791 // so an in-place edit converges at the edited line and never re-tokenizes
1792 // the (unchanged) line below it. We prove that by leaving the line below
1793 // deliberately WRONG in `lines` — if it were re-tokenized it would change.
1794 let ls0 = lines("kw\nkw\nkw");
1795 let mut c = cache(3);
1796 c.tokenize_until(3, u32::MAX, |r| ls0[r as usize]);
1797 c.on_commit(0, 1, 1); // edit line 0 only
1798 // Pass a lines slice whose line 2 is a sentinel that must NOT be touched.
1799 let probe_lines = ["kw", "kw", "SHOULD-NOT-RETOKENIZE"];
1800 c.tokenize_until(3, u32::MAX, |r| probe_lines[r as usize]);
1801 // Line 2 kept its original "kw" spans (convergence stopped at line 0).
1802 assert_eq!(c.line_spans(2), Some(highlighter().highlight("kw").pop().unwrap().as_slice()));
1803 }
1804
1805 #[test]
1806 fn perf_canary_state_neutral_keystroke_is_o1_regardless_of_size() {
1807 // Op-count canary (not timing): the test grammar has no multi-line
1808 // state, so editing any line converges at that line — a keystroke
1809 // re-tokenizes ~1 line no matter how big the document is. The "no
1810 // O(file) stacking" guarantee: the number is independent of the
1811 // 2000-line size.
1812 let big = vec!["kw x"; 2000].join("\n");
1813 let ls = lines(&big);
1814 let mut c = cache(ls.len() as u32);
1815 c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]); // full initial pass
1816 c.on_commit(1000, 1, 1); // a keystroke deep in the document
1817 let n = c.tokenize_until(ls.len() as u32, u32::MAX, |r| ls[r as usize]);
1818 assert!(n <= 2, "state-neutral keystroke re-tokenized {n} lines in a 2000-line doc (expected O(1))");
1819 }
1820
1821 #[test]
1822 fn perf_canary_target_bounds_work_to_the_viewport() {
1823 // Perf canary 1 (the viewport-targeting tooth): tokenizing to a viewport
1824 // target does ≤ viewport work, never O(file) — even with every line dirty
1825 // (a fresh cache, or a top-of-file state cascade). 2000 lines dirty,
1826 // target row 50 → exactly 51 lines tokenized, nothing below.
1827 let big = vec!["kw x"; 2000].join("\n");
1828 let ls = lines(&big);
1829 let mut c = cache(ls.len() as u32); // all 2000 lines dirty
1830 let n = c.tokenize_until(50, u32::MAX, |r| ls[r as usize]);
1831 assert_eq!(n, 51, "target must bound tokenization to the viewport (rows 0..=50)");
1832 assert!(c.line_spans(50).is_some(), "the viewport is tokenized");
1833 assert!(c.line_spans(51).is_none(), "nothing past the viewport target is tokenized");
1834 }
1835
1836 #[test]
1837 fn perf_canary_budget_caps_a_call_and_resumes() {
1838 // The per-call budget: one call does at most `max_lines` of work, the
1839 // frontier records where it stopped, and the next call resumes there —
1840 // total work conserved.
1841 let big = vec!["kw x"; 300].join("\n");
1842 let ls = lines(&big);
1843 let mut c = cache(ls.len() as u32);
1844 let n = c.tokenize_until(u32::MAX, 100, |r| ls[r as usize]);
1845 assert_eq!(n, 100, "the budget caps the call");
1846 assert_eq!(c.first_dirty(), Some(100), "the frontier records the resume point");
1847 let n = c.tokenize_until(u32::MAX, u32::MAX, |r| ls[r as usize]);
1848 assert_eq!(n, 200, "the next call finishes the remainder");
1849 assert_eq!(c.first_dirty(), None, "converged");
1850 }
1851
1852 #[test]
1853 fn perf_canary_deep_dirty_tail_commit_is_cheap() {
1854 // A commit must be O(edit + #runs), independent of how long a dirty
1855 // tail the document carries — storing runs (not individual rows) is
1856 // what makes that hold. Generous wall-clock bound (the one in-test
1857 // timing allowed): 1000 commits against a 1M-line dirty tail must be
1858 // near-instant; a per-commit rebuild of the whole dirty set would take
1859 // tens of seconds.
1860 let mut c = cache(1_000_000); // every line dirty, one run
1861 let t0 = std::time::Instant::now();
1862 for _ in 0..1_000 {
1863 c.on_commit(500_000, 1, 1);
1864 }
1865 assert!(
1866 t0.elapsed() < std::time::Duration::from_secs(1),
1867 "1000 deep-dirty-tail commits took {:?} — the dirty set is being rebuilt per commit",
1868 t0.elapsed()
1869 );
1870 assert!(c.ret.invalid.runs() <= 3, "the run list stays compact: {}", c.ret.invalid.runs());
1871 }
1872
1873 #[test]
1874 fn dirty_runs_stay_small_under_a_typing_run() {
1875 let mut c = cache(2_000);
1876 // Converge everything first.
1877 let big = vec!["kw x"; 2000].join("\n");
1878 let ls = lines(&big);
1879 c.tokenize_until(u32::MAX, u32::MAX, |r| ls[r as usize]);
1880 // A typing run at one spot, plus a couple of scattered edits.
1881 for _ in 0..50 {
1882 c.on_commit(700, 1, 1);
1883 }
1884 c.on_commit(100, 1, 2);
1885 c.on_commit(1500, 2, 1);
1886 assert!(c.ret.invalid.runs() <= 4, "scattered typing produced {} runs", c.ret.invalid.runs());
1887 }
1888
1889 // ------------------------------------------------------------------
1890 // Highlight virtualization: a STATEFUL grammar — an unterminated `"` flips
1891 // every following line into the `string` context — so checkpoints,
1892 // warm-ups, and cross-stride convergence are exercised for real (the `kw`
1893 // grammar above is stateless: every end state is equal, which can never
1894 // distinguish a right checkpoint from a wrong one).
1895 // ------------------------------------------------------------------
1896 const GRAMMAR_STR: &str = "%YAML 1.2\n\
1897 ---\n\
1898 name: TestStr\n\
1899 scope: source.tstr\n\
1900 contexts:\n\
1901 \x20 main:\n\
1902 \x20 - match: '\"'\n\
1903 \x20 scope: punctuation.definition.string.begin\n\
1904 \x20 push: string\n\
1905 \x20 - match: '\\bkw\\b'\n\
1906 \x20 scope: keyword.control.test\n\
1907 \x20 string:\n\
1908 \x20 - match: '\"'\n\
1909 \x20 scope: punctuation.definition.string.end\n\
1910 \x20 pop: true\n\
1911 \x20 - match: '.'\n\
1912 \x20 scope: string.quoted.test\n";
1913
1914 // A grammar with an ASYMMETRIC block comment (`/* … */`): unlike the
1915 // symmetric `"` toggle, a wrong guess about being inside a comment
1916 // SELF-HEALS at the next `*/` (which returns to ground unconditionally),
1917 // so a mis-guessed segment re-CONVERGES — the case the stitch's early-stop
1918 // splice exists for. (`/*` only opens from `main`; `*/` only closes from
1919 // `comment`; neither nests.)
1920 const GRAMMAR_CMT: &str = "%YAML 1.2\n\
1921 ---\n\
1922 name: TestCmt\n\
1923 scope: source.tcmt\n\
1924 contexts:\n\
1925 \x20 main:\n\
1926 \x20 - match: '/\\*'\n\
1927 \x20 scope: punctuation.definition.comment.begin\n\
1928 \x20 push: comment\n\
1929 \x20 - match: '\\bkw\\b'\n\
1930 \x20 scope: keyword.control.test\n\
1931 \x20 comment:\n\
1932 \x20 - match: '\\*/'\n\
1933 \x20 scope: punctuation.definition.comment.end\n\
1934 \x20 pop: true\n\
1935 \x20 - match: '.'\n\
1936 \x20 scope: comment.block.test\n";
1937
1938 fn engine_cmt() -> HighlightEngine {
1939 HighlightEngine::new(
1940 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1941 TokenTheme::from_tm_theme(THEME).unwrap(),
1942 )
1943 }
1944
1945 fn cache_cmt(n: u32) -> HighlightCache {
1946 HighlightCache::new(
1947 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1948 TokenTheme::from_tm_theme(THEME).unwrap(),
1949 n,
1950 )
1951 }
1952
1953 fn highlighter_cmt() -> Highlighter {
1954 Highlighter::new(
1955 SyntaxDef::from_sublime_syntax(GRAMMAR_CMT).unwrap(),
1956 TokenTheme::from_tm_theme(THEME).unwrap(),
1957 )
1958 }
1959
1960 fn cache_str(n: u32) -> HighlightCache {
1961 HighlightCache::new(
1962 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
1963 TokenTheme::from_tm_theme(THEME).unwrap(),
1964 n,
1965 )
1966 }
1967
1968 fn highlighter_str() -> Highlighter {
1969 Highlighter::new(
1970 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
1971 TokenTheme::from_tm_theme(THEME).unwrap(),
1972 )
1973 }
1974
1975 /// Drive to full convergence (dirty walk + window refill), budgeted like
1976 /// the real sweep.
1977 fn drive_all(c: &mut HighlightCache, lines: &[String]) -> u32 {
1978 let mut work = 0;
1979 while c.pending().is_some() {
1980 work += c
1981 .tokenize_until(u32::MAX, HIGHLIGHT_MAX_LINES_PER_CALL, |r| lines[r as usize].as_str());
1982 }
1983 work
1984 }
1985
1986 /// The virtualization guarantee: sweeping a 10k-line document with the
1987 /// window aimed at the top retains a bounded number of rows, not the whole
1988 /// document — spans and states outside the window are evicted, so RAM does
1989 /// not grow with the sweep.
1990 #[test]
1991 fn virtualized_sweep_retains_bounded_rows() {
1992 let lines: Vec<String> = (0..10_000).map(|i| format!("kw line {i}")).collect();
1993 let mut c = cache(10_000);
1994 c.set_window(0..64);
1995 drive_all(&mut c, &lines);
1996 let window_bound = (64 + 2 * HIGHLIGHT_WINDOW_SLACK) as usize;
1997 assert!(
1998 c.retained_span_rows() <= window_bound,
1999 "span retention must be windowed: {} rows kept (bound {window_bound})",
2000 c.retained_span_rows()
2001 );
2002 let state_bound = window_bound + 3 * (10_000 / HIGHLIGHT_CHECKPOINT_STRIDE as usize);
2003 assert!(
2004 c.retained_state_rows() <= state_bound,
2005 "state retention must be window + sparse checkpoints: {} kept (bound {state_bound})",
2006 c.retained_state_rows()
2007 );
2008 // Retention is bounded but the window is still CORRECT…
2009 let full = highlighter().highlight(&lines.join("\n"));
2010 assert_eq!(c.line_spans(10), Some(full[10].as_slice()));
2011 // …and out-of-window rows honestly report nothing (fallback render).
2012 assert_eq!(c.line_spans(5_000), None);
2013 }
2014
2015 /// A window move over already-swept rows refills from the nearest
2016 /// checkpoint: correct spans (stateful grammar — a wrong warm-up state
2017 /// would color the string region wrong), bounded work.
2018 #[test]
2019 fn window_move_refills_from_checkpoints() {
2020 let mut lines: Vec<String> = (0..3_000).map(|i| format!("x {i} kw")).collect();
2021 lines[1_000] = "\"open".into(); // unterminated: rows 1001.. are in-string
2022 lines[2_000] = "close\"".into(); // …until the string pops here
2023 let full = highlighter_str().highlight(&lines.join("\n"));
2024 let mut c = cache_str(3_000);
2025 c.set_window(0..40);
2026 drive_all(&mut c, &lines);
2027 assert!(c.line_spans(1_600).is_none(), "deep rows evicted after the sweep");
2028
2029 // Cold jump into the middle of the multi-line string.
2030 c.set_window(1_500..1_540);
2031 let fill_work = drive_all(&mut c, &lines);
2032 for r in 1_500..1_540 {
2033 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2034 }
2035 assert_eq!(c.line_spans(10), None, "the old window was evicted");
2036 // ≤ one stride of warm-up + the retained window (+ a little dust).
2037 let bound = HIGHLIGHT_CHECKPOINT_STRIDE + 40 + 2 * HIGHLIGHT_WINDOW_SLACK + 8;
2038 assert!(fill_work <= bound, "cold-jump refill did {fill_work} lines (bound {bound})");
2039 }
2040
2041 /// A state-neutral edit OUTSIDE the window re-converges at checkpoint
2042 /// grain: bounded by strides (+ warm-up), never by the document — and
2043 /// the far-away window's rows stay correct.
2044 #[test]
2045 fn out_of_window_edit_reconverges_within_a_stride() {
2046 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2047 let mut c = cache_str(2_000);
2048 c.set_window(1_500..1_540);
2049 drive_all(&mut c, &lines);
2050 lines[100] = "kw edited".into(); // state-neutral, far above the window
2051 c.on_commit(100, 1, 1);
2052 let work = drive_all(&mut c, &lines);
2053 let bound = 2 * HIGHLIGHT_CHECKPOINT_STRIDE + 2;
2054 assert!(work <= bound, "out-of-window keystroke re-tokenized {work} lines (bound {bound})");
2055 let full = highlighter_str().highlight(&lines.join("\n"));
2056 assert_eq!(c.line_spans(1_520), Some(full[1_520].as_slice()));
2057 }
2058
2059 /// An in-window state-neutral keystroke stays O(1) under the STATEFUL
2060 /// grammar too — per-line convergence probes live in the window.
2061 #[test]
2062 fn in_window_keystroke_stays_o1_with_stateful_grammar() {
2063 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2064 lines[300] = "\"open".into();
2065 lines[600] = "shut\"".into();
2066 let mut c = cache_str(2_000);
2067 c.set_window(900..940);
2068 drive_all(&mut c, &lines);
2069 lines[920] = "kw retyped".into();
2070 c.on_commit(920, 1, 1);
2071 let work = drive_all(&mut c, &lines);
2072 assert!(work <= 2, "in-window keystroke re-tokenized {work} lines (expected O(1))");
2073 }
2074
2075 /// The randomized battering ram: seeded edits, window moves, and
2076 /// budget-starved drives in any order — after convergence, every retained
2077 /// row equals the whole-document oracle, wherever the window lands.
2078 #[test]
2079 fn randomized_edits_and_window_moves_match_the_oracle() {
2080 let mut lines: Vec<String> = (0..1_200)
2081 .map(|i| match i % 97 {
2082 13 => "\"".to_string(),
2083 51 => "shut\" kw".to_string(),
2084 _ => format!("kw word {i}"),
2085 })
2086 .collect();
2087 let mut c = cache_str(1_200);
2088 let mut state = 0xDEADBEEF_u64;
2089 let mut rand = move |bound: usize| {
2090 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2091 ((state >> 33) as usize) % bound.max(1)
2092 };
2093 for _step in 0..120 {
2094 match rand(3) {
2095 0 => {
2096 let s = rand(lines.len());
2097 let old = (1 + rand(3)).min(lines.len() - s);
2098 let n = 1 + rand(3);
2099 let repl: Vec<String> = (0..n)
2100 .map(|k| match rand(5) {
2101 0 => "\"".to_string(),
2102 1 => "q\" kw".to_string(),
2103 _ => format!("e{k} kw"),
2104 })
2105 .collect();
2106 lines.splice(s..s + old, repl);
2107 c.on_commit(s as u32, old as u32, n as u32);
2108 }
2109 1 => {
2110 let s = rand(lines.len());
2111 c.set_window(s as u32..(s + 40).min(lines.len()) as u32);
2112 }
2113 _ => {
2114 let target = rand(lines.len()) as u32;
2115 let budget = 32 + rand(200) as u32;
2116 c.tokenize_until(target, budget, |r| lines[r as usize].as_str());
2117 }
2118 }
2119 assert_eq!(c.line_count() as usize, lines.len(), "line count in step");
2120 }
2121 // Converge, then check every retained row — and re-aim the window at
2122 // several places so refill paths get checked against the oracle too.
2123 let full = highlighter_str().highlight(&lines.join("\n"));
2124 drive_all(&mut c, &lines);
2125 let mut checked = 0usize;
2126 for r in 0..lines.len() as u32 {
2127 if let Some(spans) = c.line_spans(r) {
2128 assert_eq!(spans, full[r as usize].as_slice(), "row {r}");
2129 checked += 1;
2130 }
2131 }
2132 assert!(checked >= 40, "the window retained rows to check ({checked})");
2133 for &probe in &[0usize, 400, 800, lines.len().saturating_sub(45)] {
2134 c.set_window(probe as u32..(probe + 40).min(lines.len()) as u32);
2135 drive_all(&mut c, &lines);
2136 for (r, expected) in
2137 full.iter().enumerate().take((probe + 40).min(lines.len())).skip(probe)
2138 {
2139 assert_eq!(c.line_spans(r as u32), Some(expected.as_slice()), "probe {probe} row {r}");
2140 }
2141 }
2142 }
2143
2144 #[test]
2145 fn scattered_multi_caret_marks_only_edited_lines_dirty() {
2146 // A scattered multi-caret keystroke folds into ONE covering line range
2147 // (first caret .. last caret). The dirty set must hold only the EDITED
2148 // lines (per-edit spans), not the whole covering span — else the sweep
2149 // re-tokenizes O(document) between the carets.
2150 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2151 let mut c = cache_str(2_000);
2152 c.set_window(0..40);
2153 drive_all(&mut c, &lines);
2154 assert_eq!(c.dirty_row_count(), 0, "swept clean");
2155 // Two carets, rows 10 and 1_500, one char each (state-neutral, 1→1).
2156 lines[10] = "kw a".into();
2157 lines[1_500] = "kw b".into();
2158 c.on_commit_patch(&[(10, 1, 1), (1_500, 1, 1)]);
2159 assert_eq!(
2160 c.dirty_row_count(),
2161 2,
2162 "a scattered 2-caret edit must mark 2 lines dirty, not the ~1491-row covering span"
2163 );
2164 // …and the highlight is still correct after the sweep.
2165 drive_all(&mut c, &lines);
2166 let full = highlighter_str().highlight(&lines.join("\n"));
2167 for r in 0..40 {
2168 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2169 }
2170 }
2171
2172 #[test]
2173 fn scattered_edit_keeps_the_window_aimed_at_the_viewport() {
2174 // Select-all-occurrences of a word + delete is a scattered multi-edit
2175 // whose covering range engulfs the viewport window. The window must
2176 // stay aimed at the viewport (only the edited rows invalidated), so the
2177 // VISIBLE rows recolor on the next tokenize — not only after a scroll
2178 // fires set_window and re-aims it. A splice that rode the covering range
2179 // would drain or reposition the window, dropping the visible rows to
2180 // fallback until a scrollwheel tick.
2181 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2182 let mut c = cache_str(2_000);
2183 c.set_window(940..980);
2184 drive_all(&mut c, &lines);
2185 assert!(c.line_spans(960).is_some(), "the viewport window is filled");
2186 // Delete a word at scattered occurrences: rows 10, 960 (in view), 1_500,
2187 // one transaction, all state-neutral (1→1). Covering range 10..1_500
2188 // engulfs the window at 940..980.
2189 for r in [10usize, 960, 1_500] {
2190 lines[r] = "kw w".into();
2191 }
2192 c.on_commit_patch(&[(10, 1, 1), (960, 1, 1), (1_500, 1, 1)]);
2193 // Tokenize WITHOUT re-aiming the window (no set_window / no scroll).
2194 drive_all(&mut c, &lines);
2195 let full = highlighter_str().highlight(&lines.join("\n"));
2196 for r in 940..980u32 {
2197 assert_eq!(
2198 c.line_spans(r),
2199 Some(full[r as usize].as_slice()),
2200 "viewport row {r} did not recolor without a scroll to re-aim the window",
2201 );
2202 }
2203 }
2204
2205 /// The multi-edit analogue of the randomized oracle: each step commits a
2206 /// TRANSACTION of several disjoint edits at once via `on_commit_patch` (the
2207 /// scattered multi-caret path), and after convergence every retained row
2208 /// must still equal the whole-document oracle. Guards the per-edit
2209 /// checkpoint/dirty merge walks against any shift or coalescing bug.
2210 #[test]
2211 fn randomized_multi_edit_commits_match_the_oracle() {
2212 let mut lines: Vec<String> = (0..1_200)
2213 .map(|i| match i % 97 {
2214 13 => "\"".to_string(),
2215 51 => "shut\" kw".to_string(),
2216 _ => format!("kw word {i}"),
2217 })
2218 .collect();
2219 let mut c = cache_str(1_200);
2220 let mut state = 0x1234_5678_9ABC_DEF0_u64;
2221 let mut rand = move |bound: usize| {
2222 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2223 ((state >> 33) as usize) % bound.max(1)
2224 };
2225 for _step in 0..80 {
2226 if rand(3) == 2 {
2227 // Sometimes just tokenize a budget, leaving dirt around.
2228 let target = rand(lines.len()) as u32;
2229 c.tokenize_until(target, 32 + rand(200) as u32, |r| lines[r as usize].as_str());
2230 assert_eq!(c.line_count() as usize, lines.len());
2231 continue;
2232 }
2233 // Build up to 4 disjoint edits, ascending with a gap between each.
2234 let k = 1 + rand(4);
2235 let mut sites: Vec<(usize, usize, Vec<String>)> = Vec::new();
2236 let mut cursor = rand(20);
2237 for _ in 0..k {
2238 let s = cursor + rand(30);
2239 if s >= lines.len() {
2240 break;
2241 }
2242 let old = (1 + rand(3)).min(lines.len() - s);
2243 let n = 1 + rand(3);
2244 let repl: Vec<String> = (0..n)
2245 .map(|j| match rand(5) {
2246 0 => "\"".to_string(),
2247 1 => "q\" kw".to_string(),
2248 _ => format!("m{j} kw"),
2249 })
2250 .collect();
2251 sites.push((s, old, repl));
2252 cursor = s + old + 1; // a gap ⇒ the next start is strictly after
2253 }
2254 if sites.is_empty() {
2255 continue;
2256 }
2257 // Per-edit spans (pre-edit, disjoint) + the covering splice.
2258 let spans: Vec<(u32, u32, u32)> =
2259 sites.iter().map(|(s, o, r)| (*s as u32, *o as u32, r.len() as u32)).collect();
2260 c.on_commit_patch(&spans);
2261 // Apply to `lines` back-to-front so earlier indices stay valid.
2262 for (s, o, repl) in sites.iter().rev() {
2263 lines.splice(*s..*s + *o, repl.clone());
2264 }
2265 assert_eq!(c.line_count() as usize, lines.len(), "line count after multi-edit");
2266 }
2267 let full = highlighter_str().highlight(&lines.join("\n"));
2268 drive_all(&mut c, &lines);
2269 let mut checked = 0usize;
2270 for r in 0..lines.len() as u32 {
2271 if let Some(spans) = c.line_spans(r) {
2272 assert_eq!(spans, full[r as usize].as_slice(), "row {r}");
2273 checked += 1;
2274 }
2275 }
2276 assert!(checked >= 40, "retained rows to check ({checked})");
2277 for &probe in &[0usize, 300, 700, lines.len().saturating_sub(45)] {
2278 c.set_window(probe as u32..(probe + 40).min(lines.len()) as u32);
2279 drive_all(&mut c, &lines);
2280 for (r, expected) in
2281 full.iter().enumerate().take((probe + 40).min(lines.len())).skip(probe)
2282 {
2283 assert_eq!(c.line_spans(r as u32), Some(expected.as_slice()), "probe {probe} row {r}");
2284 }
2285 }
2286 }
2287
2288 /// Checkpoints drift off the stride grid (any line-delta edit shifts them),
2289 /// and a state-changing cascade crossing an off-stride checkpoint must
2290 /// REFRESH it — a stale one left below the frontier poisons a later
2291 /// cold-jump warm-up into permanently wrong highlighting. Fails against a
2292 /// `retain` that only writes stride-aligned checkpoints.
2293 #[test]
2294 fn shifted_checkpoints_are_refreshed_by_a_crossing_cascade() {
2295 let mut lines: Vec<String> = (0..2_000).map(|i| format!("kw {i}")).collect();
2296 let mut c = cache_str(2_000);
2297 c.set_window(0..40);
2298 drive_all(&mut c, &lines);
2299 // A single Enter above everything: every checkpoint shifts off-stride.
2300 lines.insert(10, "kw split".to_string());
2301 c.on_commit(10, 1, 2);
2302 drive_all(&mut c, &lines);
2303 // A state-changing edit near the top: the cascade repaints the tail,
2304 // crossing every shifted checkpoint.
2305 lines[12] = "\"open".to_string(); // unterminated → everything below is in-string
2306 c.on_commit(12, 1, 1);
2307 drive_all(&mut c, &lines);
2308 // Cold-jump far below: the refill warms up from whatever checkpoint
2309 // is nearest — which must hold the POST-cascade (in-string) state.
2310 c.set_window(1_285..1_325);
2311 drive_all(&mut c, &lines);
2312 let full = highlighter_str().highlight(&lines.join("\n"));
2313 for r in 1_285..1_325u32 {
2314 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2315 }
2316 }
2317
2318 /// Off-stride and orphaned resume checkpoints must be pruned as fresh
2319 /// stride checkpoints land, or they accumulate without bound across
2320 /// edit/cascade cycles — slowly re-growing the RAM virtualization keeps
2321 /// bounded.
2322 #[test]
2323 fn checkpoints_do_not_accumulate_across_edit_cycles() {
2324 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw {i}")).collect();
2325 let mut c = cache_str(4_000);
2326 c.set_window(0..40);
2327 drive_all(&mut c, &lines);
2328 for cycle in 0..16 {
2329 // Shift the grid…
2330 lines.insert(5, format!("kw cycle {cycle}"));
2331 c.on_commit(5, 1, 2);
2332 // …and flip the whole tail's state, twice (open then close).
2333 lines[7] = "\"open".to_string();
2334 c.on_commit(7, 1, 1);
2335 drive_all(&mut c, &lines);
2336 lines[7] = "kw closed".to_string();
2337 c.on_commit(7, 1, 1);
2338 drive_all(&mut c, &lines);
2339 }
2340 let bound = 2 * (c.line_count() / HIGHLIGHT_CHECKPOINT_STRIDE) as usize + 8;
2341 assert!(
2342 c.ret.checkpoints.len() <= bound,
2343 "checkpoints accumulate: {} after 16 cycles (bound {bound})",
2344 c.ret.checkpoints.len()
2345 );
2346 }
2347
2348 // ── The checkpoint delta-gap `SumTree` ──────────────────────────────────
2349
2350 /// A fresh (document-top) `LineState` for seeding checkpoint trees without a
2351 /// real sweep — the `main`-context start state.
2352 fn fresh_state() -> LineState {
2353 engine_str().fresh_state()
2354 }
2355
2356 /// A distinct `LineState`: the parser left INSIDE a string context (after an
2357 /// unclosed `"`), so it compares unequal to [`fresh_state`] — lets the oracle
2358 /// pin the `(row, state)` sequence, not just the rows.
2359 fn str_state() -> LineState {
2360 let eng = engine_str();
2361 let syntect = SyntectHighlighter::new(&eng.theme.0);
2362 let (_spans, end) = tokenize_line(&syntect, &eng.syntax.set, &eng.fresh_state(), "\"");
2363 end
2364 }
2365
2366 /// A straightforward flat-Vec checkpoint shift — the ORACLE reference the
2367 /// delta-gap tree's `shift` must match, edit for edit. Drift in a
2368 /// checkpoint row poisons later warm-ups (a wrong start state → permanently
2369 /// wrong colors), so this equivalence is load-bearing.
2370 fn vec_shift_reference(cps: &mut Vec<(u32, Box<LineState>)>, spans: &[(u32, u32, u32)]) {
2371 if spans.is_empty() {
2372 return;
2373 }
2374 let old = std::mem::take(cps);
2375 let mut si = 0;
2376 let mut acc = 0i64;
2377 for (row, state) in old {
2378 while si < spans.len() && spans[si].0 + spans[si].1 <= row {
2379 acc += i64::from(spans[si].2) - i64::from(spans[si].1);
2380 si += 1;
2381 }
2382 if si < spans.len() && row >= spans[si].0 {
2383 continue; // inside a replaced span → stale
2384 }
2385 cps.push(((row as i64 + acc) as u32, state));
2386 }
2387 }
2388
2389 /// ORACLE: the checkpoint tree's `shift` equals the flat-Vec reference under
2390 /// random single- AND multi-edit patches, after EVERY commit. Single-edit
2391 /// patches drive `shift_single` (the windowed seam surgery — the real risk);
2392 /// multi-edit patches drive `shift_walk`. States alternate between two
2393 /// distinct values so a mismapped payload (not just a wrong row) is caught.
2394 #[test]
2395 fn checkpoint_tree_equals_the_vec_reference_under_random_edits() {
2396 let (st_a, st_b) = (fresh_state(), str_state());
2397 assert!(st_a != st_b, "seed states must differ for the state check to bite");
2398 let mut rng = 0x1234_5678u32;
2399 let mut next = || {
2400 rng ^= rng << 13;
2401 rng ^= rng >> 17;
2402 rng ^= rng << 5;
2403 rng
2404 };
2405 for trial in 0..200 {
2406 // A fresh random ascending, distinct checkpoint set per trial.
2407 let mut n_lines = 400u32 + next() % 4_000;
2408 let k = 4 + next() % 60;
2409 let mut rows: Vec<u32> = Vec::new();
2410 let mut r = next() % 40;
2411 for _ in 0..k {
2412 if r >= n_lines {
2413 break;
2414 }
2415 rows.push(r);
2416 r += 1 + next() % 90;
2417 }
2418 let seed = |i: usize| if i.is_multiple_of(2) { st_a.clone() } else { st_b.clone() };
2419 let init: Vec<(u32, Box<LineState>)> =
2420 rows.iter().enumerate().map(|(i, &r)| (r, Box::new(seed(i)))).collect();
2421 let mut tree = {
2422 let items = init.iter().scan(0u32, |prev, (r, s)| {
2423 let gap = r - *prev;
2424 *prev = *r;
2425 Some(CkptItem { row_gap: gap, state: s.clone() })
2426 });
2427 Checkpoints { tree: SumTree::from_items(items) }
2428 };
2429 let mut reference = init;
2430
2431 for step in 0..12 {
2432 // A valid ascending, disjoint patch of 1..=3 edits (mixes the paths).
2433 let n_edits = 1 + (next() % 3) as usize;
2434 let mut spans: Vec<(u32, u32, u32)> = Vec::new();
2435 let mut cursor = 0u32;
2436 for _ in 0..n_edits {
2437 if cursor >= n_lines {
2438 break;
2439 }
2440 let span = (n_lines - cursor).clamp(1, 120);
2441 let s = cursor + next() % span;
2442 if s >= n_lines {
2443 break;
2444 }
2445 let o = (next() % 5).min(n_lines - s);
2446 let nw = next() % 5;
2447 spans.push((s, o, nw));
2448 cursor = s + o + 1; // keep replaced spans disjoint + ascending
2449 }
2450 if spans.is_empty() {
2451 continue;
2452 }
2453 let delta: i64 = spans.iter().map(|&(_, o, n)| i64::from(n) - i64::from(o)).sum();
2454
2455 tree.shift(&spans);
2456 vec_shift_reference(&mut reference, &spans);
2457 n_lines = (n_lines as i64 + delta) as u32;
2458
2459 let got = tree.rows();
2460 let want: Vec<u32> = reference.iter().map(|(r, _)| *r).collect();
2461 assert_eq!(got, want, "trial {trial} step {step}: rows diverge for {spans:?}");
2462 let states_ok = tree
2463 .tree
2464 .items()
2465 .iter()
2466 .zip(&reference)
2467 .all(|(it, (_, s))| *it.state == **s);
2468 assert!(states_ok, "trial {trial} step {step}: a checkpoint state was mismapped");
2469 }
2470 }
2471 }
2472
2473 /// PERF CELL: one 1-line keystroke's checkpoint shift is independent of the
2474 /// checkpoint count. A flat-Vec walk would charge K (take + rebuild every
2475 /// commit and undo step); the windowed seam touches O(1). FLIP-VERIFY:
2476 /// force `shift` down the `shift_walk` fallback (change its dispatch to
2477 /// `if false`) and this trips — the meter reads ≈K → 2K instead of a flat 1.
2478 #[test]
2479 fn checkpoint_shift_is_checkpoint_count_independent() {
2480 let st = fresh_state();
2481 let meter = |k: u32| -> u64 {
2482 // K stride checkpoints; the edit (row 5, 1→1) sits far below the first
2483 // (row 255), so the windowed shift drops nothing and shifts nothing.
2484 let rows: Vec<u32> =
2485 (0..k).map(|i| (i + 1) * HIGHLIGHT_CHECKPOINT_STRIDE - 1).collect();
2486 let mut cps = Checkpoints::from_rows(&rows, &st);
2487 crate::perf::reset();
2488 cps.shift(&[(5, 1, 1)]);
2489 crate::perf::meter()
2490 };
2491 let (small, big) = (meter(1000), meter(2000));
2492 eprintln!("[perf_gate] checkpoint shift charge {small:>7} -> {big:>7}");
2493 assert!(
2494 big <= small + small / 4 + 256,
2495 "checkpoint shift charged {small} -> {big}: it walked every checkpoint, not the seam",
2496 );
2497 }
2498
2499 /// A collapsed mega-fold makes the widget report a visible range spanning
2500 /// the fold's hidden interior — the retention window must CAP its length,
2501 /// or a fold re-grows retention to O(document).
2502 #[test]
2503 fn window_length_is_capped() {
2504 let lines: Vec<String> = (0..200_000).map(|i| format!("kw {i}")).collect();
2505 let mut c = cache(200_000);
2506 c.set_window(0..150_000); // a viewport straddling a huge collapsed fold
2507 drive_all(&mut c, &lines);
2508 assert!(
2509 c.retained_span_rows() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize,
2510 "the window must be capped: {} rows retained",
2511 c.retained_span_rows()
2512 );
2513 }
2514
2515 #[test]
2516 fn in_window_commit_with_a_document_scale_span_stays_bounded() {
2517 // A scattered multi-caret transaction folds into ONE covering line span
2518 // (first caret .. last caret), so on_commit's in-window branch sees a
2519 // document-scale `new` even though the window is small. The dense splice
2520 // must stay bounded — splicing `vec![None; new]` would regrow `win` to
2521 // O(new), an O(document) per-keystroke allocation.
2522 let mut c = cache(200_000);
2523 c.set_window(100..140); // small window near the top; the first caret is in it
2524 assert!(c.window_len() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize);
2525 // The covering splice of an edit spanning rows 100..150_000 (top+bottom
2526 // carets, one char each → +150k covering lines, say).
2527 c.on_commit(100, 1, 150_000);
2528 assert!(
2529 c.window_len() <= HIGHLIGHT_MAX_WINDOW_ROWS as usize,
2530 "in-window covering splice regrew the window to {} rows",
2531 c.window_len()
2532 );
2533 // The dirty set and line count still track the (over-wide) splice, so
2534 // the covered rows are refilled correctly on the sweep.
2535 assert_eq!(c.line_count(), 200_000 + 150_000 - 1);
2536 }
2537
2538 // ------------------------------------------------------------------
2539 // Off-thread bulk tokenization: parallel sweep + viewport speculation.
2540 // All under the STATEFUL GRAMMAR_STR so a wrong guess (a cut inside a
2541 // multi-line string) produces genuinely different colors that the stitch
2542 // must repair - the whole point.
2543 // ------------------------------------------------------------------
2544
2545 fn engine_str() -> HighlightEngine {
2546 HighlightEngine::new(
2547 SyntaxDef::from_sublime_syntax(GRAMMAR_STR).unwrap(),
2548 TokenTheme::from_tm_theme(THEME).unwrap(),
2549 )
2550 }
2551
2552 fn snap(lines: &[String]) -> Snapshot {
2553 crate::buffer::Buffer::new(&lines.join("\n")).unwrap().snapshot()
2554 }
2555
2556 fn drive_all_snap(c: &mut HighlightCache, s: &Snapshot) {
2557 while c.pending().is_some() {
2558 c.tokenize_until(u32::MAX, HIGHLIGHT_MAX_LINES_PER_CALL, |r| s.line(r));
2559 }
2560 }
2561
2562 /// Simulate the app's coordinator: tokenize every segment Fresh (as the
2563 /// worker pool would, order-independently), then stitch left to right -
2564 /// re-running (with the early-stop `converge_against`) any segment whose
2565 /// Fresh guess mismatched the true prior end. Returns the verified chain
2566 /// and how many segments needed a re-run.
2567 fn parallel_verify(
2568 engine: &HighlightEngine,
2569 snapshot: &Snapshot,
2570 cuts: &[u32],
2571 spans_for: Option<Range<u32>>,
2572 ) -> (Vec<SegmentTokens>, usize) {
2573 let n = snapshot.line_count();
2574 let mut bounds = vec![0u32];
2575 bounds.extend(cuts.iter().copied().filter(|&c| c > 0 && c < n));
2576 bounds.sort_unstable();
2577 bounds.dedup();
2578 bounds.push(n);
2579 // Pass 1 - all Fresh (the parallel workers; order irrelevant).
2580 let segs: Vec<SegmentTokens> = bounds
2581 .windows(2)
2582 .map(|w| {
2583 tokenize_segment(engine, snapshot, w[0]..w[1], SegmentStart::Fresh, spans_for.clone(), None)
2584 })
2585 .collect();
2586 // Pass 2 - sequential stitch.
2587 let fresh = engine.fresh_boundary();
2588 let mut verified: Vec<SegmentTokens> = Vec::with_capacity(segs.len());
2589 let mut prev_end: Option<SegmentBoundary> = None;
2590 let mut reruns = 0;
2591 for (idx, seg) in segs.into_iter().enumerate() {
2592 let corrected = if idx == 0 {
2593 seg // Fresh at row 0 is the true start
2594 } else {
2595 let true_start = prev_end.clone().unwrap();
2596 if true_start == fresh {
2597 seg // the Fresh guess happened to be right
2598 } else {
2599 reruns += 1;
2600 let rows = seg.rows();
2601 tokenize_segment(
2602 engine,
2603 snapshot,
2604 rows,
2605 SegmentStart::After(true_start),
2606 spans_for.clone(),
2607 Some(&seg),
2608 )
2609 }
2610 };
2611 prev_end = Some(corrected.end_boundary().clone());
2612 verified.push(corrected);
2613 }
2614 (verified, reruns)
2615 }
2616
2617 /// THE correctness spine (property test): under random stateful documents
2618 /// and random segment cuts - including cuts deliberately inside multi-line
2619 /// strings - the parallel-verified + absorbed cache must equal a
2620 /// whole-document `Highlighter::highlight` on every row, and its checkpoint
2621 /// rows must match a sync-swept cache. Fails against any stitch that does
2622 /// not repair a wrong-guessed boundary.
2623 #[test]
2624 fn parallel_stitch_equals_the_whole_document_oracle() {
2625 let engine = engine_str();
2626 let mut state = 0x1234_5678_9ABC_DEF0_u64;
2627 let mut rng = move |bound: usize| {
2628 state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
2629 ((state >> 33) as usize) % bound.max(1)
2630 };
2631 for round in 0..24 {
2632 let n = 200 + rng(1_200);
2633 let lines: Vec<String> = (0..n)
2634 .map(|i| match rng(11) {
2635 0 => "\"".to_string(), // open a multi-line string
2636 1 => "text\" kw".to_string(), // close it, then a keyword
2637 2 => "\" and \" kw".to_string(),
2638 _ => format!("kw word {i}"),
2639 })
2640 .collect();
2641 let s = snap(&lines);
2642 let ln = s.line_count();
2643 // 1-6 random cuts, some likely inside string regions.
2644 let cuts: Vec<u32> = (0..1 + rng(6)).map(|_| rng(ln as usize) as u32).collect();
2645 let win_start = rng(ln as usize) as u32;
2646 let win = win_start..(win_start + 40).min(ln);
2647
2648 let (verified, _reruns) = parallel_verify(&engine, &s, &cuts, None);
2649 let mut c = cache_str(ln);
2650 c.set_window(win.clone());
2651 for seg in verified {
2652 c.absorb(seg, true);
2653 }
2654 assert_eq!(c.first_dirty(), None, "round {round}: verified sweep must clear all dirt");
2655 // Spans-less segments left window gaps - the sync refill (from the
2656 // absorbed checkpoints) fills them; then every window row is exact.
2657 drive_all_snap(&mut c, &s);
2658 let full = highlighter_str().highlight(&lines.join("\n"));
2659 for r in win.clone() {
2660 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "round {round} row {r}");
2661 }
2662 // Checkpoint ROWS must match a purely sync sweep (the absorb path
2663 // may not fabricate off-grid checkpoints the sync path lacks).
2664 let mut sync = cache_str(ln);
2665 sync.set_window(win.clone());
2666 drive_all(&mut sync, &lines);
2667 let got: Vec<u32> = c.ret.checkpoints.rows();
2668 let want: Vec<u32> = sync.ret.checkpoints.rows();
2669 assert_eq!(got, want, "round {round}: checkpoint rows diverge from a sync sweep");
2670 }
2671 }
2672
2673 /// A wrong-guessed boundary (a cut deep inside a block comment) repairs in
2674 /// O(distance to the comment's close), NOT O(segment): the re-run's
2675 /// early-stop splices the proven-identical tail, tokenizing only up to one
2676 /// stride past the closing line. (Uses the self-healing GRAMMAR_CMT — a
2677 /// symmetric-toggle string never re-converges, so it can't exercise the
2678 /// splice; that is the degenerate case tested separately.)
2679 #[test]
2680 fn wrong_guess_repair_stops_within_a_stride() {
2681 let engine = engine_cmt();
2682 // A comment opens at row 100 and closes at row 300; the rest is plain.
2683 // A cut at 1500 is far PAST the comment, so both the fresh guess and
2684 // the truth are in the ground state there — to force a genuine
2685 // mis-guess, cut at 200 (inside the comment).
2686 let mut lines: Vec<String> = (0..8_000).map(|i| format!("kw word {i}")).collect();
2687 lines[100] = "/*".to_string();
2688 lines[300] = "*/ kw".to_string();
2689 let s = snap(&lines);
2690 // The tail segment 200..8000, guessed Fresh (ground) — wrong, row 200
2691 // is inside the comment.
2692 let seg_rows = 200u32..8_000;
2693 let guessed = tokenize_segment(&engine, &s, seg_rows.clone(), SegmentStart::Fresh, None, None);
2694 let truth_prefix = tokenize_segment(&engine, &s, 0..200, SegmentStart::Fresh, None, None);
2695 let true_start = SegmentStart::After(truth_prefix.end_boundary().clone());
2696 let repaired = tokenize_segment(&engine, &s, seg_rows, true_start, None, Some(&guessed));
2697 // Converged: the tail was spliced, so far fewer than 7800 rows ran.
2698 // The comment closes at 300; convergence is detected at the first
2699 // stride checkpoint past it, so tokenized ≤ (300 − 200) + one stride.
2700 let bound = (300 - 200) + HIGHLIGHT_CHECKPOINT_STRIDE;
2701 assert!(
2702 repaired.tokenized_rows() <= bound,
2703 "repair tokenized {} rows (bound {bound}) — early-stop did not fire",
2704 repaired.tokenized_rows()
2705 );
2706 assert!(repaired.tokenized_rows() < 7_800, "a full re-run would tokenize the whole segment");
2707 // …and it is byte-identical to a full correct re-run.
2708 let full_rerun =
2709 tokenize_segment(&engine, &s, 200..8_000, SegmentStart::After(truth_prefix.end_boundary().clone()), None, None);
2710 assert!(repaired.end_boundary() == full_rerun.end_boundary(), "spliced tail must be correct");
2711 // End-to-end oracle around the close, where the guess was wrong.
2712 let (verified, reruns) = parallel_verify(&engine, &s, &[200], None);
2713 assert_eq!(reruns, 1, "the in-comment cut must trigger exactly one re-run");
2714 let mut c = cache_cmt(8_000);
2715 c.set_window(190..600);
2716 for v in verified {
2717 c.absorb(v, true);
2718 }
2719 drive_all_snap(&mut c, &s);
2720 let full = highlighter_cmt().highlight(&lines.join("\n"));
2721 for r in 190..600u32 {
2722 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2723 }
2724 }
2725
2726 /// A converging re-run whose `spans_for` DIFFERS from the old segment's
2727 /// window (the coordinator dispatched the re-run after the viewport moved)
2728 /// must stay internally consistent — the window is forced to the old
2729 /// segment's, so the spliced tail lines up. Were the moved `spans_for`
2730 /// honored instead, the splice would write misaligned spans as clean
2731 /// (viewport poison) or trip the window-equality assertion.
2732 #[test]
2733 fn converging_rerun_ignores_a_moved_spans_for() {
2734 let engine = engine_cmt();
2735 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw word {i}")).collect();
2736 lines[100] = "/*".to_string();
2737 lines[300] = "*/ kw".to_string();
2738 let s = snap(&lines);
2739 let seg_rows = 200u32..2_000;
2740 let old_window = Some(210u32..250); // the window when the guess was made
2741 let guessed =
2742 tokenize_segment(&engine, &s, seg_rows.clone(), SegmentStart::Fresh, old_window.clone(), None);
2743 let prefix = tokenize_segment(&engine, &s, 0..200, SegmentStart::Fresh, None, None);
2744 let after = || SegmentStart::After(prefix.end_boundary().clone());
2745 // Re-run with a MOVED window (1500..1540 — the viewport scrolled).
2746 let moved = tokenize_segment(&engine, &s, seg_rows.clone(), after(), Some(1_500..1_540), Some(&guessed));
2747 // …and a control re-run whose spans_for already matches the old window.
2748 let matched = tokenize_segment(&engine, &s, seg_rows, after(), old_window, Some(&guessed));
2749 // The moved re-run behaves as if it reused the old window: same tail,
2750 // same window range, same end — no panic, no misalignment.
2751 assert!(moved.end_boundary() == matched.end_boundary(), "same converged end");
2752 assert_eq!(moved.rows, matched.rows);
2753 assert_eq!(moved.win, matched.win, "window forced to the old segment's");
2754 assert_eq!(moved.win_spans.len(), moved.win.len(), "spans line up with the window");
2755 assert_eq!(moved.win_states.len(), moved.win.len());
2756 // And absorbing it colours the old window's rows correctly.
2757 let full = highlighter_cmt().highlight(&lines.join("\n"));
2758 let mut c = cache_cmt(4_000);
2759 c.set_window(210..250);
2760 c.absorb(prefix, true);
2761 c.absorb(moved, true);
2762 drive_all_snap(&mut c, &s);
2763 for r in 210..250u32 {
2764 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2765 }
2766 }
2767
2768 /// Degenerate honesty: a document that is one never-closed multi-line
2769 /// string makes every boundary mismatch (full sequential re-run) — the
2770 /// result is still byte-identical to the oracle.
2771 #[test]
2772 fn one_giant_string_falls_back_to_sequential_but_stays_correct() {
2773 let engine = engine_str();
2774 let mut lines: Vec<String> = (0..2_000).map(|i| format!("body {i}")).collect();
2775 lines[0] = "\"".to_string(); // opened, never closed
2776 let s = snap(&lines);
2777 let (verified, reruns) = parallel_verify(&engine, &s, &[400, 800, 1_200, 1_600], None);
2778 assert_eq!(reruns, 4, "every mid-string boundary mismatches");
2779 let mut c = cache_str(2_000);
2780 c.set_window(900..980);
2781 for v in verified {
2782 c.absorb(v, true);
2783 }
2784 drive_all_snap(&mut c, &s);
2785 let full = highlighter_str().highlight(&lines.join("\n"));
2786 for r in 900..980u32 {
2787 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2788 }
2789 }
2790
2791 /// Verified absorb clears the segment's rows from the frontier and the
2792 /// spans it carries (spans_for) render immediately - no sync walk needed.
2793 #[test]
2794 fn verified_absorb_clears_dirt_and_shows_spans() {
2795 let engine = engine_str();
2796 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2797 let s = snap(&lines);
2798 let win = 900u32..940;
2799 // One verified segment covering the viewport, carrying its spans.
2800 let seg = tokenize_segment(&engine, &s, 0..2_000, SegmentStart::Fresh, Some(win.clone()), None);
2801 let mut c = cache_str(2_000);
2802 c.set_window(win.clone());
2803 c.absorb(seg, true);
2804 assert_eq!(c.first_dirty(), None, "verified absorb clears the whole frontier");
2805 // The requested spans render immediately — no sync walk. (The window
2806 // pads ±SLACK beyond `spans_for`, so pending() may still report a
2807 // slack gap; that is the sync refill's cheap job, tested elsewhere.)
2808 let full = highlighter_str().highlight(&lines.join("\n"));
2809 for r in win {
2810 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2811 }
2812 }
2813
2814 /// Speculative absorb (a GUESSED fresh start) shows spans in the window
2815 /// immediately, but plants NO checkpoints (unverified states would poison
2816 /// warm-ups) and leaves the rows dirty (the frontier re-verifies them).
2817 #[test]
2818 fn speculative_absorb_shows_spans_without_checkpoints_or_clearing_dirt() {
2819 let engine = engine_str();
2820 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2821 let s = snap(&lines);
2822 let win = 900u32..940;
2823 // A viewport-first speculative segment: back off 128 rows, Fresh guess.
2824 let seg = tokenize_segment(&engine, &s, 772..940, SegmentStart::Fresh, Some(win.clone()), None);
2825 let mut c = cache_str(2_000);
2826 c.set_window(win.clone());
2827 c.absorb(seg, false);
2828 // Spans are visible now (the guess is right here - no multi-line state).
2829 let full = highlighter_str().highlight(&lines.join("\n"));
2830 for r in win.clone() {
2831 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "speculative row {r}");
2832 }
2833 // But nothing is verified: the frontier is untouched and no checkpoint
2834 // was planted (retained_state_rows counts window states + checkpoints;
2835 // the window states are the harmless per-line probes).
2836 assert_eq!(c.first_dirty(), Some(0), "speculation must not clear dirt");
2837 assert!(c.ret.checkpoints.is_empty(), "speculation must not plant checkpoints");
2838 }
2839
2840 /// End to end: speculative colors first, then the frontier's dirty walk
2841 /// reaches the window and CONVERGES in O(1) against the correct
2842 /// speculative state (the guess was right) - the whole window consumed by
2843 /// tokenizing a single row.
2844 #[test]
2845 fn speculative_then_frontier_converges_o1_when_the_guess_was_right() {
2846 let engine = engine_str();
2847 let lines: Vec<String> = (0..2_000).map(|i| format!("kw word {i}")).collect();
2848 let s = snap(&lines);
2849 let win = 900u32..940;
2850 let seg = tokenize_segment(&engine, &s, 772..940, SegmentStart::Fresh, Some(win.clone()), None);
2851 let mut c = cache_str(2_000);
2852 c.set_window(win.clone());
2853 c.absorb(seg, false);
2854 // Now drive the frontier from row 0 (as the idle sweep would). When it
2855 // reaches the window, each row's freshly-tokenized state matches the
2856 // stored speculative state, so it converges immediately and the whole
2857 // window's spans are proven correct.
2858 drive_all_snap(&mut c, &s);
2859 assert_eq!(c.first_dirty(), None);
2860 let full = highlighter_str().highlight(&lines.join("\n"));
2861 for r in win {
2862 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r}");
2863 }
2864 }
2865
2866 /// The poison guard: a WRONG speculative span (guessed fresh inside a
2867 /// multi-line comment) must never survive as clean when a verified
2868 /// spans-less segment clears its dirt. Verified absorb evicts it; the sync
2869 /// refill (from the correct checkpoints) repaints it right.
2870 #[test]
2871 fn verified_absorb_evicts_wrong_speculative_spans_no_poison() {
2872 let engine = engine_cmt();
2873 let mut lines: Vec<String> = (0..4_000).map(|i| format!("kw word {i}")).collect();
2874 lines[100] = "/*".to_string(); // a comment that stays open…
2875 lines[3_000] = "*/ kw".to_string(); // …until here
2876 let s = snap(&lines);
2877 let win = 1_500u32..1_540; // deep inside the comment
2878 let full = highlighter_cmt().highlight(&lines.join("\n"));
2879 let mut c = cache_cmt(4_000);
2880 c.set_window(win.clone());
2881 // Speculate from a FRESH (ground) start — WRONG here, the truth is
2882 // in-comment.
2883 let spec = tokenize_segment(&engine, &s, 1_400..1_540, SegmentStart::Fresh, Some(win.clone()), None);
2884 c.absorb(spec, false);
2885 assert_ne!(
2886 c.line_spans(1_520),
2887 Some(full[1_520].as_slice()),
2888 "the speculative guess must actually be wrong here (else the test proves nothing)"
2889 );
2890 // The correct verified sweep (one segment, Fresh at row 0 = true).
2891 let (verified, _) = parallel_verify(&engine, &s, &[], None);
2892 for v in verified {
2893 c.absorb(v, true);
2894 }
2895 // The wrong speculative span is GONE — evicted, not left clean.
2896 assert_eq!(c.line_spans(1_520), None, "wrong speculative spans must be evicted, never trusted");
2897 // …and the sync refill repaints the window correctly.
2898 drive_all_snap(&mut c, &s);
2899 for r in win {
2900 assert_eq!(c.line_spans(r), Some(full[r as usize].as_slice()), "row {r} corrected");
2901 }
2902 }
2903
2904 #[test]
2905 fn dirty_ranges_shift_merge_unit() {
2906 let mut d = DirtyRanges::default();
2907 d.insert(5);
2908 d.insert(7);
2909 d.insert(6); // bridges 5..6 and 7..8 into one run
2910 assert_eq!(d.0, vec![5..8]);
2911 d.insert(4); // extends left
2912 assert_eq!(d.0, vec![4..8]);
2913 // Splice via a single covering span: rows [5,7) became 3 rows → tail
2914 // shifts by +1 (apply_splices reproduces the classic commit splice).
2915 d.apply_splices(&[(5, 2, 3)]);
2916 assert_eq!(d.0, vec![4..9], "clip + shift + new-block merge into one run");
2917 // A pure delete ahead of the run shifts it left.
2918 d.apply_splices(&[(0, 2, 0)]);
2919 assert_eq!(d.0, vec![2..7]);
2920 // Front consumption.
2921 assert_eq!(d.first(), Some(2));
2922 d.remove_first(2);
2923 assert_eq!(d.0, vec![3..7]);
2924 }
2925}