Skip to main content

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