Skip to main content

path_res_bench/
path_res_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//! File path-resolution benchmark (`CrateSnapshot::resolve_file_paths_into`, Step 2.4)
12//! measuring `ns/file`, total resolved references/locals, and heap allocations across
13//! workspace + `$RIDX_BENCH_REPOS`.
14
15use ridx_syntax::name_res::{CrateId, CrateSnapshot, Edition, FileId, FileNameRes, GlobalDefId, ItemKind, MemItemDb, MemSourceDb, OwnedDef, OwnedUse, SourceDb, VisKind};
16use ridx_syntax::{parse, SyntaxTree};
17use std::alloc::{GlobalAlloc, Layout, System};
18use std::cell::Cell;
19use std::hint::black_box;
20use std::path::{Path, PathBuf};
21use std::time::{Duration, Instant};
22
23struct CountingAlloc;
24
25#[derive(Clone, Copy, Default)]
26struct AllocStats {
27    enabled: bool,
28    allocs: u64,
29    total_bytes: u64,
30}
31
32thread_local! {
33    static STATS: Cell<AllocStats> = const { Cell::new(AllocStats { enabled: false, allocs: 0, total_bytes: 0 }) };
34}
35
36// SAFETY: Delegates directly to `std::alloc::System` while counting heap allocations on this thread.
37unsafe impl GlobalAlloc for CountingAlloc {
38    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
39        let ptr = unsafe { System.alloc(layout) };
40        if !ptr.is_null() {
41            let _ = STATS.try_with(|c| {
42                let mut s = c.get();
43                if s.enabled {
44                    s.allocs += 1;
45                    s.total_bytes += layout.size() as u64;
46                    c.set(s);
47                }
48            });
49        }
50        ptr
51    }
52
53    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
54        unsafe { System.dealloc(ptr, layout) };
55    }
56
57    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
58        let out = unsafe { System.realloc(ptr, layout, new_size) };
59        if !out.is_null() {
60            let _ = STATS.try_with(|c| {
61                let mut s = c.get();
62                if s.enabled {
63                    s.allocs += 1;
64                    if new_size > layout.size() {
65                        s.total_bytes += (new_size - layout.size()) as u64;
66                    }
67                    c.set(s);
68                }
69            });
70        }
71        out
72    }
73}
74
75#[global_allocator]
76static GLOBAL: CountingAlloc = CountingAlloc;
77
78fn measure_allocs<R>(f: impl FnOnce() -> R) -> (R, AllocStats) {
79    STATS.with(|c| c.set(AllocStats { enabled: true, allocs: 0, total_bytes: 0 }));
80    let out = f();
81    let stats = STATS.with(|c| {
82        let mut s = c.get();
83        s.enabled = false;
84        c.set(s);
85        s
86    });
87    (out, stats)
88}
89
90fn seed_minimal_sysroot(db: &mut MemItemDb) -> (CrateId, CrateId, CrateId) {
91    let core_k = db.add_crate("core", Edition::Edition2021);
92    let alloc_k = db.add_crate("alloc", Edition::Edition2021);
93    let std_k = db.add_crate("std", Edition::Edition2021);
94    for (idx, k) in [core_k, alloc_k, std_k].into_iter().enumerate() {
95        let root = GlobalDefId::new(k, 0);
96        let prel = GlobalDefId::new(k, 1);
97        db.set_crate_root_def(k, root);
98        db.set_prelude_module(k, prel);
99        let opt = GlobalDefId::new(k, 10 + idx as u32 * 4);
100        let some_d = GlobalDefId::new(k, 11 + idx as u32 * 4);
101        let none_d = GlobalDefId::new(k, 12 + idx as u32 * 4);
102        db.add_module_def(prel, OwnedDef { id: opt, name: "Option".into(), kind: ItemKind::Enum, vis: VisKind::Public, has_value_ctor: false });
103        db.add_assoc_item(opt, OwnedDef { id: some_d, name: "Some".into(), kind: ItemKind::Variant, vis: VisKind::Public, has_value_ctor: true });
104        db.add_assoc_item(opt, OwnedDef { id: none_d, name: "None".into(), kind: ItemKind::Variant, vis: VisKind::Public, has_value_ctor: true });
105        for (nm, vd) in [("Some", some_d), ("None", none_d)] {
106            db.add_module_use(
107                prel,
108                OwnedUse {
109                    name: nm.into(),
110                    type_def: vd,
111                    value_def: vd,
112                    macro_def: GlobalDefId::NONE,
113                    vis: VisKind::Public,
114                    is_glob: false,
115                    is_reexport: true,
116                    is_prelude: false,
117                    is_underscore: false,
118                    prim_ty_code: 0,
119                },
120            );
121        }
122    }
123    (core_k, alloc_k, std_k)
124}
125
126fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
127    if dir.parent().is_none() {
128        return;
129    }
130    let Ok(rd) = std::fs::read_dir(dir) else {
131        return;
132    };
133    let mut entries: Vec<_> = rd.filter_map(|e| e.ok()).collect();
134    entries.sort_by_key(|e| e.file_name());
135    for e in entries {
136        let Ok(ft) = e.file_type() else { continue };
137        if ft.is_symlink() {
138            continue;
139        }
140        let p = e.path();
141        let s = e.file_name().to_string_lossy().into_owned();
142        if ft.is_dir() {
143            if !matches!(s.as_str(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
144                collect_repo(&p, out_rs, out_manifests);
145            }
146        } else if ft.is_file() && s == "Cargo.toml" {
147            out_manifests.push(p);
148        } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
149            out_rs.push(p);
150        }
151    }
152}
153
154fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
155    let mut section = "";
156    let mut name = String::from("crate");
157    let mut edition = Edition::Edition2021;
158    let mut lib_path = None;
159    let mut features = Vec::new();
160    for raw in toml_text.lines() {
161        let line = raw.split('#').next().unwrap_or("").trim();
162        if line.is_empty() {
163            continue;
164        }
165        if line.starts_with('[') && line.ends_with(']') {
166            section = &line[1..line.len() - 1];
167            continue;
168        }
169        let Some((k, v)) = line.split_once('=') else {
170            continue;
171        };
172        let (k, v) = (k.trim().trim_matches('"'), v.trim().trim_matches('"'));
173        match section {
174            "package" if k == "name" => name = v.replace('-', "_"),
175            "package" if k == "edition" => {
176                edition = match v {
177                    "2015" => Edition::Edition2015,
178                    "2018" => Edition::Edition2018,
179                    "2024" => Edition::Edition2024,
180                    _ => Edition::Edition2021,
181                };
182            }
183            "lib" if k == "path" => lib_path = Some(v.to_string()),
184            "features" => features.push(k.to_string()),
185            _ => {}
186        }
187    }
188    (name, edition, lib_path, features)
189}
190
191fn bench_repo(root: &Path) {
192    let mut rs_paths = Vec::new();
193    let mut manifests = Vec::new();
194    collect_repo(root, &mut rs_paths, &mut manifests);
195    if rs_paths.is_empty() {
196        return;
197    }
198    let mut sources = MemSourceDb::new();
199    for p in &rs_paths {
200        if let Ok(text) = std::fs::read_to_string(p) {
201            let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
202            sources.add_file(&rel, text);
203        }
204    }
205    let mut db = MemItemDb::new();
206    let (core_k, alloc_k, std_k) = seed_minimal_sysroot(&mut db);
207    let mut crates = Vec::new();
208    for mp in &manifests {
209        let Ok(t) = std::fs::read_to_string(mp) else {
210            continue;
211        };
212        if !t.contains("[package]") {
213            continue;
214        }
215        let (pkg, ed, explicit_lib, feats) = parse_manifest_meta(&t);
216        let cdir = mp.parent().unwrap_or(root);
217        let rel = cdir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
218        let join_r = |s: &str| {
219            if rel.is_empty() {
220                s.to_string()
221            } else {
222                format!("{rel}/{s}")
223            }
224        };
225        let lib_fid = explicit_lib
226            .as_deref()
227            .and_then(|lp| sources.resolve_path(&join_r(lp)))
228            .or_else(|| sources.resolve_path(&join_r("src/lib.rs")))
229            .or_else(|| sources.resolve_path(&join_r("src/main.rs")));
230        let Some(rf) = lib_fid else { continue };
231        let cid = db.add_crate(&pkg, ed);
232        db.set_crate_root_def(cid, GlobalDefId::new(cid, 0));
233        for ext in [("core", core_k), ("alloc", alloc_k), ("std", std_k)] {
234            db.add_extern_crate(cid, ext.0, ext.1);
235        }
236        db.add_cfg_flag(cid, "unix");
237        for f in &feats {
238            db.add_cfg_kv(cid, "feature", f.as_str());
239        }
240        crates.push((cid, pkg, rf));
241    }
242    if crates.is_empty() {
243        return;
244    }
245    for i in 0..crates.len() {
246        for j in 0..crates.len() {
247            if i != j {
248                db.add_extern_crate(crates[i].0, crates[j].1.clone(), crates[j].0);
249            }
250        }
251    }
252
253    let parsed: Vec<SyntaxTree<'_>> = (0..sources.len()).map(|i| parse(sources.file_text(FileId(i as u32)))).collect();
254    let mut snapshots = Vec::with_capacity(crates.len());
255    let mut crate_files: Vec<Vec<FileId>> = Vec::with_capacity(crates.len());
256    let mut total_files = 0usize;
257    for &(cid, _, rf) in &crates {
258        let snap = CrateSnapshot::build_clean_cached(&db, &sources, cid, rf, |fid| parsed.get(fid.0 as usize));
259        let mut fids = Vec::new();
260        for m in &snap.mod_tree.modules {
261            if m.file.is_some() && !m.is_inline() && !m.is_unresolved() && !fids.contains(&m.file) {
262                fids.push(m.file);
263            }
264        }
265        total_files += fids.len();
266        crate_files.push(fids);
267        snapshots.push(snap);
268    }
269    if total_files == 0 {
270        return;
271    }
272
273    // Warm up `ExtScopeCache` and reusable `FileNameRes` buffer once so steady-state per-file cost is measured cleanly:
274    let mut out_buf = FileNameRes::new();
275    for (ci, snap) in snapshots.iter().enumerate() {
276        for &fid in &crate_files[ci] {
277            snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
278        }
279    }
280
281    let mut total_refs = 0usize;
282    let mut total_locals = 0usize;
283    let (_, allocs) = measure_allocs(|| {
284        for (ci, snap) in snapshots.iter().enumerate() {
285            for &fid in &crate_files[ci] {
286                snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
287                total_refs += out_buf.refs.len();
288                total_locals += out_buf.locals.len();
289                black_box(&out_buf);
290            }
291        }
292    });
293
294    let rounds = if total_files > 400 { 5usize } else { 11usize };
295    let mut best = Duration::MAX;
296    for _ in 0..rounds {
297        let t0 = Instant::now();
298        for (ci, snap) in snapshots.iter().enumerate() {
299            for &fid in &crate_files[ci] {
300                snap.resolve_file_paths_into(&db, fid, &parsed[fid.0 as usize], &mut out_buf);
301                black_box(out_buf.refs.len());
302            }
303        }
304        best = best.min(t0.elapsed());
305    }
306
307    let files_f = total_files as f64;
308    let label = root.file_name().and_then(|s| s.to_str()).unwrap_or("repo");
309    println!(
310        "{label:<16} crates={:>3} files={:>4} refs={:>7} locals={:>6} | {:>8.1} ns/file ({:>5.2} ms total) | allocs/file={:>4.1} bytes/file={:>7.1}",
311        snapshots.len(),
312        total_files,
313        total_refs,
314        total_locals,
315        best.as_nanos() as f64 / files_f,
316        best.as_secs_f64() * 1000.0,
317        allocs.allocs as f64 / files_f,
318        allocs.total_bytes as f64 / files_f,
319    );
320}
321
322fn default_ws_root() -> PathBuf {
323    if let Ok(ws) = std::env::var("RIDX_WS_SRC") {
324        let p = PathBuf::from(ws);
325        if p.parent().is_some() && p.join("Cargo.toml").is_file() {
326            return p;
327        }
328    }
329    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
330    if let Some(w) = manifest_dir.parent().and_then(Path::parent) {
331        if w.parent().is_some() && w.join("Cargo.toml").is_file() {
332            return w.to_path_buf();
333        }
334    }
335    manifest_dir.to_path_buf()
336}
337
338fn main() {
339    let mut dirs: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
340    if dirs.is_empty() {
341        dirs.push(default_ws_root());
342        if let Ok(dir) = std::env::var("RIDX_BENCH_REPOS") {
343            if let Ok(rd) = std::fs::read_dir(dir) {
344                let mut sub: Vec<_> = rd.filter_map(|e| e.ok().map(|x| x.path())).filter(|p| p.is_dir()).collect();
345                sub.sort();
346                dirs.extend(sub);
347            }
348        }
349    }
350    for p in dirs {
351        bench_repo(&p);
352    }
353}