//! Tokenization benchmarks for `rustik-highlight`. //! //! Compiles one representative TextMate grammar, then tokenizes synthetic //! source blobs line by line while carrying [`LineState`], so multi-line //! begin/end and begin/while rules exercise the cross-line tokenizer paths //! (`advance_inside_open_rule`, `check_while_conditions`, capture //! retokenization, and span clamping). //! //! Run with `cargo bench -p rustik-highlight --bench tokenize`. use std::hint::black_box; use std::str::FromStr; use std::time::{Duration, Instant}; use rustik_highlight::{Grammar, LineState, LineTokenizer}; /// Representative TextMate grammar exercising match, begin/end, begin/while, /// `contentName`, capture, and nested-capture tokenizer paths. const GRAMMAR: &str = r##"{ "name": "Bench", "scopeName": "source.bench", "patterns": [{ "include": "#main" }], "repository": { "main": { "patterns": [ { "include": "#block-comment" }, { "include": "#doc-comment" }, { "include": "#string" }, { "include": "#keyword" }, { "include": "#number" }, { "include": "#call" } ] }, "block-comment": { "name": "comment.block.bench", "contentName": "comment.block.content.bench", "begin": "/\\*", "end": "\\*/", "patterns": [{ "include": "#codetag" }] }, "doc-comment": { "name": "comment.line.documentation.bench", "contentName": "comment.line.content.bench", "begin": "^\\s*///", "while": "^\\s*///", "patterns": [{ "include": "#codetag" }] }, "codetag": { "name": "keyword.codetag.bench", "match": "\\b(TODO|FIXME|NOTE)\\b" }, "string": { "name": "string.quoted.double.bench", "begin": "\"", "end": "\"", "patterns": [ { "name": "constant.character.escape.bench", "match": "\\\\." } ] }, "keyword": { "name": "keyword.control.bench", "match": "\\b(if|else|while|for|return|fn|let|const|struct|match|impl)\\b" }, "number": { "name": "constant.numeric.bench", "match": "\\b[0-9]+(\\.[0-9]+)?\\b" }, "call": { "match": "\\b([a-z_][A-Za-z0-9_]*)(\\()", "captures": { "1": { "name": "entity.name.function.bench", "patterns": [{ "include": "#keyword" }] }, "2": { "name": "punctuation.section.parens.begin.bench" } } } } }"##; /// Default number of source lines per generated blob. const DEFAULT_LINES: usize = 2_000; /// Default number of full-blob tokenization passes per timed run. const DEFAULT_PASSES: usize = 100; /// Default number of independent timed runs per workload. const DEFAULT_RUNS: usize = 5; /// Runs the tokenization benchmark. fn main() { let args = Args::parse(); let grammar = match Grammar::from_str(GRAMMAR) { Ok(grammar) => grammar, Err(error) => { eprintln!("failed to compile benchmark grammar: {error:?}"); std::process::exit(1); } }; let mut checksum = 0usize; for workload in args.workload.expanded() { checksum ^= run_workload(&grammar, workload, args); } black_box(checksum); } /// Benchmark command-line arguments. #[derive(Clone, Copy, Debug)] struct Args { /// Workload to run. workload: Workload, /// Number of source lines per generated blob. lines: usize, /// Number of full-blob tokenization passes per timed run. passes: usize, /// Number of independent timed runs per workload. runs: usize, } impl Args { /// Parses arguments from the process environment. fn parse() -> Self { let mut args = Self { workload: Workload::All, lines: DEFAULT_LINES, passes: DEFAULT_PASSES, runs: DEFAULT_RUNS, }; let mut raw = std::env::args().skip(1); while let Some(flag) = raw.next() { match flag.as_str() { "--workload" | "-w" => { if let Some(value) = raw.next().and_then(|value| value.parse().ok()) { args.workload = value; } } "--lines" => args.lines = next_usize(&mut raw, args.lines), "--passes" => args.passes = next_usize(&mut raw, args.passes), "--runs" => args.runs = next_usize(&mut raw, args.runs), "--help" | "-h" => { println!( "usage: cargo bench -p rustik-highlight --bench tokenize -- \ [--workload mixed|comments|code|all] [--lines N] [--passes N] [--runs N]" ); std::process::exit(0); } _ => {} } } args } } /// Parses the next argument as a `usize`, clamped to at least one. fn next_usize(args: &mut impl Iterator, fallback: usize) -> usize { args.next() .and_then(|value| value.parse().ok()) .unwrap_or(fallback) .max(1) } /// Named tokenization workload. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum Workload { /// Balanced mix of code lines and multi-line comment blocks. Mixed, /// Comment-heavy source dominated by multi-line begin/end and begin/while rules. Comments, /// Code-heavy source dominated by match rules and capture retokenization. Code, /// Runs every named workload. All, } impl Workload { /// Returns the concrete workloads represented by this value. fn expanded(self) -> Vec { match self { Self::All => vec![Self::Mixed, Self::Comments, Self::Code], workload => vec![workload], } } /// Returns the workload display name. const fn name(self) -> &'static str { match self { Self::Mixed => "mixed", Self::Comments => "comments", Self::Code => "code", Self::All => "all", } } } impl FromStr for Workload { type Err = (); fn from_str(value: &str) -> Result { match value { "mixed" => Ok(Self::Mixed), "comments" => Ok(Self::Comments), "code" => Ok(Self::Code), "all" => Ok(Self::All), _ => Err(()), } } } /// Runs one workload and prints its result row. fn run_workload(grammar: &Grammar, workload: Workload, args: Args) -> usize { let blob = generate(workload, args.lines); let mut rates = Vec::with_capacity(args.runs); let mut checksum = 0usize; for _ in 0..args.runs { let (elapsed, run_checksum) = run_once(grammar, &blob, args.passes); let lines = (blob.len() * args.passes) as f64; rates.push(lines / elapsed.as_secs_f64()); checksum ^= run_checksum; } let stats = Stats::from_rates(&rates); println!( "{:<10} {:>12.1} lines/s ±{:.1}", workload.name(), stats.avg, stats.stddev, ); checksum } /// Tokenizes the blob `passes` times and returns the elapsed time and a /// deterministic checksum of the emitted spans. fn run_once(grammar: &Grammar, blob: &[String], passes: usize) -> (Duration, usize) { let mut tokenizer = LineTokenizer::new(grammar); let mut spans = Vec::new(); let mut checksum = 0usize; let start = Instant::now(); for pass in 0..passes { let mut state = LineState::default(); for line in blob { tokenizer.tokenize_line_into(&mut state, line, &mut spans); checksum = checksum.wrapping_add(spans.len()).rotate_left(1); } checksum ^= pass; } (start.elapsed(), checksum) } /// Builds a deterministic source blob for one workload. fn generate(workload: Workload, lines: usize) -> Vec { let mut blob = Vec::with_capacity(lines); let mut block = 0usize; while blob.len() < lines { match workload { Workload::Code => blob.push(code_line(blob.len())), Workload::Comments => { push_block_comment(&mut blob, block, 5); push_doc_comment(&mut blob, block, 4); } Workload::Mixed | Workload::All => { for _ in 0..6 { blob.push(code_line(blob.len())); } push_block_comment(&mut blob, block, 3); for _ in 0..4 { blob.push(code_line(blob.len())); } push_doc_comment(&mut blob, block, 3); } } block += 1; } blob.truncate(lines); blob } /// Returns one generated code line covering keywords, numbers, strings, and calls. fn code_line(n: usize) -> String { match n % 4 { 0 => format!("let value_{n} = compute_{n}(\"item {n}\", {n});"), 1 => format!("if value_{n} > {n} {{ return helper_{n}({n}); }}"), 2 => format!("const LIMIT_{n}: u32 = {};", n.wrapping_mul(7)), _ => format!(" while next_{n}() {{ step_{n}({n}.5); }}"), } } /// Appends a multi-line block comment spanning `span` lines. fn push_block_comment(blob: &mut Vec, block: usize, span: usize) { blob.push(format!("/* block {block}: TODO revisit")); for line in 1..span { blob.push(format!(" * detail {line} NOTE keep aligned")); } blob.push(" */".to_owned()); } /// Appends a multi-line `///` documentation comment spanning `span` lines. fn push_doc_comment(blob: &mut Vec, block: usize, span: usize) { for line in 0..span { blob.push(format!("/// doc {block} line {line}: FIXME expand")); } } /// Summary statistics for repeated benchmark runs. #[derive(Clone, Copy, Debug)] struct Stats { /// Mean lines tokenized per second. avg: f64, /// Standard deviation of the per-run rate. stddev: f64, } impl Stats { /// Computes statistics from per-run line rates. fn from_rates(rates: &[f64]) -> Self { let count = rates.len() as f64; let avg = rates.iter().sum::() / count; let variance = rates.iter().map(|rate| (rate - avg).powi(2)).sum::() / count; Self { avg, stddev: variance.sqrt(), } } }