Skip to main content

mod_tree_bench/
mod_tree_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, per-file latency (`ns/file`), and heap-allocation benchmark for `ModuleTree` (2.1).
12//!
13//! Usage:
14//! - `mod_tree_bench [repo_dir ...]` (also scans subdirectories of `$RIDX_BENCH_REPOS` if set).
15
16use ridx_syntax::name_res::{CrateId, Edition, FileId, MemItemDb, MemSourceDb, ModuleTree, SourceDb};
17use ridx_syntax::{parse, SyntaxTree};
18use std::alloc::{GlobalAlloc, Layout, System};
19use std::cell::Cell;
20use std::hint::black_box;
21use std::path::{Path, PathBuf};
22use std::time::{Duration, Instant};
23
24struct CountingAlloc;
25
26#[derive(Clone, Copy, Default, Debug)]
27struct AllocStats {
28    enabled: bool,
29    allocs: u64,
30    reallocs: u64,
31    deallocs: u64,
32    total_bytes: u64,
33    live_bytes: i64,
34    peak_live_bytes: i64,
35}
36
37thread_local! {
38    static STATS: Cell<AllocStats> = const { Cell::new(AllocStats {
39        enabled: false,
40        allocs: 0,
41        reallocs: 0,
42        deallocs: 0,
43        total_bytes: 0,
44        live_bytes: 0,
45        peak_live_bytes: 0,
46    }) };
47}
48
49// SAFETY: Delegates directly to `std::alloc::System` while updating thread-local counters.
50unsafe impl GlobalAlloc for CountingAlloc {
51    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
52        let ptr = unsafe { System.alloc(layout) };
53        if !ptr.is_null() {
54            let _ = STATS.try_with(|c| {
55                let mut s = c.get();
56                if s.enabled {
57                    s.allocs += 1;
58                    s.total_bytes += layout.size() as u64;
59                    s.live_bytes += layout.size() as i64;
60                    if s.live_bytes > s.peak_live_bytes {
61                        s.peak_live_bytes = s.live_bytes;
62                    }
63                    c.set(s);
64                }
65            });
66        }
67        ptr
68    }
69
70    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
71        let _ = STATS.try_with(|c| {
72            let mut s = c.get();
73            if s.enabled {
74                s.deallocs += 1;
75                s.live_bytes -= layout.size() as i64;
76                c.set(s);
77            }
78        });
79        unsafe { System.dealloc(ptr, layout) };
80    }
81
82    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
83        let out = unsafe { System.realloc(ptr, layout, new_size) };
84        if !out.is_null() {
85            let _ = STATS.try_with(|c| {
86                let mut s = c.get();
87                if s.enabled {
88                    s.reallocs += 1;
89                    if new_size > layout.size() {
90                        s.total_bytes += (new_size - layout.size()) as u64;
91                    }
92                    s.live_bytes += new_size as i64 - layout.size() as i64;
93                    if s.live_bytes > s.peak_live_bytes {
94                        s.peak_live_bytes = s.live_bytes;
95                    }
96                    c.set(s);
97                }
98            });
99        }
100        out
101    }
102}
103
104#[global_allocator]
105static GLOBAL: CountingAlloc = CountingAlloc;
106
107fn measure_allocs<R>(f: impl FnOnce() -> R) -> (R, AllocStats) {
108    STATS.with(|c| {
109        c.set(AllocStats { enabled: true, ..AllocStats::default() });
110    });
111    let out = f();
112    let stats = STATS.with(|c| {
113        let mut s = c.get();
114        s.enabled = false;
115        c.set(s);
116        s
117    });
118    (out, stats)
119}
120
121struct CrateEntry {
122    id: CrateId,
123    root_file: FileId,
124}
125
126struct CorpusFixture {
127    label: String,
128    db: MemItemDb,
129    sources: MemSourceDb,
130    crates: Vec<CrateEntry>,
131    total_rs_files: usize,
132}
133
134fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
135    if dir.parent().is_none() {
136        return;
137    }
138    let Ok(rd) = std::fs::read_dir(dir) else {
139        return;
140    };
141    let mut entries: Vec<_> = rd.flatten().collect();
142    entries.sort_by_key(|e| e.file_name());
143    for e in entries {
144        let Ok(ft) = e.file_type() else { continue };
145        if ft.is_symlink() {
146            continue;
147        }
148        let p = e.path();
149        let name = e.file_name();
150        let s = name.to_string_lossy();
151        if ft.is_dir() {
152            if matches!(s.as_ref(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
153                continue;
154            }
155            collect_repo(&p, out_rs, out_manifests);
156        } else if ft.is_file() && s == "Cargo.toml" {
157            out_manifests.push(p);
158        } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
159            out_rs.push(p);
160        }
161    }
162}
163
164fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
165    let mut section = "";
166    let mut name = String::from("crate");
167    let mut edition = Edition::Edition2021;
168    let mut lib_path: Option<String> = None;
169    let mut features = Vec::new();
170    for raw in toml_text.lines() {
171        let line = raw.split('#').next().unwrap_or("").trim();
172        if line.is_empty() {
173            continue;
174        }
175        if line.starts_with('[') && line.ends_with(']') {
176            section = &line[1..line.len() - 1];
177            continue;
178        }
179        let Some((k, v)) = line.split_once('=') else {
180            continue;
181        };
182        let k = k.trim().trim_matches('"');
183        let v = v.trim().trim_matches('"');
184        match section {
185            "package" if k == "name" => name = v.replace('-', "_"),
186            "package" if k == "edition" => {
187                edition = match v {
188                    "2015" => Edition::Edition2015,
189                    "2018" => Edition::Edition2018,
190                    "2024" => Edition::Edition2024,
191                    _ => Edition::Edition2021,
192                };
193            }
194            "lib" if k == "path" => lib_path = Some(v.to_string()),
195            "features" => features.push(k.to_string()),
196            _ => {}
197        }
198    }
199    (name, edition, lib_path, features)
200}
201
202fn load_corpus(root: &Path) -> Option<CorpusFixture> {
203    let mut rs_paths = Vec::new();
204    let mut manifests = Vec::new();
205    collect_repo(root, &mut rs_paths, &mut manifests);
206    if rs_paths.is_empty() {
207        return None;
208    }
209    let mut sources = MemSourceDb::new();
210    for p in &rs_paths {
211        let Ok(text) = std::fs::read_to_string(p) else {
212            continue;
213        };
214        let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
215        sources.add_file(&rel, &text);
216    }
217
218    let mut db = MemItemDb::new();
219    let mut crates = Vec::new();
220    for mp in &manifests {
221        let Ok(toml_text) = std::fs::read_to_string(mp) else {
222            continue;
223        };
224        if !toml_text.contains("[package]") {
225            continue;
226        }
227        let (pkg_name, ed, explicit_lib, feats) = parse_manifest_meta(&toml_text);
228        let crate_dir = mp.parent().unwrap_or(root);
229        let rel_dir = crate_dir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
230        let join_rel = |sub: &str| {
231            if rel_dir.is_empty() {
232                sub.to_string()
233            } else {
234                format!("{rel_dir}/{sub}")
235            }
236        };
237        let mut roots = Vec::new();
238        if let Some(lp) = explicit_lib {
239            if let Some(fid) = sources.resolve_path(&join_rel(&lp)) {
240                roots.push(fid);
241            }
242        } else if let Some(fid) = sources.resolve_path(&join_rel("src/lib.rs")) {
243            roots.push(fid);
244        }
245        if let Some(fid) = sources.resolve_path(&join_rel("src/main.rs")) {
246            if !roots.contains(&fid) {
247                roots.push(fid);
248            }
249        }
250        for root_file in roots {
251            let cid = db.add_crate(&pkg_name, ed);
252            for flag in ["unix", "test"] {
253                db.add_cfg_flag(cid, flag);
254            }
255            for (k, v) in [
256                ("target_os", "linux"),
257                ("target_family", "unix"),
258                ("target_arch", "x86_64"),
259                ("target_pointer_width", "64"),
260                ("target_endian", "little"),
261                ("target_has_atomic", "64"),
262                ("target_has_atomic", "ptr"),
263            ] {
264                db.add_cfg_kv(cid, k, v);
265            }
266            for f in &feats {
267                db.add_cfg_kv(cid, "feature", f.as_str());
268            }
269            crates.push(CrateEntry { id: cid, root_file });
270        }
271    }
272    if crates.is_empty() {
273        return None;
274    }
275    let label = root.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "repo".into());
276    let total_rs_files = sources.len();
277    Some(CorpusFixture { label, db, sources, crates, total_rs_files })
278}
279
280fn bench_corpus(fx: &CorpusFixture) {
281    let parsed: Vec<SyntaxTree<'_>> = (0..fx.sources.len()).map(|i| parse(fx.sources.file_text(FileId(i as u32)))).collect();
282
283    let ((mod_count, reached_files, unresolved), alloc_cached) = measure_allocs(|| {
284        let mut mods = 0usize;
285        let mut reached = 0usize;
286        let mut unres = 0usize;
287        for c in &fx.crates {
288            let t = ModuleTree::build_cached(&fx.db, &fx.sources, c.id, c.root_file, |fid| parsed.get(fid.0 as usize));
289            for m in &t.modules {
290                if m.is_unresolved() {
291                    unres += 1;
292                } else if !m.is_inline() {
293                    reached += 1;
294                }
295            }
296            mods += t.modules.len();
297            black_box(&t);
298        }
299        (mods, reached, unres)
300    });
301
302    let mut best_cached = Duration::MAX;
303    let iters = if reached_files > 1500 { 7 } else { 15 };
304    for _ in 0..iters {
305        let t0 = Instant::now();
306        for c in &fx.crates {
307            let t = ModuleTree::build_cached(&fx.db, &fx.sources, c.id, c.root_file, |fid| parsed.get(fid.0 as usize));
308            black_box(t);
309        }
310        best_cached = best_cached.min(t0.elapsed());
311    }
312
313    let mut best_cold = Duration::MAX;
314    let cold_iters = if reached_files > 1500 { 2 } else { 4 };
315    for _ in 0..cold_iters {
316        let t0 = Instant::now();
317        for c in &fx.crates {
318            let t = ModuleTree::build(&fx.db, &fx.sources, c.id, c.root_file);
319            black_box(t);
320        }
321        best_cold = best_cold.min(t0.elapsed());
322    }
323
324    let denom = reached_files.max(1) as f64;
325    let cached_ns_per_file = best_cached.as_nanos() as f64 / denom;
326    let cold_us_per_file = best_cold.as_nanos() as f64 / 1000.0 / denom;
327    let allocs_per_file = (alloc_cached.allocs + alloc_cached.reallocs) as f64 / denom;
328    let bytes_per_file = alloc_cached.total_bytes as f64 / denom;
329
330    println!(
331        "{:<18} crates={:>4} rs_all={:>5} reached={:>5} mods={:>5} unres={:>3} | tree_only={:>7.1} ns/file ({:>6.2} ms) | parse+tree={:>6.2} us/file | allocs/file={:>4.2} bytes/file={:>6.1}",
332        fx.label,
333        fx.crates.len(),
334        fx.total_rs_files,
335        reached_files,
336        mod_count,
337        unresolved,
338        cached_ns_per_file,
339        best_cached.as_secs_f64() * 1000.0,
340        cold_us_per_file,
341        allocs_per_file,
342        bytes_per_file,
343    );
344}
345
346fn main() {
347    let mut dirs: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
348    if dirs.is_empty() {
349        if let Ok(ws) = std::env::var("RIDX_WS_SRC") {
350            let p = PathBuf::from(ws);
351            if p.parent().is_some() && p.join("Cargo.toml").is_file() {
352                dirs.push(p);
353            }
354        } else if let Some(w) = Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent) {
355            if w.parent().is_some() && w.join("Cargo.toml").is_file() {
356                dirs.push(w.to_path_buf());
357            }
358        }
359        if dirs.is_empty() {
360            dirs.push(PathBuf::from(env!("CARGO_MANIFEST_DIR")));
361        }
362        if let Ok(bench_root) = std::env::var("RIDX_BENCH_REPOS") {
363            if let Ok(rd) = std::fs::read_dir(bench_root) {
364                let mut sub: Vec<PathBuf> = rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
365                sub.sort();
366                dirs.extend(sub);
367            }
368        }
369    }
370    for d in dirs {
371        if let Some(fx) = load_corpus(&d) {
372            bench_corpus(&fx);
373        }
374    }
375}