1use ridx_syntax::name_res::{CrateDefMap, CrateId, Edition, FileId, GlobalDefId, ItemKind, MemItemDb, MemSourceDb, ModuleId, ModuleTree, 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, Debug)]
25struct AllocStats {
26 enabled: bool,
27 allocs: u64,
28 reallocs: u64,
29 deallocs: u64,
30 total_bytes: u64,
31}
32
33thread_local! {
34 static STATS: Cell<AllocStats> = const { Cell::new(AllocStats {
35 enabled: false,
36 allocs: 0,
37 reallocs: 0,
38 deallocs: 0,
39 total_bytes: 0,
40 }) };
41}
42
43unsafe impl GlobalAlloc for CountingAlloc {
45 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
46 let ptr = unsafe { System.alloc(layout) };
47 if !ptr.is_null() {
48 let _ = STATS.try_with(|c| {
49 let mut s = c.get();
50 if s.enabled {
51 s.allocs += 1;
52 s.total_bytes += layout.size() as u64;
53 c.set(s);
54 }
55 });
56 }
57 ptr
58 }
59
60 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
61 let _ = STATS.try_with(|c| {
62 let mut s = c.get();
63 if s.enabled {
64 s.deallocs += 1;
65 c.set(s);
66 }
67 });
68 unsafe { System.dealloc(ptr, layout) };
69 }
70
71 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
72 let out = unsafe { System.realloc(ptr, layout, new_size) };
73 if !out.is_null() {
74 let _ = STATS.try_with(|c| {
75 let mut s = c.get();
76 if s.enabled {
77 s.reallocs += 1;
78 if new_size > layout.size() {
79 s.total_bytes += (new_size - layout.size()) as u64;
80 }
81 c.set(s);
82 }
83 });
84 }
85 out
86 }
87}
88
89#[global_allocator]
90static GLOBAL: CountingAlloc = CountingAlloc;
91
92fn measure_allocs<R>(f: impl FnOnce() -> R) -> (R, AllocStats) {
93 STATS.with(|c| c.set(AllocStats { enabled: true, ..AllocStats::default() }));
94 let out = f();
95 let stats = STATS.with(|c| {
96 let mut s = c.get();
97 s.enabled = false;
98 c.set(s);
99 s
100 });
101 (out, stats)
102}
103
104fn seed_minimal_sysroot(db: &mut MemItemDb) -> (CrateId, CrateId, CrateId) {
105 let core_k = db.add_crate("core", Edition::Edition2021);
106 let alloc_k = db.add_crate("alloc", Edition::Edition2021);
107 let std_k = db.add_crate("std", Edition::Edition2021);
108 for (k, items) in [
109 (
110 core_k,
111 &[
112 ("option", "Option", ItemKind::Enum),
113 ("result", "Result", ItemKind::Enum),
114 ("convert", "TryFrom", ItemKind::Trait),
115 ("iter", "Iterator", ItemKind::Trait),
116 ("fmt", "Display", ItemKind::Trait),
117 ("ops", "Deref", ItemKind::Trait),
118 ][..],
119 ),
120 (alloc_k, &[("vec", "Vec", ItemKind::Struct), ("string", "String", ItemKind::Struct), ("boxed", "Box", ItemKind::Struct)][..]),
121 (std_k, &[("collections", "HashMap", ItemKind::Struct), ("io", "Read", ItemKind::Trait), ("sync", "Arc", ItemKind::Struct)][..]),
122 ] {
123 let root = GlobalDefId::new(k, 0);
124 let pre = GlobalDefId::new(k, 1);
125 let pre21 = GlobalDefId::new(k, 2);
126 db.set_crate_root_def(k, root);
127 db.add_module_def(root, OwnedDef { id: pre, name: "prelude".into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
128 db.add_module_def(pre, OwnedDef { id: pre21, name: "rust_2021".into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
129 let mut next_idx = 3u32;
130 for &(mname, iname, ikind) in items {
131 let mid = GlobalDefId::new(k, next_idx);
132 let iid = GlobalDefId::new(k, next_idx + 1);
133 next_idx += 2;
134 db.add_module_def(root, OwnedDef { id: mid, name: mname.into(), kind: ItemKind::Mod, vis: VisKind::Public, has_value_ctor: false });
135 db.add_module_def(mid, OwnedDef { id: iid, name: iname.into(), kind: ikind, vis: VisKind::Public, has_value_ctor: false });
136 db.add_module_use(
137 pre21,
138 OwnedUse {
139 name: iname.into(),
140 type_def: iid,
141 value_def: GlobalDefId::NONE,
142 macro_def: GlobalDefId::NONE,
143 vis: VisKind::Public,
144 is_glob: false,
145 is_reexport: true,
146 is_prelude: false,
147 is_underscore: false,
148 prim_ty_code: 0,
149 },
150 );
151 }
152 }
153 (core_k, alloc_k, std_k)
154}
155
156fn collect_repo(dir: &Path, out_rs: &mut Vec<PathBuf>, out_manifests: &mut Vec<PathBuf>) {
157 if dir.parent().is_none() {
158 return;
159 }
160 let Ok(rd) = std::fs::read_dir(dir) else {
161 return;
162 };
163 let mut entries: Vec<_> = rd.flatten().collect();
164 entries.sort_by_key(|e| e.file_name());
165 for e in entries {
166 let Ok(ft) = e.file_type() else { continue };
167 if ft.is_symlink() {
168 continue;
169 }
170 let p = e.path();
171 let s = e.file_name().to_string_lossy().into_owned();
172 if ft.is_dir() {
173 if matches!(s.as_str(), "target" | ".git" | "node_modules" | "fixtures" | "proc" | "sys" | "dev") {
174 continue;
175 }
176 collect_repo(&p, out_rs, out_manifests);
177 } else if ft.is_file() && s == "Cargo.toml" {
178 out_manifests.push(p);
179 } else if ft.is_file() && p.extension().and_then(|x| x.to_str()) == Some("rs") {
180 out_rs.push(p);
181 }
182 }
183}
184
185fn parse_manifest_meta(toml_text: &str) -> (String, Edition, Option<String>, Vec<String>) {
186 let mut section = "";
187 let mut name = String::from("crate");
188 let mut edition = Edition::Edition2021;
189 let mut lib_path = None;
190 let mut features = Vec::new();
191 for raw in toml_text.lines() {
192 let line = raw.split('#').next().unwrap_or("").trim();
193 if line.is_empty() {
194 continue;
195 }
196 if line.starts_with('[') && line.ends_with(']') {
197 section = &line[1..line.len() - 1];
198 continue;
199 }
200 let Some((k, v)) = line.split_once('=') else {
201 continue;
202 };
203 let k = k.trim().trim_matches('"');
204 let v = v.trim().trim_matches('"');
205 match section {
206 "package" if k == "name" => name = v.replace('-', "_"),
207 "package" if k == "edition" => {
208 edition = match v {
209 "2015" => Edition::Edition2015,
210 "2018" => Edition::Edition2018,
211 "2024" => Edition::Edition2024,
212 _ => Edition::Edition2021,
213 };
214 }
215 "lib" if k == "path" => lib_path = Some(v.to_string()),
216 "features" => features.push(k.to_string()),
217 _ => {}
218 }
219 }
220 (name, edition, lib_path, features)
221}
222
223fn bench_dir(root: &Path) {
224 let mut rs_paths = Vec::new();
225 let mut manifests = Vec::new();
226 collect_repo(root, &mut rs_paths, &mut manifests);
227 if rs_paths.is_empty() {
228 return;
229 }
230 let mut sources = MemSourceDb::new();
231 for p in &rs_paths {
232 if let Ok(text) = std::fs::read_to_string(p) {
233 let rel = p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
234 sources.add_file(&rel, text);
235 }
236 }
237 let mut db = MemItemDb::new();
238 let (core_k, alloc_k, std_k) = seed_minimal_sysroot(&mut db);
239 let mut crates = Vec::new();
240 for mp in &manifests {
241 let Ok(t) = std::fs::read_to_string(mp) else {
242 continue;
243 };
244 if !t.contains("[package]") {
245 continue;
246 }
247 let (pkg, ed, explicit_lib, feats) = parse_manifest_meta(&t);
248 let cdir = mp.parent().unwrap_or(root);
249 let rel = cdir.strip_prefix(root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/");
250 let join_r = |s: &str| {
251 if rel.is_empty() {
252 s.to_string()
253 } else {
254 format!("{rel}/{s}")
255 }
256 };
257 let lib_fid = explicit_lib
258 .as_deref()
259 .and_then(|lp| sources.resolve_path(&join_r(lp)))
260 .or_else(|| sources.resolve_path(&join_r("src/lib.rs")))
261 .or_else(|| sources.resolve_path(&join_r("src/main.rs")));
262 let Some(rf) = lib_fid else { continue };
263 let cid = db.add_crate(&pkg, ed);
264 db.set_crate_root_def(cid, GlobalDefId::new(cid, 0));
265 for ext in [("core", core_k), ("alloc", alloc_k), ("std", std_k)] {
266 db.add_extern_crate(cid, ext.0, ext.1);
267 }
268 db.add_cfg_flag(cid, "unix");
269 for f in &feats {
270 db.add_cfg_kv(cid, "feature", f.as_str());
271 }
272 crates.push((cid, pkg, rf));
273 }
274 if crates.is_empty() {
275 return;
276 }
277 for i in 0..crates.len() {
279 for j in 0..crates.len() {
280 if i != j {
281 db.add_extern_crate(crates[i].0, crates[j].1.clone(), crates[j].0);
282 }
283 }
284 }
285
286 let parsed: Vec<SyntaxTree<'_>> = (0..sources.len()).map(|i| parse(sources.file_text(FileId(i as u32)))).collect();
287 let mod_trees: Vec<ModuleTree> = crates.iter().map(|&(cid, _, rf)| ModuleTree::build_cached(&db, &sources, cid, rf, |fid| parsed.get(fid.0 as usize))).collect();
288 let reached_files: usize = mod_trees.iter().map(|t| t.modules.iter().filter(|m| !m.is_inline() && !m.is_unresolved()).count()).sum();
289
290 for mt in &mod_trees {
292 let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
293 let root_g = GlobalDefId::new(mt.krate, 0);
294 let mut seq = 1u32;
295 for (name, pns) in &dm.scope(ModuleId::ROOT).entries {
296 let tdef = pns
297 .types
298 .map(|_| {
299 let g = GlobalDefId::new(mt.krate, seq);
300 seq += 1;
301 g
302 })
303 .unwrap_or(GlobalDefId::NONE);
304 let vdef = pns
305 .values
306 .map(|_| {
307 let g = GlobalDefId::new(mt.krate, seq);
308 seq += 1;
309 g
310 })
311 .unwrap_or(GlobalDefId::NONE);
312 if let Some(tb) = pns.types {
313 db.set_def_kind(tdef, tb.kind);
314 }
315 db.add_module_use(
316 root_g,
317 OwnedUse {
318 name: name.to_string(),
319 type_def: tdef,
320 value_def: vdef,
321 macro_def: GlobalDefId::NONE,
322 vis: VisKind::Public,
323 is_glob: false,
324 is_reexport: true,
325 is_prelude: false,
326 is_underscore: false,
327 prim_ty_code: 0,
328 },
329 );
330 }
331 }
332
333 let ((total_items, total_uses, resolved_uses), allocs) = measure_allocs(|| {
334 let mut items = 0usize;
335 let mut uses = 0usize;
336 let mut res_ok = 0usize;
337 for mt in &mod_trees {
338 let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
339 items += dm.items.len();
340 uses += dm.uses.uses.len();
341 res_ok += dm.resolved_uses.iter().filter(|p| !p.is_empty()).count();
342 black_box(&dm);
343 }
344 (items, uses, res_ok)
345 });
346
347 let mut best = Duration::MAX;
348 let iters = if reached_files > 800 { 4 } else { 8 };
349 let mut final_res_ok = resolved_uses;
350 for _ in 0..iters {
351 let t0 = Instant::now();
352 let mut rok = 0usize;
353 for mt in &mod_trees {
354 let dm = CrateDefMap::build_cached(&db, &sources, mt, &[], |fid| parsed.get(fid.0 as usize));
355 rok += dm.resolved_uses.iter().filter(|p| !p.is_empty()).count();
356 black_box(dm);
357 }
358 final_res_ok = rok;
359 best = best.min(t0.elapsed());
360 }
361
362 let denom = reached_files.max(1) as f64;
363 let label = root.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "repo".into());
364 let (ns_f, ms_t, all_f, b_f) =
365 (best.as_nanos() as f64 / denom, best.as_secs_f64() * 1000.0, (allocs.allocs + allocs.reallocs) as f64 / denom, allocs.total_bytes as f64 / denom);
366 println!("{label:<18} files={reached_files:>5} items={total_items:>6} uses={total_uses:>6} (ws+std_ok={final_res_ok:>5}) | def_map={ns_f:>8.1} ns/file ({ms_t:>6.2} ms) | allocs/file={all_f:>5.1} bytes/file={b_f:>7.1}");
367}
368
369fn main() {
370 let mut dirs: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
371 if dirs.is_empty() {
372 let ws = std::env::var("RIDX_WS_SRC")
373 .ok()
374 .map(PathBuf::from)
375 .or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).parent().and_then(Path::parent).map(Path::to_path_buf))
376 .filter(|p| p.parent().is_some() && p.join("Cargo.toml").is_file())
377 .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
378 dirs.push(ws);
379 if let Some(rd) = std::env::var("RIDX_BENCH_REPOS").ok().and_then(|d| std::fs::read_dir(d).ok()) {
380 let mut sub: Vec<PathBuf> = rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
381 sub.sort();
382 dirs.extend(sub);
383 }
384 }
385 for d in dirs {
386 bench_dir(&d);
387 }
388}