highlight: Flatten include search for speed

3a9268c71678a925c19feff3d619c54bd5b1c1d9
Compile each pattern set into a flattened declaration-order `RegSet` after
grammar compilation. This keeps TextMate include semantics while
removing recursive include traversal from the per-token hot path.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 161db5b6
crates/diff/Cargo.toml +4 -0
15 15
16 16
[[bench]]
17 17
name = "render"
18 18
harness = false
19 19
20 +
[[bench]]
21 +
name = "highlight"
22 +
harness = false
23 +
20 24
[lints]
21 25
workspace = true
crates/diff/benches/highlight.rs added +310 -0
1 +
//! Highlight pipeline benchmarks for `rustik-diff`.
2 +
//!
3 +
//! The benchmark mirrors the interactive pager's slow path more closely than
4 +
//! the render benchmark: it times built-in grammar/theme setup, full-context
5 +
//! patch decode, source extraction, visible request collection, and the final
6 +
//! highlight/apply/render pass.
7 +
//!
8 +
//! Run with `cargo bench -p rustik-diff --bench highlight`.
9 +
10 +
use std::collections::BTreeMap;
11 +
use std::hint::black_box;
12 +
use std::io::{self, Write as _};
13 +
use std::path::PathBuf;
14 +
use std::time::{Duration, Instant};
15 +
16 +
use rustik_diff::{
17 +
    BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffSide, DiffViewer,
18 +
    HighlightRequest, HighlightSource,
19 +
};
20 +
use rustik_highlight as syntax;
21 +
use rustik_tui::{Buffer, Color, Constraint, Label, Rect, Scroll, Style, Table, TableOptions};
22 +
23 +
/// Fixed terminal-sized render area.
24 +
const AREA: Rect = Rect::new(0, 0, 120, 40);
25 +
/// Default source rows generated for the full-context file.
26 +
const DEFAULT_LINES: usize = 100_000;
27 +
/// Default number of independent timed runs.
28 +
const DEFAULT_RUNS: usize = 3;
29 +
/// Rows per hunk in the sparse viewport document.
30 +
const SPARSE_HUNK_LINES: usize = 64;
31 +
/// Theme name used by the interactive pager.
32 +
const THEME_NAME: &str = "rustik-catppuccin-mocha";
33 +
/// Built-in syntax theme JSON used by the interactive pager.
34 +
const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json");
35 +
/// Low-emphasis report text color.
36 +
const REPORT_DIM: Color = Color::Fixed(244);
37 +
/// Widest expected duration value used to keep report rows aligned.
38 +
const DURATION_FORMAT: &str = "000000.0 ms";
39 +
40 +
/// Runs the benchmark.
41 +
fn main() {
42 +
    let args = Args::parse();
43 +
    let sparse_patch = synthetic_diff("src/slow.rs", args.lines, SPARSE_HUNK_LINES);
44 +
    let full_patch = synthetic_diff("src/slow.rs", args.lines, args.lines);
45 +
    let sparse_document = decode_patch(&sparse_patch);
46 +
    let widths = ReportWidths::new();
47 +
    let mut totals = StageDurations::default();
48 +
    let mut checksum = 0usize;
49 +
50 +
    for _ in 0..args.runs {
51 +
        let report = run_once(&sparse_document, &full_patch);
52 +
        totals += report.stages;
53 +
        checksum ^= report.checksum;
54 +
    }
55 +
    let stats = totals.div(args.runs);
56 +
57 +
    report_stage("assets", stats.assets, widths);
58 +
    report_stage("context-decode", stats.context_decode, widths);
59 +
    report_stage("source-build", stats.source_build, widths);
60 +
    report_stage("requests", stats.requests, widths);
61 +
    report_stage("land", stats.land, widths);
62 +
    io::stdout().flush().ok();
63 +
64 +
    black_box(checksum);
65 +
}
66 +
67 +
/// Benchmark command-line arguments.
68 +
#[derive(Clone, Copy, Debug)]
69 +
struct Args {
70 +
    /// Source rows generated for the full-context file.
71 +
    lines: usize,
72 +
    /// Number of independent timed runs.
73 +
    runs: usize,
74 +
}
75 +
76 +
impl Args {
77 +
    /// Parses benchmark arguments from the process environment.
78 +
    fn parse() -> Self {
79 +
        let mut parsed = Self {
80 +
            lines: DEFAULT_LINES,
81 +
            runs: DEFAULT_RUNS,
82 +
        };
83 +
        let mut args = std::env::args().skip(1);
84 +
85 +
        while let Some(arg) = args.next() {
86 +
            match arg.as_str() {
87 +
                "--lines" => parsed.lines = next_usize(&mut args, parsed.lines),
88 +
                "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1),
89 +
                "--help" | "-h" => {
90 +
                    println!(
91 +
                        "usage: cargo bench -p rustik-diff --bench highlight -- [--lines N] [--runs N]"
92 +
                    );
93 +
                    std::process::exit(0);
94 +
                }
95 +
                _ => {}
96 +
            }
97 +
        }
98 +
        parsed
99 +
    }
100 +
}
101 +
102 +
/// Stage timings from one benchmark run.
103 +
#[derive(Clone, Copy, Debug, Default)]
104 +
struct StageDurations {
105 +
    /// Built-in theme and grammar setup.
106 +
    assets: Duration,
107 +
    /// Full-context unified-diff decode.
108 +
    context_decode: Duration,
109 +
    /// Full-file source extraction from decoded diff data.
110 +
    source_build: Duration,
111 +
    /// Visible highlight request collection.
112 +
    requests: Duration,
113 +
    /// Syntax highlight, cache apply, and highlighted render.
114 +
    land: Duration,
115 +
}
116 +
117 +
impl StageDurations {
118 +
    /// Returns average stage timings over `count` runs.
119 +
    fn div(self, count: usize) -> Self {
120 +
        let count = count.max(1) as u32;
121 +
122 +
        Self {
123 +
            assets: self.assets / count,
124 +
            context_decode: self.context_decode / count,
125 +
            source_build: self.source_build / count,
126 +
            requests: self.requests / count,
127 +
            land: self.land / count,
128 +
        }
129 +
    }
130 +
}
131 +
132 +
impl std::ops::AddAssign for StageDurations {
133 +
    fn add_assign(&mut self, rhs: Self) {
134 +
        self.assets += rhs.assets;
135 +
        self.context_decode += rhs.context_decode;
136 +
        self.source_build += rhs.source_build;
137 +
        self.requests += rhs.requests;
138 +
        self.land += rhs.land;
139 +
    }
140 +
}
141 +
142 +
/// Result from one benchmark run.
143 +
#[derive(Clone, Copy, Debug)]
144 +
struct BenchReport {
145 +
    /// Timed stage durations.
146 +
    stages: StageDurations,
147 +
    /// Deterministic checksum of the produced work.
148 +
    checksum: usize,
149 +
}
150 +
151 +
/// Report column widths.
152 +
#[derive(Clone, Copy, Debug)]
153 +
struct ReportWidths {
154 +
    /// Width reserved for stage names.
155 +
    stage: usize,
156 +
    /// Width reserved for formatted durations.
157 +
    duration: usize,
158 +
}
159 +
160 +
impl ReportWidths {
161 +
    /// Computes report column widths.
162 +
    fn new() -> Self {
163 +
        Self {
164 +
            stage: "context-decode".len(),
165 +
            duration: DURATION_FORMAT.len(),
166 +
        }
167 +
    }
168 +
}
169 +
170 +
/// Parses the next argument as a `usize`.
171 +
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
172 +
    args.next()
173 +
        .and_then(|value| value.parse().ok())
174 +
        .unwrap_or(fallback)
175 +
}
176 +
177 +
/// Runs one timed highlight pipeline pass.
178 +
fn run_once(sparse_document: &DiffDocument, full_patch: &str) -> BenchReport {
179 +
    let mut stages = StageDurations::default();
180 +
    let mut checksum = 0usize;
181 +
182 +
    let start = Instant::now();
183 +
    let mut highlighter = build_highlighter();
184 +
    stages.assets = start.elapsed();
185 +
186 +
    let start = Instant::now();
187 +
    let full_document = decode_patch(full_patch);
188 +
    stages.context_decode = start.elapsed();
189 +
190 +
    let start = Instant::now();
191 +
    let full_sources = full_sources(&full_document);
192 +
    stages.source_build = start.elapsed();
193 +
194 +
    let mut viewer = DiffViewer::new(sparse_document.clone(), DiffOptions::default());
195 +
    let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows;
196 +
    viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA);
197 +
198 +
    let start = Instant::now();
199 +
    let requests = viewer.highlight_requests(AREA);
200 +
    stages.requests = start.elapsed();
201 +
202 +
    let start = Instant::now();
203 +
    let requests = full_source_requests(requests, &full_sources);
204 +
    let results = highlighter.highlight_requests(requests);
205 +
206 +
    checksum ^= results.len();
207 +
    viewer.apply_highlights(results);
208 +
209 +
    let mut buffer = Buffer::empty(AREA);
210 +
    viewer.render(AREA, &mut buffer);
211 +
    checksum ^= buffer.area().rows ^ buffer.area().cols;
212 +
    stages.land = start.elapsed();
213 +
214 +
    BenchReport { stages, checksum }
215 +
}
216 +
217 +
/// Builds a highlighter for the generated Rust source file.
218 +
fn build_highlighter() -> BuiltinHighlighter {
219 +
    let raw_theme = match THEME.parse::<syntax::RawTheme>() {
220 +
        Ok(theme) => theme,
221 +
        Err(error) => {
222 +
            eprintln!("failed to parse benchmark theme: {error:?}");
223 +
            std::process::exit(1);
224 +
        }
225 +
    };
226 +
    let mut registry = syntax::Registry::default();
227 +
228 +
    registry.add_theme(syntax::Theme::compile(&raw_theme));
229 +
    let mut raw = match syntax::syntaxes::RUST.parse::<syntax::RawGrammar>() {
230 +
        Ok(raw) => raw,
231 +
        Err(error) => {
232 +
            eprintln!("failed to parse benchmark grammar: {error:?}");
233 +
            std::process::exit(1);
234 +
        }
235 +
    };
236 +
    if !raw
237 +
        .file_types
238 +
        .iter()
239 +
        .any(|existing| existing.eq_ignore_ascii_case("rs"))
240 +
    {
241 +
        raw.file_types.push("rs".to_owned());
242 +
    }
243 +
    let grammar = match syntax::Grammar::compile_with(&raw, &[]) {
244 +
        Ok(grammar) => grammar,
245 +
        Err(error) => {
246 +
            eprintln!("failed to compile benchmark grammar: {error:?}");
247 +
            std::process::exit(1);
248 +
        }
249 +
    };
250 +
    registry.add_grammar(grammar);
251 +
    BuiltinHighlighter::new(registry, THEME_NAME)
252 +
}
253 +
254 +
/// Decodes a synthetic patch or exits with a benchmark setup error.
255 +
fn decode_patch(patch: &str) -> DiffDocument {
256 +
    match DiffDocument::decode_str(patch) {
257 +
        Ok(document) => document,
258 +
        Err(error) => {
259 +
            eprintln!("failed to decode generated benchmark diff: {error}");
260 +
            std::process::exit(1);
261 +
        }
262 +
    }
263 +
}
264 +
265 +
/// Extracts full-file sources from a full-context diff document.
266 +
fn full_sources(document: &DiffDocument) -> BTreeMap<(PathBuf, DiffSide), HighlightSource> {
267 +
    let mut sources = BTreeMap::new();
268 +
269 +
    for file in &document.files {
270 +
        for side in [DiffSide::Old, DiffSide::New] {
271 +
            let Some(path) = file.source_path(side) else {
272 +
                continue;
273 +
            };
274 +
            let Some(source) = file.highlight_source(side) else {
275 +
                continue;
276 +
            };
277 +
            sources.insert((path, side), source);
278 +
        }
279 +
    }
280 +
    sources
281 +
}
282 +
283 +
/// Replaces sparse hunk sources with full-file sources where line text matches.
284 +
fn full_source_requests(
285 +
    requests: Vec<HighlightRequest>,
286 +
    sources: &BTreeMap<(PathBuf, DiffSide), HighlightSource>,
287 +
) -> Vec<HighlightRequest> {
288 +
    requests
289 +
        .into_iter()
290 +
        .map(|mut request| {
291 +
            let Some(path) = request.path.as_ref() else {
292 +
                return request;
293 +
            };
294 +
            let key = (path.clone(), request.key.side);
295 +
            if let Some(source) = sources.get(&key)
296 +
                && source.line(request.key.source_line)
297 +
                    == request.source.line(request.key.source_line)
298 +
            {
299 +
                request.source = source.clone();
300 +
            }
301 +
            request
302 +
        })
303 +
        .collect()
304 +
}
305 +
306 +
/// Creates a deterministic Git-style unified diff for one file.
307 +
fn synthetic_diff(path: &str, lines: usize, hunk_lines: usize) -> String {
308 +
    let mut diff = String::new();
309 +
310 +
    diff.push_str(&format!("
{path}\n")); +0 -0
crates/diff/benches/render.rs +97 -23
7 7
use std::io::{self, Write as _};
8 8
use std::str::FromStr;
9 9
use std::time::{Duration, Instant};
10 10
11 11
use rustik_diff::{
12 -
    Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, HighlightRequest, HighlightResult,
12 +
    BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer,
13 +
    HighlightRequest, HighlightResult,
13 14
};
15 +
use rustik_highlight as syntax;
14 16
use rustik_tui::{
15 17
    Buffer, Color, Constraint, Label, Line, Rect, Scroll, Style, Table, TableOptions,
16 18
};
17 19
18 20
/// Fixed terminal-sized render area.
23 25
const WIDE_AREA: Rect = Rect::new(0, 0, 180, 50);
24 26
/// Tiny terminal area used to stress minimum-width rendering.
25 27
const TINY_AREA: Rect = Rect::new(0, 0, 44, 12);
26 28
/// Default frame count.
27 29
const DEFAULT_FRAMES: usize = 80;
30 +
/// Default frame count for expensive real syntax-highlight landing runs.
31 +
const DEFAULT_HIGHLIGHT_FRAMES: usize = 3;
28 32
/// Default frame count for each workload in the full suite.
29 33
const DEFAULT_SUITE_FRAMES: usize = DEFAULT_FRAMES;
30 34
/// Default number of independent timed runs per workload.
31 35
const DEFAULT_RUNS: usize = 3;
32 36
/// Default number of file sections in the generated diff.
37 41
const SAMPLE_ROWS: usize = 5;
38 42
/// One column sample stride for the checksum.
39 43
const SAMPLE_COLS: usize = 7;
40 44
/// Low-emphasis report text color.
41 45
const REPORT_DIM: Color = Color::Fixed(244);
46 +
/// Theme name used by the interactive pager.
47 +
const THEME_NAME: &str = "rustik-catppuccin-mocha";
48 +
/// Built-in syntax theme JSON used by the interactive pager.
49 +
const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json");
42 50
43 51
/// Runs the benchmark.
44 52
fn main() {
45 53
    let args = Args::parse();
46 54
    let workloads = args.workload.expanded();
126 134
127 135
impl FrameCount {
128 136
    /// Returns the concrete frame count for one workload.
129 137
    const fn for_workload(self, requested: Workload) -> usize {
130 138
        match (self, requested) {
139 +
            (Self::Default, Workload::Highlight) => DEFAULT_HIGHLIGHT_FRAMES,
131 140
            (Self::Default, Workload::All) => DEFAULT_SUITE_FRAMES,
132 141
            (Self::Default, _) => DEFAULT_FRAMES,
133 142
            (Self::Explicit(frames), _) => frames,
134 143
        }
135 144
    }
146 155
    Resize,
147 156
    /// Scrolling offsets concentrated around file boundaries.
148 157
    Sticky,
149 158
    /// Focus and collapse workload across many files.
150 159
    Collapse,
151 -
    /// Visible highlight request and row-refresh workload.
160 +
    /// Visible syntax-highlight landing workload.
152 161
    Highlight,
153 162
    /// Visible highlight request scheduling without drawing rows.
154 163
    HighlightRequests,
155 164
    /// Steady-state render of word-diff overlays on a warm highlight cache.
156 165
    WordDiff,
201 210
            Self::LongLines => "long-lines",
202 211
            Self::All => "all",
203 212
        }
204 213
    }
205 214
206 -
    /// Returns the rate unit measured by the workload.
207 -
    const fn rate_unit(self) -> &'static str {
215 +
    /// Returns the report unit measured by the workload.
216 +
    const fn metric_unit(self) -> &'static str {
208 217
        match self {
209 218
            Self::HighlightRequests => "tps",
219 +
            Self::Highlight => "ms/land",
210 220
            Self::WarmScroll
211 221
            | Self::Session
212 222
            | Self::Resize
213 223
            | Self::Sticky
214 224
            | Self::Collapse
215 -
            | Self::Highlight
216 225
            | Self::WordDiff
217 226
            | Self::ManyFiles
218 227
            | Self::HugeFile
219 228
            | Self::LongLines
220 229
            | Self::All => "fps",
221 230
        }
222 231
    }
223 232
233 +
    /// Converts an elapsed workload run into the reported metric.
234 +
    fn metric_value(self, elapsed: Duration, frames: usize) -> f64 {
235 +
        let frames = frames.max(1);
236 +
        match self {
237 +
            Self::Highlight => elapsed.as_secs_f64() * 1_000.0 / frames as f64,
238 +
            _ => frames as f64 / elapsed.as_secs_f64(),
239 +
        }
240 +
    }
241 +
224 242
    /// Returns the synthetic document shape for the workload.
225 243
    fn document_shape(self, args: Args) -> DiffShape {
226 244
        match self {
227 245
            Self::ManyFiles => DiffShape {
228 246
                files: args.files.max(1_024),
240 258
                files: args.files,
241 259
                lines: args.lines,
242 260
                hunk_lines: 64,
243 261
                profile: LineProfile::LongUnicode,
244 262
            },
263 +
            Self::Highlight => {
264 +
                let lines = args.lines.max(16_384);
265 +
                DiffShape {
266 +
                    files: 1,
267 +
                    lines,
268 +
                    hunk_lines: lines,
269 +
                    profile: LineProfile::Normal,
270 +
                }
271 +
            }
245 272
            Self::Sticky | Self::Collapse => DiffShape {
246 273
                files: args.files.max(256),
247 274
                lines: 32,
248 275
                hunk_lines: 16,
249 276
                profile: LineProfile::Normal,
250 277
            },
251 278
            Self::Session
252 279
            | Self::Resize
253 -
            | Self::Highlight
254 280
            | Self::HighlightRequests
255 281
            | Self::WordDiff
256 282
            | Self::WarmScroll
257 283
            | Self::All => DiffShape {
258 284
                files: args.files,
313 339
/// Result from one workload run.
314 340
#[derive(Clone, Copy, Debug)]
315 341
struct BenchReport {
316 342
    /// Workload that produced the report.
317 343
    workload: Workload,
318 -
    /// Workload-rate statistics across independent runs.
319 -
    rate: RepeatStats,
344 +
    /// Workload metric statistics across independent runs.
345 +
    metric: RepeatStats,
320 346
    /// Combined deterministic render checksum across independent runs.
321 347
    checksum: usize,
322 348
}
323 349
324 350
/// Summary statistics for repeated benchmark runs.
325 351
#[derive(Clone, Copy, Debug)]
326 352
struct RepeatStats {
327 -
    /// Average workload iterations per second.
353 +
    /// Average reported workload value.
328 354
    avg: f64,
329 -
    /// Workload-rate standard deviation.
355 +
    /// Reported workload value standard deviation.
330 356
    stddev: f64,
331 357
}
332 358
333 359
/// Report column widths derived before workloads run.
334 360
#[derive(Clone, Copy, Debug)]
335 361
struct ReportWidths {
336 362
    /// Widest selected workload name.
337 363
    workload: usize,
338 -
    /// Width reserved for formatted workload rates.
339 -
    rate: usize,
364 +
    /// Width reserved for formatted workload metrics.
365 +
    metric: usize,
340 366
}
341 367
342 -
/// Widest expected workload-rate value used to keep streaming rows aligned.
343 -
const RATE_FORMAT: &str = "000000.0";
368 +
/// Widest expected workload-metric value used to keep streaming rows aligned.
369 +
const METRIC_FORMAT: &str = "000000.0";
344 370
345 371
/// Parses the next argument as a `usize`.
346 372
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
347 373
    args.next()
348 374
        .and_then(|value| value.parse().ok())
356 382
        .unwrap_or(fallback)
357 383
}
358 384
359 385
/// Runs one named benchmark workload.
360 386
fn run_workload(workload: Workload, args: Args) -> BenchReport {
361 -
    let frames = args.frames.for_workload(args.workload);
387 +
    let frames = args.frames.for_workload(workload);
362 388
    let shape = workload.document_shape(args);
363 389
    let input = synthetic_diff(shape);
364 390
    let document = match DiffDocument::decode_str(&input) {
365 391
        Ok(document) => document,
366 392
        Err(error) => {
371 397
    let rows = rustik_tui::Widget::size(
372 398
        &DiffViewer::new(document.clone(), DiffOptions::default()),
373 399
        Constraint::UNBOUNDED,
374 400
    )
375 401
    .rows;
376 -
    let mut rates = Vec::with_capacity(args.runs);
402 +
    let mut metrics = Vec::with_capacity(args.runs);
377 403
    let mut checksum = rows;
378 404
379 405
    for run in 0..args.runs {
380 406
        let (run_elapsed, run_checksum) = run_once(workload, document.clone(), frames);
381 -
        rates.push(frames as f64 / run_elapsed.as_secs_f64());
407 +
        metrics.push(workload.metric_value(run_elapsed, frames));
382 408
        checksum ^= run_checksum.rotate_left((run % usize::BITS as usize) as u32);
383 409
    }
384 410
385 411
    BenchReport {
386 412
        workload,
387 -
        rate: RepeatStats::from_values(&rates),
413 +
        metric: RepeatStats::from_values(&metrics),
388 414
        checksum,
389 415
    }
390 416
}
391 417
392 418
/// Runs one independent timed pass for a workload.
514 540
        }
515 541
        AREA
516 542
    })
517 543
}
518 544
519 -
/// Renders while applying synthetic highlight results for visible rows.
545 +
/// Renders until visible rows have real syntax highlights applied.
520 546
fn run_highlight(document: DiffDocument, frames: usize) -> (Duration, usize) {
521 -
    run_scripted(document, frames, |viewer, frame| {
547 +
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
548 +
    let mut buffer = Buffer::empty(AREA);
549 +
    let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows;
550 +
    viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA);
551 +
    let start = Instant::now();
552 +
    let raw_theme = match THEME.parse::<syntax::RawTheme>() {
553 +
        Ok(theme) => theme,
554 +
        Err(error) => {
555 +
            eprintln!("failed to parse benchmark theme: {error:?}");
556 +
            std::process::exit(1);
557 +
        }
558 +
    };
559 +
    let mut raw = match syntax::syntaxes::RUST.parse::<syntax::RawGrammar>() {
560 +
        Ok(raw) => raw,
561 +
        Err(error) => {
562 +
            eprintln!("failed to parse benchmark grammar: {error:?}");
563 +
            std::process::exit(1);
564 +
        }
565 +
    };
566 +
    if !raw
567 +
        .file_types
568 +
        .iter()
569 +
        .any(|existing| existing.eq_ignore_ascii_case("rs"))
570 +
    {
571 +
        raw.file_types.push("rs".to_owned());
572 +
    }
573 +
    let rust_grammar = match syntax::Grammar::compile_with(&raw, &[]) {
574 +
        Ok(grammar) => grammar,
575 +
        Err(error) => {
576 +
            eprintln!("failed to compile benchmark grammar: {error:?}");
577 +
            std::process::exit(1);
578 +
        }
579 +
    };
580 +
    let mut registry = syntax::Registry::default();
581 +
    registry.add_theme(syntax::Theme::compile(&raw_theme));
582 +
    registry.add_grammar(rust_grammar);
583 +
    let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME);
584 +
    let mut checksum = 0usize;
585 +
586 +
    for frame in 0..frames {
587 +
        buffer.clear();
588 +
        viewer.render(AREA, &mut buffer);
589 +
        checksum ^= sample_buffer(&buffer, frame);
522 590
        let requests = viewer.highlight_requests(AREA);
523 -
        viewer.apply_highlights(requests.into_iter().take(AREA.rows).map(highlight_result));
591 +
        let results = highlighter.highlight_requests(requests);
592 +
        viewer.apply_highlights(results);
593 +
        buffer.clear();
594 +
        viewer.render(AREA, &mut buffer);
595 +
        checksum ^= sample_buffer(&buffer, frame.wrapping_add(frames));
524 596
        viewer.apply(
525 597
            DiffAction::Scroll(Scroll::Lines((frame % 5 + 1) as isize)),
526 598
            AREA,
527 599
        );
528 -
        AREA
529 -
    })
600 +
        buffer.reset_dirty();
601 +
    }
602 +
603 +
    (start.elapsed(), checksum)
530 604
}
531 605
532 606
/// Renders cached word-diff overlays with a warm highlight cache.
533 607
///
534 608
/// Pre-applies synthetic highlight results for the rows the workload will
src/file_{file:04}.rs\n" +0 -0
crates/highlight/src/grammar/pattern.rs +105 -63
87 87
/// Compiled patterns at one nesting level plus their combined search regex.
88 88
#[derive(Debug)]
89 89
pub(super) struct PatternSet {
90 90
    /// Patterns in declaration order.
91 91
    pub(super) patterns: Vec<Pattern>,
92 -
    /// Included pattern sets searched after this set's local patterns.
93 -
    includes: Vec<PatternSetId>,
94 -
    /// Combined RegSet covering each pattern's match or begin source.
92 +
    /// Ordered local patterns and includes declared in this set.
93 +
    entries: Vec<PatternEntry>,
94 +
    /// Pattern locations in the flattened regex search set.
95 +
    matches: Vec<RuleLocation>,
96 +
    /// Combined RegSet covering flattened pattern match or begin sources.
95 97
    regexes: Option<RegSet>,
96 98
}
97 99
100 +
/// Ordered search entry inside one pattern set.
101 +
#[derive(Clone, Copy, Debug)]
102 +
enum PatternEntry {
103 +
    /// Local pattern index inside the set.
104 +
    Pattern(usize),
105 +
    /// Included pattern set searched at this point.
106 +
    Include(PatternSetId),
107 +
}
108 +
98 109
/// Compiled injection rule searched against matching scope stacks.
99 110
#[derive(Debug)]
100 111
pub(super) struct Injection {
101 112
    /// Selector that decides when this injection applies.
102 113
    pub(super) selector: ScopeSelector,
466 477
    pub(super) fn find_next(
467 478
        self,
468 479
        search: &mut PatternSearch<'_, '_, '_>,
469 480
        pos: usize,
470 481
    ) -> Option<Match> {
471 -
        let mut active = Vec::new();
472 -
        self.find_next_inner(search, pos, &mut active)
473 -
    }
474 -
475 -
    /// Finds the next pattern match while carrying the active include stack.
476 -
    fn find_next_inner(
477 -
        self,
478 -
        search: &mut PatternSearch<'_, '_, '_>,
479 -
        pos: usize,
480 -
        active: &mut Vec<PatternSetId>,
481 -
    ) -> Option<Match> {
482 -
        if active.contains(&self) || active.len() > MAX_INCLUDE_DEPTH {
483 -
            return None;
484 -
        }
485 -
        active.push(self);
486 -
        let found = search
482 +
        search
487 483
            .sets
488 484
            .get(self.index())
489 -
            .and_then(|set| set.find_next_inner(search, pos, active));
490 -
        active.pop();
491 -
        found
485 +
            .and_then(|set| set.find_next(search, pos))
492 486
    }
493 487
}
494 488
495 489
impl PatternSet {
496 490
    /// Creates an empty pattern set.
497 491
    pub(super) fn empty() -> Self {
498 492
        Self {
499 493
            patterns: Vec::new(),
500 -
            includes: Vec::new(),
494 +
            entries: Vec::new(),
495 +
            matches: Vec::new(),
501 496
            regexes: None,
502 497
        }
503 498
    }
504 499
505 -
    /// Builds a pattern set and its combined regex search set.
506 -
    fn new(patterns: Vec<Pattern>, includes: Vec<PatternSetId>) -> Self {
507 -
        let sources: Vec<&str> = patterns.iter().map(Pattern::search_source).collect();
508 -
        let regexes = (!sources.is_empty())
509 -
            .then(|| RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS).ok())
510 -
            .flatten();
511 -
500 +
    /// Builds a pattern set from local patterns and declaration-order search entries.
501 +
    fn new(patterns: Vec<Pattern>, entries: Vec<PatternEntry>) -> Self {
512 502
        Self {
513 503
            patterns,
514 -
            includes,
515 -
            regexes,
504 +
            entries,
505 +
            matches: Vec::new(),
506 +
            regexes: None,
516 507
        }
517 508
    }
518 509
519 -
    /// Finds the next pattern match at or after `pos`.
520 -
    fn find_next_inner(
521 -
        &self,
522 -
        search: &mut PatternSearch<'_, '_, '_>,
523 -
        pos: usize,
524 -
        active: &mut Vec<PatternSetId>,
525 -
    ) -> Option<Match> {
510 +
    /// Finds the next flattened pattern match at or after `pos`.
511 +
    fn find_next(&self, search: &mut PatternSearch<'_, '_, '_>, pos: usize) -> Option<Match> {
526 512
        if pos > search.limit
527 513
            || search.limit > search.line.len()
528 514
            || !search.line.is_char_boundary(pos)
529 515
        {
530 516
            return None;
531 517
        }
532 -
        let mut found = self.find_next_local(search, pos);
533 -
        for include in &self.includes {
534 -
            let Some(candidate) = include.find_next_inner(search, pos, active) else {
535 -
                continue;
536 -
            };
537 -
            found = match found {
538 -
                Some(current) if current.start <= candidate.start => Some(current),
539 -
                _ => Some(candidate),
540 -
            };
541 -
        }
542 -
        found
543 -
    }
544 -
545 -
    /// Finds the next local pattern match at or after `pos`.
546 -
    fn find_next_local(&self, search: &mut PatternSearch<'_, '_, '_>, pos: usize) -> Option<Match> {
547 518
        let regexes = self.regexes.as_ref()?;
548 519
        let (entry, captures) = regexes.captures_with_options(
549 520
            search.line,
550 521
            pos,
551 522
            search.limit,
552 523
            RegSetLead::Position,
553 524
            search.anchors.search_options(pos),
554 525
        )?;
555 -
        let pattern = self.patterns.get(entry)?;
526 +
        let location = self.matches.get(entry)?;
527 +
        let pattern = search
528 +
            .sets
529 +
            .get(location.set.index())?
530 +
            .patterns
531 +
            .get(location.index)?;
556 532
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
557 533
558 534
        pattern.match_result(regex_match, search)
559 535
    }
560 536
}
590 566
            &self.raw.patterns,
591 567
            &mut vec![&self.raw.repository],
592 568
        )?;
593 569
        self.assign_set(root, root_set);
594 570
        let injections = self.compile_injections()?;
571 +
        self.compile_searches();
595 572
        let rule_locations = self.rule_locations();
596 573
597 574
        Ok(CompiledPatterns {
598 575
            root,
599 576
            sets: self.sets,
621 598
        current: &'raw RawGrammar,
622 599
        patterns: &'raw [RawPattern],
623 600
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
624 601
    ) -> Result<PatternSet, Error> {
625 602
        let mut compiled = Vec::new();
626 -
        let mut includes = Vec::new();
603 +
        let mut entries = Vec::new();
627 604
        for pattern in patterns {
628 605
            if let Some(include) = &pattern.include {
629 606
                if let Some(include) = self.compile_include(current, include, repositories)? {
630 -
                    includes.push(include);
607 +
                    entries.push(PatternEntry::Include(include));
631 608
                }
632 609
                continue;
633 610
            }
634 -
            self.compile_pattern(current, pattern, repositories, &mut compiled, &mut includes)?;
611 +
            self.compile_pattern(current, pattern, repositories, &mut compiled, &mut entries)?;
635 612
        }
636 -
        Ok(PatternSet::new(compiled, includes))
613 +
        Ok(PatternSet::new(compiled, entries))
637 614
    }
638 615
639 616
    /// Compiles one raw pattern into the current pattern-set builder.
640 617
    fn compile_pattern(
641 618
        &mut self,
642 619
        current: &'raw RawGrammar,
643 620
        pattern: &'raw RawPattern,
644 621
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
645 622
        compiled: &mut Vec<Pattern>,
646 -
        includes: &mut Vec<PatternSetId>,
623 +
        entries: &mut Vec<PatternEntry>,
647 624
    ) -> Result<(), Error> {
648 625
        let scope = Scope::from_raw(pattern.name.as_deref(), &mut self.interner);
649 626
        let body = match (
650 627
            &pattern.match_rule,
651 628
            &pattern.begin,
684 661
                    begin_source: begin.clone(),
685 662
                    while_rule,
686 663
                }
687 664
            }
688 665
            _ => {
689 -
                self.inline_patterns(current, pattern, repositories, compiled, includes)?;
666 +
                self.inline_patterns(current, pattern, repositories, compiled, entries)?;
690 667
                return Ok(());
691 668
            }
692 669
        };
693 670
        // Nested children are compiled — and assigned their rule ids — before
694 671
        // this pattern, so every parent has a higher rule id than its children.
713 690
            current,
714 691
            pattern.while_captures.as_ref().or(shared),
715 692
            repositories,
716 693
        )?;
717 694
695 +
        let index = compiled.len();
718 696
        compiled.push(Pattern {
719 697
            id,
720 698
            scope,
721 699
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
722 700
            captures: PatternCaptures {
726 704
                while_rule,
727 705
            },
728 706
            body,
729 707
            nested,
730 708
        });
709 +
        entries.push(PatternEntry::Pattern(index));
731 710
        Ok(())
732 711
    }
733 712
734 713
    /// Compiles grouping pattern children directly into the parent builder.
735 714
    fn inline_patterns(
736 715
        &mut self,
737 716
        current: &'raw RawGrammar,
738 717
        pattern: &'raw RawPattern,
739 718
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
740 719
        compiled: &mut Vec<Pattern>,
741 -
        includes: &mut Vec<PatternSetId>,
720 +
        entries: &mut Vec<PatternEntry>,
742 721
    ) -> Result<(), Error> {
722 +
        let offset = compiled.len();
743 723
        let inline = self.compile_patterns(current, &pattern.patterns, repositories)?;
744 724
        compiled.extend(inline.patterns);
745 -
        includes.extend(inline.includes);
725 +
        entries.extend(inline.entries.into_iter().map(|entry| match entry {
726 +
            PatternEntry::Pattern(index) => PatternEntry::Pattern(index + offset),
727 +
            PatternEntry::Include(id) => PatternEntry::Include(id),
728 +
        }));
746 729
747 730
        Ok(())
748 731
    }
749 732
750 733
    /// Compiles a nested pattern set into the arena and returns its id.
878 861
        }
879 862
        injections.sort_by_key(|injection| injection.selector.priority);
880 863
        Ok(injections)
881 864
    }
882 865
866 +
    /// Compiles flattened regex search sets after all pattern sets are assigned.
867 +
    fn compile_searches(&mut self) {
868 +
        let mut searches = Vec::with_capacity(self.sets.len());
869 +
        for index in 0..self.sets.len() {
870 +
            let mut active = Vec::new();
871 +
            let mut collected = Vec::new();
872 +
            let mut matches = Vec::new();
873 +
            let mut sources = Vec::new();
874 +
            self.collect_search_entries(PatternSetId::new(index), &mut active, &mut collected);
875 +
            for location in collected {
876 +
                let Some(pattern) = self
877 +
                    .sets
878 +
                    .get(location.set.index())
879 +
                    .and_then(|set| set.patterns.get(location.index))
880 +
                else {
881 +
                    continue;
882 +
                };
883 +
                matches.push(location);
884 +
                sources.push(pattern.search_source());
885 +
            }
886 +
            let regexes = (!sources.is_empty())
887 +
                .then(|| RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS).ok())
888 +
                .flatten();
889 +
890 +
            searches.push((matches, regexes));
891 +
        }
892 +
893 +
        for (set, (matches, regexes)) in self.sets.iter_mut().zip(searches) {
894 +
            set.matches = matches;
895 +
            set.regexes = regexes;
896 +
        }
897 +
    }
898 +
899 +
    /// Collects the declaration-order patterns searched for `set`.
900 +
    fn collect_search_entries(
901 +
        &self,
902 +
        set: PatternSetId,
903 +
        active: &mut Vec<PatternSetId>,
904 +
        matches: &mut Vec<RuleLocation>,
905 +
    ) {
906 +
        if active.contains(&set) || active.len() > MAX_INCLUDE_DEPTH {
907 +
            return;
908 +
        }
909 +
        let Some(pattern_set) = self.sets.get(set.index()) else {
910 +
            return;
911 +
        };
912 +
913 +
        active.push(set);
914 +
        for entry in &pattern_set.entries {
915 +
            match entry {
916 +
                PatternEntry::Pattern(index) => matches.push(RuleLocation { set, index: *index }),
917 +
                PatternEntry::Include(include) => {
918 +
                    self.collect_search_entries(*include, active, matches);
919 +
                }
920 +
            }
921 +
        }
922 +
        active.pop();
923 +
    }
924 +
883 925
    /// Compiles capture metadata.
884 926
    fn captures(
885 927
        &mut self,
886 928
        current: &'raw RawGrammar,
887 929
        raw: Option<&'raw BTreeMap<String, RawCapture>>,
crates/highlight/src/tests.rs +26 -0
162 162
    assert!(scopes.contains(&"source.ruby"));
163 163
    assert!(scopes.contains(&"keyword.control.ruby"));
164 164
    assert!(scopes.contains(&"punctuation.section.embedded.end.erb"));
165 165
}
166 166
167 +
#[test]
168 +
fn includes_preserve_pattern_order() {
169 +
    let grammar = Grammar::from_str(
170 +
        r##"{
171 +
            "name":"Test",
172 +
            "scopeName":"source.test",
173 +
            "patterns":[
174 +
                {"include":"#keywords"},
175 +
                {"match":"foo","name":"identifier.test"}
176 +
            ],
177 +
            "repository":{
178 +
                "keywords":{"patterns":[
179 +
                    {"match":"foo","name":"keyword.control.test"}
180 +
                ]}
181 +
            }
182 +
        }"##,
183 +
    )
184 +
    .unwrap();
185 +
186 +
    let spans = grammar.tokenize_line(&mut LineState::default(), "foo");
187 +
    let scopes = scope_names(&grammar, &spans);
188 +
189 +
    assert!(scopes.contains(&"keyword.control.test"));
190 +
    assert!(!scopes.contains(&"identifier.test"));
191 +
}
192 +
167 193
#[test]
168 194
fn scoped_nested_rules_keep_state_even_when_container_has_no_scope() {
169 195
    let grammar = Grammar::from_str(
170 196
        r#"{
171 197
            "name":"Test",