Skip to main content

syntax_bench/
syntax_bench.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Throughput, latency, memory-allocation, and `xref live profile` benchmark harness for `ridx-syntax`.
12//!
13//! Modes:
14//! - `syntax_bench [dir ...]` — runs allocation + multi-iteration throughput benchmarks on workspace + dirs.
15//! - `syntax_bench --profile <lex|parse|sema|all> <secs> [dir ...]` — runs a steady hot loop for `xref live profile`.
16
17use ridx_syntax::sema_fn::{own_returns, own_returns_into, own_try_ops, own_try_ops_into, param_uses, param_uses_into, params, params_into, tail_expr, ParamInfo, ParamUses};
18use ridx_syntax::tree::Node;
19use ridx_syntax::{lex, parse, NodeId, SyntaxKind as K, SyntaxTree, Token};
20use std::alloc::{GlobalAlloc, Layout, System};
21use std::cell::Cell;
22use std::hint::black_box;
23use std::path::{Path, PathBuf};
24use std::time::{Duration, Instant};
25
26struct CountingAlloc;
27
28#[derive(Clone, Copy, Default, Debug)]
29struct AllocStats {
30    enabled: bool,
31    allocs: u64,
32    reallocs: u64,
33    deallocs: u64,
34    total_bytes: u64,
35    live_bytes: i64,
36    peak_live_bytes: i64,
37}
38
39thread_local! {
40    static STATS: Cell<AllocStats> = const { Cell::new(AllocStats {
41        enabled: false,
42        allocs: 0,
43        reallocs: 0,
44        deallocs: 0,
45        total_bytes: 0,
46        live_bytes: 0,
47        peak_live_bytes: 0,
48    }) };
49}
50
51// SAFETY: Delegates directly to `std::alloc::System` while updating thread-local counters.
52unsafe impl GlobalAlloc for CountingAlloc {
53    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
54        let ptr = unsafe { System.alloc(layout) };
55        if !ptr.is_null() {
56            let _ = STATS.try_with(|c| {
57                let mut s = c.get();
58                if s.enabled {
59                    s.allocs += 1;
60                    s.total_bytes += layout.size() as u64;
61                    s.live_bytes += layout.size() as i64;
62                    if s.live_bytes > s.peak_live_bytes {
63                        s.peak_live_bytes = s.live_bytes;
64                    }
65                    c.set(s);
66                }
67            });
68        }
69        ptr
70    }
71
72    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
73        let _ = STATS.try_with(|c| {
74            let mut s = c.get();
75            if s.enabled {
76                s.deallocs += 1;
77                s.live_bytes -= layout.size() as i64;
78                c.set(s);
79            }
80        });
81        unsafe { System.dealloc(ptr, layout) };
82    }
83
84    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
85        let out = unsafe { System.realloc(ptr, layout, new_size) };
86        if !out.is_null() {
87            let _ = STATS.try_with(|c| {
88                let mut s = c.get();
89                if s.enabled {
90                    s.reallocs += 1;
91                    if new_size > layout.size() {
92                        s.total_bytes += (new_size - layout.size()) as u64;
93                    }
94                    s.live_bytes += new_size as i64 - layout.size() as i64;
95                    if s.live_bytes > s.peak_live_bytes {
96                        s.peak_live_bytes = s.live_bytes;
97                    }
98                    c.set(s);
99                }
100            });
101        }
102        out
103    }
104}
105
106#[global_allocator]
107static GLOBAL: CountingAlloc = CountingAlloc;
108
109fn measure_allocs<R>(f: impl FnOnce() -> R) -> (R, AllocStats) {
110    STATS.with(|c| {
111        c.set(AllocStats { enabled: true, ..AllocStats::default() });
112    });
113    let res = f();
114    let snap = STATS.with(|c| {
115        let mut s = c.get();
116        s.enabled = false;
117        c.set(s);
118        s
119    });
120    (res, snap)
121}
122
123fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
124    let Ok(rd) = std::fs::read_dir(dir) else { return };
125    let mut entries: Vec<_> = rd.flatten().collect();
126    entries.sort_by_key(|e| e.file_name());
127    for e in entries {
128        let p = e.path();
129        let name = e.file_name();
130        let name = name.to_string_lossy();
131        if p.is_dir() {
132            if name != "target" && name != ".git" && name != "test_data" {
133                rs_files(&p, out);
134            }
135        } else if name.ends_with(".rs") {
136            out.push(p);
137        }
138    }
139}
140
141fn load_sources(dirs: &[PathBuf]) -> Vec<String> {
142    let mut paths = Vec::new();
143    for d in dirs {
144        rs_files(d, &mut paths);
145    }
146    paths.into_iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect()
147}
148
149#[inline(never)]
150fn run_sema_on_tree(tree: &SyntaxTree<'_>) -> (usize, usize) {
151    let mut fns = 0usize;
152    let mut hits = 0usize;
153    for id in tree.descendants(tree.root()) {
154        if tree.kind(id) != K::Fn {
155            continue;
156        }
157        fns += 1;
158        let ps = params(tree, id);
159        for p in &ps {
160            for &b in &p.bindings {
161                let u = param_uses(tree, id, b);
162                hits += u.uses.len() + u.macro_uses.len();
163            }
164        }
165        hits += own_returns(tree, id).len();
166        hits += own_try_ops(tree, id).len();
167        if tail_expr(tree, id).is_some() {
168            hits += 1;
169        }
170    }
171    (fns, hits)
172}
173
174fn run_profile_loop(mode: &str, secs: u64, sources: &[String]) {
175    let trees: Vec<(SyntaxTree<'_>, Vec<NodeId>)> = if mode == "sema" {
176        sources
177            .iter()
178            .map(|s| {
179                let t = parse(s);
180                let fns: Vec<NodeId> = t.descendants(t.root()).filter(|&n| t.kind(n) == K::Fn).collect();
181                (t, fns)
182            })
183            .collect()
184    } else {
185        Vec::new()
186    };
187    eprintln!("PROFILE_READY pid={} mode={mode} files={}", std::process::id(), sources.len());
188    let deadline = Instant::now() + Duration::from_secs(secs);
189    let mut iters = 0u64;
190    while Instant::now() < deadline {
191        match mode {
192            "lex" => {
193                for s in sources {
194                    black_box(lex(black_box(s.as_str())));
195                }
196            }
197            "parse" => {
198                for s in sources {
199                    black_box(parse(black_box(s.as_str())));
200                }
201            }
202            "sema" => {
203                for (t, _) in &trees {
204                    black_box(run_sema_on_tree(black_box(t)));
205                }
206            }
207            _ => {
208                for s in sources {
209                    let t = parse(black_box(s.as_str()));
210                    black_box(run_sema_on_tree(&t));
211                }
212            }
213        }
214        iters += 1;
215    }
216    eprintln!("PROFILE_DONE pid={} mode={mode} iters={iters}", std::process::id());
217}
218
219fn bench_corpus(label: &str, sources: &[String], iters: usize) {
220    let total_bytes: usize = sources.iter().map(String::len).sum();
221    let mib = total_bytes as f64 / (1024.0 * 1024.0);
222    println!("\n=== Corpus: {label} ({} files, {:.2} MiB) | sizeof(Token)={}B sizeof(Node)={}B ===", sources.len(), mib, std::mem::size_of::<Token>(), std::mem::size_of::<Node>(),);
223
224    // 1. Lexer allocation + best-of-N timing
225    let (_, lex_alloc) = measure_allocs(|| {
226        for s in sources {
227            black_box(lex(s));
228        }
229    });
230    let mut best_lex = f64::MAX;
231    for _ in 0..iters {
232        let t0 = Instant::now();
233        for s in sources {
234            black_box(lex(black_box(s.as_str())));
235        }
236        best_lex = best_lex.min(t0.elapsed().as_secs_f64());
237    }
238    println!(
239        "  lex      : {:>7.2} ms ({:>7.1} MiB/s) | allocs={:<7} reallocs={:<7} total={:>6.2} MiB ({:.2}x src) peak={:>6.2} KiB",
240        best_lex * 1e3,
241        mib / best_lex,
242        lex_alloc.allocs,
243        lex_alloc.reallocs,
244        lex_alloc.total_bytes as f64 / (1024.0 * 1024.0),
245        lex_alloc.total_bytes as f64 / total_bytes.max(1) as f64,
246        lex_alloc.peak_live_bytes as f64 / 1024.0,
247    );
248
249    // 2. Parser allocation + best-of-N timing
250    let (_, parse_alloc) = measure_allocs(|| {
251        for s in sources {
252            black_box(parse(s));
253        }
254    });
255    let mut best_parse = f64::MAX;
256    for _ in 0..iters {
257        let t0 = Instant::now();
258        for s in sources {
259            black_box(parse(black_box(s.as_str())));
260        }
261        best_parse = best_parse.min(t0.elapsed().as_secs_f64());
262    }
263    println!(
264        "  parse    : {:>7.2} ms ({:>7.1} MiB/s) | allocs={:<7} reallocs={:<7} total={:>6.2} MiB ({:.2}x src) peak={:>6.2} KiB",
265        best_parse * 1e3,
266        mib / best_parse,
267        parse_alloc.allocs,
268        parse_alloc.reallocs,
269        parse_alloc.total_bytes as f64 / (1024.0 * 1024.0),
270        parse_alloc.total_bytes as f64 / total_bytes.max(1) as f64,
271        parse_alloc.peak_live_bytes as f64 / 1024.0,
272    );
273
274    // 3. Sema_fn on pre-parsed trees: allocation + best-of-N timing
275    let trees: Vec<SyntaxTree<'_>> = sources.iter().map(|s| parse(s)).collect();
276    let ((fn_count, hit_count), sema_alloc) = measure_allocs(|| {
277        let (mut f, mut h) = (0, 0);
278        for t in &trees {
279            let (df, dh) = run_sema_on_tree(t);
280            f += df;
281            h += dh;
282        }
283        (f, h)
284    });
285    let mut best_sema = f64::MAX;
286    for _ in 0..iters {
287        let t0 = Instant::now();
288        for t in &trees {
289            black_box(run_sema_on_tree(black_box(t)));
290        }
291        best_sema = best_sema.min(t0.elapsed().as_secs_f64());
292    }
293    let ns_per_fn = (best_sema * 1e9) / fn_count.max(1) as f64;
294    let allocs_per_fn = sema_alloc.allocs as f64 / fn_count.max(1) as f64;
295    let bytes_per_fn = sema_alloc.total_bytes as f64 / fn_count.max(1) as f64;
296    println!(
297        "  sema_fn  : {:>7.2} ms ({:>7.1} ns/fn, {fn_count} fns, {hit_count} hits) | allocs={:<7} ({allocs_per_fn:.2}/fn) reallocs={:<6} total={:>6.2} MiB ({bytes_per_fn:.1} B/fn) peak={:>5.1} KiB",
298        best_sema * 1e3,
299        ns_per_fn,
300        sema_alloc.allocs,
301        sema_alloc.reallocs,
302        sema_alloc.total_bytes as f64 / (1024.0 * 1024.0),
303        sema_alloc.peak_live_bytes as f64 / 1024.0,
304    );
305
306    // 4. Zero-alloc buffer-reusing `*_into` pass
307    let mut p_buf: Vec<ParamInfo<'_>> = Vec::with_capacity(16);
308    let mut u_buf = ParamUses { uses: Vec::with_capacity(64), macro_uses: Vec::with_capacity(32) };
309    let mut cf_buf: Vec<NodeId> = Vec::with_capacity(32);
310    let mut run_into = || {
311        let mut h = 0usize;
312        for t in &trees {
313            for id in t.descendants(t.root()) {
314                if t.kind(id) != K::Fn {
315                    continue;
316                }
317                params_into(t, id, &mut p_buf);
318                for p in &p_buf {
319                    for &b in &p.bindings {
320                        param_uses_into(t, id, b, &mut u_buf);
321                        h += u_buf.uses.len() + u_buf.macro_uses.len();
322                    }
323                }
324                own_returns_into(t, id, &mut cf_buf);
325                h += cf_buf.len();
326                own_try_ops_into(t, id, &mut cf_buf);
327                h += cf_buf.len();
328                if tail_expr(t, id).is_some() {
329                    h += 1;
330                }
331            }
332        }
333        h
334    };
335    let _ = run_into(); // warm reusable scratch buffers once
336    let (reuse_hits, reuse_alloc) = measure_allocs(&mut run_into);
337    assert_eq!(reuse_hits, hit_count);
338    let mut best_reuse = f64::MAX;
339    for _ in 0..iters {
340        let t0 = Instant::now();
341        black_box(run_into());
342        best_reuse = best_reuse.min(t0.elapsed().as_secs_f64());
343    }
344    println!(
345        "  sema_into: {:>7.2} ms ({:>7.1} ns/fn, scratch reuse)      | allocs={:<7} reallocs={:<6} total={:>6.2} KiB peak={:>5.1} KiB",
346        best_reuse * 1e3,
347        (best_reuse * 1e9) / fn_count.max(1) as f64,
348        reuse_alloc.allocs,
349        reuse_alloc.reallocs,
350        reuse_alloc.total_bytes as f64 / 1024.0,
351        reuse_alloc.peak_live_bytes as f64 / 1024.0,
352    );
353}
354
355fn main() {
356    let args: Vec<String> = std::env::args().skip(1).collect();
357    if args.first().map(String::as_str) == Some("--profile") {
358        let mode = args.get(1).map_or("all", String::as_str);
359        let secs: u64 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(4);
360        let dirs: Vec<PathBuf> = if args.len() > 3 { args[3..].iter().map(PathBuf::from).collect() } else { vec![PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")] };
361        let sources = load_sources(&dirs);
362        run_profile_loop(mode, secs, &sources);
363        return;
364    }
365
366    let ws_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
367    let ws_sources = load_sources(&[ws_root]);
368    bench_corpus("rust-intelligence", &ws_sources, 7);
369
370    for arg in &args {
371        let p = PathBuf::from(arg);
372        if p.exists() {
373            let name = p.file_name().map_or_else(|| arg.clone(), |n| n.to_string_lossy().into_owned());
374            let srcs = load_sources(&[p]);
375            if !srcs.is_empty() {
376                bench_corpus(&name, &srcs, 5);
377            }
378        }
379    }
380}