crates/highlight/benches/tokenize.rs 10.1 KiB raw
1
//! Tokenization benchmarks for `rustik-highlight`.
2
//!
3
//! Compiles one representative TextMate grammar, then tokenizes synthetic
4
//! source blobs line by line while carrying [`LineState`], so multi-line
5
//! begin/end and begin/while rules exercise the cross-line tokenizer paths
6
//! (`advance_inside_open_rule`, `check_while_conditions`, capture
7
//! retokenization, and span clamping).
8
//!
9
//! Run with `cargo bench -p rustik-highlight --bench tokenize`.
10
11
use std::hint::black_box;
12
use std::str::FromStr;
13
use std::time::{Duration, Instant};
14
15
use rustik_highlight::{Grammar, LineState, LineTokenizer};
16
17
/// Representative TextMate grammar exercising match, begin/end, begin/while,
18
/// `contentName`, capture, and nested-capture tokenizer paths.
19
const GRAMMAR: &str = r##"{
20
  "name": "Bench",
21
  "scopeName": "source.bench",
22
  "patterns": [{ "include": "#main" }],
23
  "repository": {
24
    "main": {
25
      "patterns": [
26
        { "include": "#block-comment" },
27
        { "include": "#doc-comment" },
28
        { "include": "#string" },
29
        { "include": "#keyword" },
30
        { "include": "#number" },
31
        { "include": "#call" }
32
      ]
33
    },
34
    "block-comment": {
35
      "name": "comment.block.bench",
36
      "contentName": "comment.block.content.bench",
37
      "begin": "/\\*",
38
      "end": "\\*/",
39
      "patterns": [{ "include": "#codetag" }]
40
    },
41
    "doc-comment": {
42
      "name": "comment.line.documentation.bench",
43
      "contentName": "comment.line.content.bench",
44
      "begin": "^\\s*///",
45
      "while": "^\\s*///",
46
      "patterns": [{ "include": "#codetag" }]
47
    },
48
    "codetag": {
49
      "name": "keyword.codetag.bench",
50
      "match": "\\b(TODO|FIXME|NOTE)\\b"
51
    },
52
    "string": {
53
      "name": "string.quoted.double.bench",
54
      "begin": "\"",
55
      "end": "\"",
56
      "patterns": [
57
        { "name": "constant.character.escape.bench", "match": "\\\\." }
58
      ]
59
    },
60
    "keyword": {
61
      "name": "keyword.control.bench",
62
      "match": "\\b(if|else|while|for|return|fn|let|const|struct|match|impl)\\b"
63
    },
64
    "number": {
65
      "name": "constant.numeric.bench",
66
      "match": "\\b[0-9]+(\\.[0-9]+)?\\b"
67
    },
68
    "call": {
69
      "match": "\\b([a-z_][A-Za-z0-9_]*)(\\()",
70
      "captures": {
71
        "1": {
72
          "name": "entity.name.function.bench",
73
          "patterns": [{ "include": "#keyword" }]
74
        },
75
        "2": { "name": "punctuation.section.parens.begin.bench" }
76
      }
77
    }
78
  }
79
}"##;
80
81
/// Default number of source lines per generated blob.
82
const DEFAULT_LINES: usize = 2_000;
83
/// Default number of full-blob tokenization passes per timed run.
84
const DEFAULT_PASSES: usize = 100;
85
/// Default number of independent timed runs per workload.
86
const DEFAULT_RUNS: usize = 5;
87
88
/// Runs the tokenization benchmark.
89
fn main() {
90
    let args = Args::parse();
91
    let grammar = match Grammar::from_str(GRAMMAR) {
92
        Ok(grammar) => grammar,
93
        Err(error) => {
94
            eprintln!("failed to compile benchmark grammar: {error:?}");
95
            std::process::exit(1);
96
        }
97
    };
98
    let mut checksum = 0usize;
99
100
    for workload in args.workload.expanded() {
101
        checksum ^= run_workload(&grammar, workload, args);
102
    }
103
    black_box(checksum);
104
}
105
106
/// Benchmark command-line arguments.
107
#[derive(Clone, Copy, Debug)]
108
struct Args {
109
    /// Workload to run.
110
    workload: Workload,
111
    /// Number of source lines per generated blob.
112
    lines: usize,
113
    /// Number of full-blob tokenization passes per timed run.
114
    passes: usize,
115
    /// Number of independent timed runs per workload.
116
    runs: usize,
117
}
118
119
impl Args {
120
    /// Parses arguments from the process environment.
121
    fn parse() -> Self {
122
        let mut args = Self {
123
            workload: Workload::All,
124
            lines: DEFAULT_LINES,
125
            passes: DEFAULT_PASSES,
126
            runs: DEFAULT_RUNS,
127
        };
128
        let mut raw = std::env::args().skip(1);
129
130
        while let Some(flag) = raw.next() {
131
            match flag.as_str() {
132
                "--workload" | "-w" => {
133
                    if let Some(value) = raw.next().and_then(|value| value.parse().ok()) {
134
                        args.workload = value;
135
                    }
136
                }
137
                "--lines" => args.lines = next_usize(&mut raw, args.lines),
138
                "--passes" => args.passes = next_usize(&mut raw, args.passes),
139
                "--runs" => args.runs = next_usize(&mut raw, args.runs),
140
                "--help" | "-h" => {
141
                    println!(
142
                        "usage: cargo bench -p rustik-highlight --bench tokenize -- \
143
                         [--workload mixed|comments|code|all] [--lines N] [--passes N] [--runs N]"
144
                    );
145
                    std::process::exit(0);
146
                }
147
                _ => {}
148
            }
149
        }
150
        args
151
    }
152
}
153
154
/// Parses the next argument as a `usize`, clamped to at least one.
155
fn next_usize(args: &mut impl Iterator<Item = String>, fallback: usize) -> usize {
156
    args.next()
157
        .and_then(|value| value.parse().ok())
158
        .unwrap_or(fallback)
159
        .max(1)
160
}
161
162
/// Named tokenization workload.
163
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
164
enum Workload {
165
    /// Balanced mix of code lines and multi-line comment blocks.
166
    Mixed,
167
    /// Comment-heavy source dominated by multi-line begin/end and begin/while rules.
168
    Comments,
169
    /// Code-heavy source dominated by match rules and capture retokenization.
170
    Code,
171
    /// Runs every named workload.
172
    All,
173
}
174
175
impl Workload {
176
    /// Returns the concrete workloads represented by this value.
177
    fn expanded(self) -> Vec<Self> {
178
        match self {
179
            Self::All => vec![Self::Mixed, Self::Comments, Self::Code],
180
            workload => vec![workload],
181
        }
182
    }
183
184
    /// Returns the workload display name.
185
    const fn name(self) -> &'static str {
186
        match self {
187
            Self::Mixed => "mixed",
188
            Self::Comments => "comments",
189
            Self::Code => "code",
190
            Self::All => "all",
191
        }
192
    }
193
}
194
195
impl FromStr for Workload {
196
    type Err = ();
197
198
    fn from_str(value: &str) -> Result<Self, Self::Err> {
199
        match value {
200
            "mixed" => Ok(Self::Mixed),
201
            "comments" => Ok(Self::Comments),
202
            "code" => Ok(Self::Code),
203
            "all" => Ok(Self::All),
204
            _ => Err(()),
205
        }
206
    }
207
}
208
209
/// Runs one workload and prints its result row.
210
fn run_workload(grammar: &Grammar, workload: Workload, args: Args) -> usize {
211
    let blob = generate(workload, args.lines);
212
    let mut rates = Vec::with_capacity(args.runs);
213
    let mut checksum = 0usize;
214
215
    for _ in 0..args.runs {
216
        let (elapsed, run_checksum) = run_once(grammar, &blob, args.passes);
217
        let lines = (blob.len() * args.passes) as f64;
218
        rates.push(lines / elapsed.as_secs_f64());
219
        checksum ^= run_checksum;
220
    }
221
222
    let stats = Stats::from_rates(&rates);
223
    println!(
224
        "{:<10}  {:>12.1} lines/s  ±{:.1}",
225
        workload.name(),
226
        stats.avg,
227
        stats.stddev,
228
    );
229
    checksum
230
}
231
232
/// Tokenizes the blob `passes` times and returns the elapsed time and a
233
/// deterministic checksum of the emitted spans.
234
fn run_once(grammar: &Grammar, blob: &[String], passes: usize) -> (Duration, usize) {
235
    let mut tokenizer = LineTokenizer::new(grammar);
236
    let mut spans = Vec::new();
237
    let mut checksum = 0usize;
238
    let start = Instant::now();
239
240
    for pass in 0..passes {
241
        let mut state = LineState::default();
242
        for line in blob {
243
            tokenizer.tokenize_line_into(&mut state, line, &mut spans);
244
            checksum = checksum.wrapping_add(spans.len()).rotate_left(1);
245
        }
246
        checksum ^= pass;
247
    }
248
249
    (start.elapsed(), checksum)
250
}
251
252
/// Builds a deterministic source blob for one workload.
253
fn generate(workload: Workload, lines: usize) -> Vec<String> {
254
    let mut blob = Vec::with_capacity(lines);
255
    let mut block = 0usize;
256
257
    while blob.len() < lines {
258
        match workload {
259
            Workload::Code => blob.push(code_line(blob.len())),
260
            Workload::Comments => {
261
                push_block_comment(&mut blob, block, 5);
262
                push_doc_comment(&mut blob, block, 4);
263
            }
264
            Workload::Mixed | Workload::All => {
265
                for _ in 0..6 {
266
                    blob.push(code_line(blob.len()));
267
                }
268
                push_block_comment(&mut blob, block, 3);
269
                for _ in 0..4 {
270
                    blob.push(code_line(blob.len()));
271
                }
272
                push_doc_comment(&mut blob, block, 3);
273
            }
274
        }
275
        block += 1;
276
    }
277
    blob.truncate(lines);
278
    blob
279
}
280
281
/// Returns one generated code line covering keywords, numbers, strings, and calls.
282
fn code_line(n: usize) -> String {
283
    match n % 4 {
284
        0 => format!("let value_{n} = compute_{n}(\"item {n}\", {n});"),
285
        1 => format!("if value_{n} > {n} {{ return helper_{n}({n}); }}"),
286
        2 => format!("const LIMIT_{n}: u32 = {};", n.wrapping_mul(7)),
287
        _ => format!("    while next_{n}() {{ step_{n}({n}.5); }}"),
288
    }
289
}
290
291
/// Appends a multi-line block comment spanning `span` lines.
292
fn push_block_comment(blob: &mut Vec<String>, block: usize, span: usize) {
293
    blob.push(format!("/* block {block}: TODO revisit"));
294
    for line in 1..span {
295
        blob.push(format!(" * detail {line} NOTE keep aligned"));
296
    }
297
    blob.push(" */".to_owned());
298
}
299
300
/// Appends a multi-line `///` documentation comment spanning `span` lines.
301
fn push_doc_comment(blob: &mut Vec<String>, block: usize, span: usize) {
302
    for line in 0..span {
303
        blob.push(format!("/// doc {block} line {line}: FIXME expand"));
304
    }
305
}
306
307
/// Summary statistics for repeated benchmark runs.
308
#[derive(Clone, Copy, Debug)]
309
struct Stats {
310
    /// Mean lines tokenized per second.
311
    avg: f64,
312
    /// Standard deviation of the per-run rate.
313
    stddev: f64,
314
}
315
316
impl Stats {
317
    /// Computes statistics from per-run line rates.
318
    fn from_rates(rates: &[f64]) -> Self {
319
        let count = rates.len() as f64;
320
        let avg = rates.iter().sum::<f64>() / count;
321
        let variance = rates.iter().map(|rate| (rate - avg).powi(2)).sum::<f64>() / count;
322
323
        Self {
324
            avg,
325
            stddev: variance.sqrt(),
326
        }
327
    }
328
}