//! Highlight pipeline benchmarks for `rustik-diff`. //! //! The benchmark mirrors the interactive pager's slow path more closely than //! the render benchmark. It times built-in grammar and theme setup, whole-file //! source indexing, request collection, and the final highlight, apply, and //! render pass. //! //! Run with `cargo bench -p rustik-diff --bench highlight`. use std::convert::Infallible; use std::hint::black_box; use std::io::{self, Write as _}; use std::time::{Duration, Instant}; use rustik_diff::{BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer}; use rustik_highlight as syntax; use rustik_tui::{Buffer, Color, Constraint, Label, Rect, Scroll, Style, Table, TableOptions}; /// Fixed terminal-sized render area. const AREA: Rect = Rect::new(0, 0, 120, 40); /// Default source line number targeted by the generated patch. const DEFAULT_LINES: usize = 100_000; /// Default number of independent timed runs. const DEFAULT_RUNS: usize = 3; /// Context rows in the sparse viewport document. const SPARSE_CONTEXT_LINES: usize = 32; /// Theme name used by the interactive pager. const THEME_NAME: &str = "rustik-catppuccin-mocha"; /// Built-in syntax theme JSON used by the interactive pager. const THEME: &str = include_str!("../src/themes/rustik-catppuccin-mocha.json"); /// Low-emphasis report text color. const REPORT_DIM: Color = Color::Fixed(244); /// Widest expected duration value used to keep report rows aligned. const DURATION_FORMAT: &str = "000000.0 ms"; /// Runs the benchmark. fn main() { let args = Args::parse(); let sparse_patch = synthetic_context_diff("src/slow.rs", args.lines, SPARSE_CONTEXT_LINES); let sparse_document = decode_patch(&sparse_patch); let old_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "old"); let new_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "new"); let widths = ReportWidths::new(); let mut totals = StageDurations::default(); let mut checksum = 0usize; for _ in 0..args.runs { let report = run_once(&sparse_document, &old_source, &new_source); totals += report.stages; checksum ^= report.checksum; } let stats = totals.div(args.runs); report_stage("assets", stats.assets, widths); report_stage("whole-source", stats.whole_source, widths); report_stage("requests", stats.requests, widths); report_stage("land", stats.land, widths); io::stdout().flush().ok(); black_box(checksum); } /// Benchmark command-line arguments. #[derive(Clone, Copy, Debug)] struct Args { /// Source line number targeted by the generated patch. lines: usize, /// Number of independent timed runs. runs: usize, } impl Args { /// Parses benchmark arguments from the process environment. fn parse() -> Self { let mut parsed = Self { lines: DEFAULT_LINES, runs: DEFAULT_RUNS, }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--lines" => parsed.lines = next_usize(&mut args, parsed.lines), "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1), "--help" | "-h" => { println!( "usage: cargo bench -p rustik-diff --bench highlight -- [--lines N] [--runs N]" ); std::process::exit(0); } _ => {} } } parsed } } /// Stage timings from one benchmark run. #[derive(Clone, Copy, Debug, Default)] struct StageDurations { /// Built-in theme and grammar setup. assets: Duration, /// Whole-file source indexing and loading. whole_source: Duration, /// Visible highlight request collection. requests: Duration, /// Syntax highlight, cache apply, and highlighted render. land: Duration, } impl StageDurations { /// Returns average stage timings over `count` runs. fn div(self, count: usize) -> Self { let count = count.max(1) as u32; Self { assets: self.assets / count, whole_source: self.whole_source / count, requests: self.requests / count, land: self.land / count, } } } impl std::ops::AddAssign for StageDurations { fn add_assign(&mut self, rhs: Self) { self.assets += rhs.assets; self.whole_source += rhs.whole_source; self.requests += rhs.requests; self.land += rhs.land; } } /// Result from one benchmark run. #[derive(Clone, Copy, Debug)] struct BenchReport { /// Timed stage durations. stages: StageDurations, /// Deterministic checksum of the produced work. checksum: usize, } /// Report column widths. #[derive(Clone, Copy, Debug)] struct ReportWidths { /// Width reserved for stage names. stage: usize, /// Width reserved for formatted durations. duration: usize, } impl ReportWidths { /// Computes report column widths. fn new() -> Self { Self { stage: "whole-source".len(), duration: DURATION_FORMAT.len(), } } } /// Parses the next argument as a `usize`. fn next_usize(args: &mut impl Iterator, fallback: usize) -> usize { args.next() .and_then(|value| value.parse().ok()) .unwrap_or(fallback) } /// Runs one timed highlight pipeline pass. fn run_once(sparse_document: &DiffDocument, old_source: &str, new_source: &str) -> BenchReport { let mut stages = StageDurations::default(); let mut checksum = 0usize; let start = Instant::now(); let mut highlighter = build_highlighter(); stages.assets = start.elapsed(); let old_oid = sparse_document.files[0].header.old_oid.unwrap(); let mut viewer = DiffViewer::new(sparse_document.clone(), DiffOptions::default()); let start = Instant::now(); viewer .load_file_sources(|oid| { let source = if oid == old_oid { old_source } else { new_source }; Ok::<_, Infallible>(source.as_bytes().to_vec()) }) .unwrap(); stages.whole_source = start.elapsed(); let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows; viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA); let start = Instant::now(); let requests = viewer.highlight_requests(AREA); stages.requests = start.elapsed(); let start = Instant::now(); let results = highlighter.highlight_requests(requests); checksum ^= results.len(); viewer.apply_highlights(results); let mut buffer = Buffer::empty(AREA); viewer.render(AREA, &mut buffer); checksum ^= buffer.area().rows ^ buffer.area().cols; stages.land = start.elapsed(); BenchReport { stages, checksum } } /// Creates a full source whose visible hunk matches the generated sparse diff. fn synthetic_source(lines: usize, context_lines: usize, changed_value: &str) -> String { let changed = lines.max(1).div_ceil(2); let before = context_lines.min(changed.saturating_sub(1)); let after = context_lines.min(lines.saturating_sub(changed)); let start = changed - before; let end = changed + after; let mut source = String::new(); for line in 1..=lines { if (start..=end).contains(&line) { let value = if line == changed { changed_value } else { "same" }; push_source_line(&mut source, line, value); } else { source.push_str("x\n"); } } source } /// Builds a highlighter for the generated Rust source file. fn build_highlighter() -> BuiltinHighlighter { let raw_theme = match THEME.parse::() { Ok(theme) => theme, Err(error) => { eprintln!("failed to parse benchmark theme: {error:?}"); std::process::exit(1); } }; let mut registry = syntax::Registry::default(); registry.add_theme(syntax::Theme::compile(&raw_theme)); let mut raw = match syntax::syntaxes::RUST.parse::() { Ok(raw) => raw, Err(error) => { eprintln!("failed to parse benchmark grammar: {error:?}"); std::process::exit(1); } }; if !raw .file_types .iter() .any(|existing| existing.eq_ignore_ascii_case("rs")) { raw.file_types.push("rs".to_owned()); } let grammar = match syntax::Grammar::compile_with(&raw, &[]) { Ok(grammar) => grammar, Err(error) => { eprintln!("failed to compile benchmark grammar: {error:?}"); std::process::exit(1); } }; registry.add_grammar(grammar); BuiltinHighlighter::new(registry, THEME_NAME) } /// Decodes a synthetic patch or exits with a benchmark setup error. fn decode_patch(patch: &str) -> DiffDocument { match DiffDocument::decode_str(patch) { Ok(document) => document, Err(error) => { eprintln!("failed to decode generated benchmark diff: {error}"); std::process::exit(1); } } } /// Creates a deterministic Git-style unified diff for one centered file hunk. fn synthetic_context_diff(path: &str, lines: usize, context_lines: usize) -> String { let mut diff = String::new(); diff.push_str(&format!("diff --git a/{path} b/{path}\n")); diff.push_str("index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n"); diff.push_str(&format!("--- a/{path}\n")); diff.push_str(&format!("+++ b/{path}\n")); let changed = lines.max(1).div_ceil(2); let before = context_lines.min(changed.saturating_sub(1)); let after = context_lines.min(lines.saturating_sub(changed)); let start = changed - before; let old_lines = before + 1 + after; let new_lines = old_lines; diff.push_str(&format!( "@@ -{start},{old_lines} +{start},{new_lines} @@ fn hunk_{changed:06}()\n" )); for line in start..changed { push_context_line(&mut diff, line); } diff.push('-'); push_source_line(&mut diff, changed, "old"); diff.push('+'); push_source_line(&mut diff, changed, "new"); for line in changed + 1..=changed + after { push_context_line(&mut diff, line); } diff } /// Adds one generated context line. fn push_context_line(diff: &mut String, line: usize) { diff.push(' '); push_source_line(diff, line, "same"); } /// Adds one generated source line after the diff prefix. fn push_source_line(diff: &mut String, line: usize, value: &str) { diff.push_str(&format!("let value_{line:06} = compute_{value}({line});")); diff.push('\n'); } /// Prints one styled stage report line. fn report_stage(stage: &str, duration: Duration, widths: ReportWidths) { let table = Table::new(TableOptions { spacing: 3, ..TableOptions::default() }) .row([ Label::from("x".repeat(widths.stage)), Label::from("0".repeat(widths.duration)), ]) .row([ Label::new(stage).style(Style::default().bold()), Label::from(format_duration(duration)).fg(REPORT_DIM), ]); if let Some(line) = table.lines(Constraint::UNBOUNDED).get(1) { println!("{}", line.styled()); } } /// Formats a duration in milliseconds. fn format_duration(duration: Duration) -> String { format!("{:.1} ms", duration.as_secs_f64() * 1_000.0) }