Skip to main content

ridx_syntax/name_res/
mem_db.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//! Fast in-memory [`SourceDb`] and [`ItemDb`] implementations for standalone tests,
12//! workspace benchmarks, and overlay verification without requiring `ridx-format`.
13
14use std::collections::HashMap;
15
16use super::db::{CrateId, Edition, FileId, GlobalDefId, IndexedDef, IndexedUse, ItemDb, SourceDb};
17use super::db_impls::{ImplTargetKey, IndexedImpl};
18use super::mod_tree::join_norm_path;
19
20/// In-memory source file table keyed by normalized `/` path.
21#[derive(Clone, Debug, Default)]
22pub struct MemSourceDb {
23    paths: Vec<String>,
24    texts: Vec<String>,
25    by_path: HashMap<String, FileId>,
26}
27
28impl MemSourceDb {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn with_capacity(cap: usize) -> Self {
34        Self { paths: Vec::with_capacity(cap), texts: Vec::with_capacity(cap), by_path: HashMap::with_capacity(cap) }
35    }
36
37    /// Inserts or overwrites `path` (normalized to forward slashes) and returns its [`FileId`].
38    pub fn add_file(&mut self, path: &str, text: impl Into<String>) -> FileId {
39        let norm = join_norm_path("", path);
40        if let Some(&existing) = self.by_path.get(&norm) {
41            self.texts[existing.0 as usize] = text.into();
42            return existing;
43        }
44        let id = FileId(self.paths.len() as u32);
45        self.by_path.insert(norm.clone(), id);
46        self.paths.push(norm);
47        self.texts.push(text.into());
48        id
49    }
50
51    #[inline]
52    pub fn len(&self) -> usize {
53        self.paths.len()
54    }
55    #[inline]
56    pub fn is_empty(&self) -> bool {
57        self.paths.is_empty()
58    }
59}
60
61impl SourceDb for MemSourceDb {
62    #[inline]
63    fn resolve_path(&self, normalized_path: &str) -> Option<FileId> {
64        self.by_path.get(normalized_path).copied()
65    }
66    #[inline]
67    fn file_path(&self, file: FileId) -> &str {
68        &self.paths[file.0 as usize]
69    }
70    #[inline]
71    fn file_text(&self, file: FileId) -> &str {
72        &self.texts[file.0 as usize]
73    }
74}
75
76#[derive(Clone, Debug, Default)]
77struct CrateMemEntry {
78    name: String,
79    edition: Edition,
80    /// Sorted bare cfg flags (`unix`, `test`, `debug_assertions`, ...).
81    cfg_flags: Vec<String>,
82    /// Sorted `(key, value)` pairs (`("feature", "rt")`, `("target_os", "linux")`, ...).
83    cfg_kvs: Vec<(String, String)>,
84    /// Optional indexed `macro_rules!` bodies keyed by call path (`"cfg_if"`, `"cfg::alloc"`).
85    macros: HashMap<String, String>,
86    envs: HashMap<String, String>,
87    externs: HashMap<String, CrateId>,
88    root_def: Option<GlobalDefId>,
89    prelude_mod: Option<GlobalDefId>,
90}
91
92/// In-memory [`ItemDb`] backing `cfg` evaluation, crate metadata, and indexed test fixtures.
93#[derive(Clone, Debug, Default)]
94pub struct MemItemDb {
95    crates: HashMap<CrateId, CrateMemEntry>,
96    def_kinds: HashMap<GlobalDefId, super::db::ItemKind>,
97    def_files: HashMap<GlobalDefId, FileId>,
98    alias_targets: HashMap<GlobalDefId, ImplTargetKey>,
99    module_defs: HashMap<GlobalDefId, Vec<OwnedDef>>,
100    module_uses: HashMap<GlobalDefId, Vec<OwnedUse>>,
101    assoc_items: HashMap<GlobalDefId, Vec<OwnedDef>>,
102    supertraits: HashMap<GlobalDefId, Vec<GlobalDefId>>,
103    impls_by_target: HashMap<ImplTargetKey, Vec<IndexedImpl>>,
104    impls_by_crate: HashMap<CrateId, Vec<IndexedImpl>>,
105    lang_items: HashMap<u16, GlobalDefId>,
106    macro_defs: HashMap<GlobalDefId, (String, String)>,
107    include_files: HashMap<(FileId, String), (FileId, String)>,
108    include_bytes: HashMap<(FileId, String), u64>,
109}
110
111#[derive(Clone, Debug)]
112pub struct OwnedDef {
113    pub id: GlobalDefId,
114    pub name: String,
115    pub kind: super::db::ItemKind,
116    pub vis: super::db::VisKind,
117    pub has_value_ctor: bool,
118}
119
120#[derive(Clone, Debug)]
121pub struct OwnedUse {
122    pub name: String,
123    pub type_def: GlobalDefId,
124    pub value_def: GlobalDefId,
125    pub macro_def: GlobalDefId,
126    pub vis: super::db::VisKind,
127    pub is_glob: bool,
128    pub is_reexport: bool,
129    pub is_prelude: bool,
130    pub is_underscore: bool,
131    pub prim_ty_code: u8,
132}
133
134impl MemItemDb {
135    pub fn new() -> Self {
136        Self::default()
137    }
138
139    pub fn add_crate(&mut self, name: impl Into<String>, edition: Edition) -> CrateId {
140        let id = CrateId(self.crates.len() as u32);
141        self.set_crate(id, name, edition);
142        id
143    }
144
145    pub fn set_crate(&mut self, krate: CrateId, name: impl Into<String>, edition: Edition) {
146        let e = self.crates.entry(krate).or_default();
147        e.name = name.into();
148        e.edition = edition;
149    }
150
151    pub fn add_cfg_flag(&mut self, krate: CrateId, key: impl Into<String>) {
152        let k = key.into();
153        let list = &mut self.crates.entry(krate).or_default().cfg_flags;
154        if let Err(pos) = list.binary_search(&k) {
155            list.insert(pos, k);
156        }
157    }
158
159    pub fn add_cfg_kv(&mut self, krate: CrateId, key: impl Into<String>, value: impl Into<String>) {
160        let pair = (key.into(), value.into());
161        let list = &mut self.crates.entry(krate).or_default().cfg_kvs;
162        if let Err(pos) = list.binary_search(&pair) {
163            list.insert(pos, pair);
164        }
165    }
166
167    pub fn add_macro_rules(&mut self, krate: CrateId, call_path: impl Into<String>, body: impl Into<String>) {
168        self.crates.entry(krate).or_default().macros.insert(call_path.into(), body.into());
169    }
170
171    pub fn add_macro_def_body(&mut self, def: GlobalDefId, body: impl Into<String>, dollar_crate: impl Into<String>) {
172        self.def_kinds.insert(def, super::db::ItemKind::Macro);
173        self.macro_defs.insert(def, (body.into(), dollar_crate.into()));
174    }
175
176    pub fn set_env(&mut self, krate: CrateId, key: impl Into<String>, value: impl Into<String>) {
177        self.crates.entry(krate).or_default().envs.insert(key.into(), value.into());
178    }
179
180    pub fn add_extern_crate(&mut self, from_krate: CrateId, extern_name: impl Into<String>, target: CrateId) {
181        self.crates.entry(from_krate).or_default().externs.insert(extern_name.into(), target);
182    }
183
184    pub fn set_crate_root_def(&mut self, krate: CrateId, def: GlobalDefId) {
185        self.crates.entry(krate).or_default().root_def = Some(def);
186        self.def_kinds.entry(def).or_insert(super::db::ItemKind::Mod);
187    }
188
189    pub fn set_prelude_module(&mut self, krate: CrateId, prelude: GlobalDefId) {
190        self.crates.entry(krate).or_default().prelude_mod = Some(prelude);
191        self.def_kinds.entry(prelude).or_insert(super::db::ItemKind::Mod);
192    }
193
194    pub fn set_def_kind(&mut self, def: GlobalDefId, kind: super::db::ItemKind) {
195        self.def_kinds.insert(def, kind);
196    }
197
198    pub fn set_def_file(&mut self, def: GlobalDefId, file: FileId) {
199        self.def_files.insert(def, file);
200    }
201
202    pub fn set_type_alias_target(&mut self, alias_def: GlobalDefId, target: ImplTargetKey) {
203        self.alias_targets.insert(alias_def, target);
204    }
205
206    pub fn add_impl(&mut self, imp: IndexedImpl) {
207        self.def_kinds.insert(imp.id, super::db::ItemKind::Impl);
208        if imp.file.is_some() {
209            self.def_files.insert(imp.id, imp.file);
210        }
211        self.impls_by_target.entry(imp.target).or_default().push(imp);
212        self.impls_by_crate.entry(imp.id.krate).or_default().push(imp);
213    }
214
215    pub fn add_module_def_in_file(&mut self, module_def: GlobalDefId, file: FileId, def: OwnedDef) {
216        if file.is_some() {
217            self.def_files.insert(def.id, file);
218        }
219        self.add_module_def(module_def, def);
220    }
221
222    pub fn add_module_def(&mut self, module_def: GlobalDefId, def: OwnedDef) {
223        self.def_kinds.entry(module_def).or_insert(super::db::ItemKind::Mod);
224        self.def_kinds.insert(def.id, def.kind);
225        self.module_defs.entry(module_def).or_default().push(def);
226    }
227
228    pub fn add_module_use(&mut self, module_def: GlobalDefId, u: OwnedUse) {
229        self.module_uses.entry(module_def).or_default().push(u);
230    }
231
232    pub fn add_assoc_item(&mut self, owner_def: GlobalDefId, item: OwnedDef) {
233        self.def_kinds.insert(item.id, item.kind);
234        self.assoc_items.entry(owner_def).or_default().push(item);
235    }
236
237    pub fn add_trait_supertrait(&mut self, trait_def: GlobalDefId, super_def: GlobalDefId) {
238        self.supertraits.entry(trait_def).or_default().push(super_def);
239    }
240
241    pub fn set_lang_item(&mut self, lang_kind: u16, def: GlobalDefId) {
242        self.lang_items.insert(lang_kind, def);
243    }
244    pub fn set_include_file(&mut self, from_file: FileId, rel_or_abs: impl Into<String>, target_file: FileId, text: impl Into<String>) {
245        self.include_files.insert((from_file, rel_or_abs.into()), (target_file, text.into()));
246    }
247    pub fn set_include_bytes_len(&mut self, from_file: FileId, rel_or_abs: impl Into<String>, len: u64) {
248        self.include_bytes.insert((from_file, rel_or_abs.into()), len);
249    }
250}
251
252impl ItemDb for MemItemDb {
253    #[inline]
254    fn cfg_flag(&self, krate: CrateId, key: &str) -> bool {
255        self.crates.get(&krate).is_some_and(|c| c.cfg_flags.binary_search_by(|k| k.as_str().cmp(key)).is_ok())
256    }
257    #[inline]
258    fn cfg_key_value(&self, krate: CrateId, key: &str, value: &str) -> bool {
259        self.crates.get(&krate).is_some_and(|c| c.cfg_kvs.binary_search_by(|(k, v)| k.as_str().cmp(key).then_with(|| v.as_str().cmp(value))).is_ok())
260    }
261    #[inline]
262    fn crate_edition(&self, krate: CrateId) -> Edition {
263        self.crates.get(&krate).map_or(Edition::Edition2021, |c| c.edition)
264    }
265    #[inline]
266    fn crate_name(&self, krate: CrateId) -> &str {
267        self.crates.get(&krate).map_or("", |c| c.name.as_str())
268    }
269    #[inline]
270    fn crate_env(&self, krate: CrateId, key: &str) -> Option<&str> {
271        self.crates.get(&krate)?.envs.get(key).map(String::as_str)
272    }
273    #[inline]
274    fn resolve_include_file(&self, from_file: FileId, rel_or_abs: &str) -> Option<(FileId, &str)> {
275        self.include_files.get(&(from_file, rel_or_abs.to_owned())).map(|(f, s)| (*f, s.as_str()))
276    }
277    #[inline]
278    fn include_bytes_len(&self, from_file: FileId, rel_or_abs: &str) -> Option<u64> {
279        self.include_bytes.get(&(from_file, rel_or_abs.to_owned())).copied()
280    }
281
282    #[inline]
283    fn extern_crate(&self, from_krate: CrateId, extern_name: &str) -> Option<CrateId> {
284        self.crates.get(&from_krate)?.externs.get(extern_name).copied()
285    }
286
287    fn extern_crates<'a>(&'a self, from_krate: CrateId, out: &mut Vec<(&'a str, CrateId)>) {
288        if let Some(c) = self.crates.get(&from_krate) {
289            out.extend(c.externs.iter().map(|(k, &v)| (k.as_str(), v)));
290        }
291    }
292
293    #[inline]
294    fn crate_root_def(&self, krate: CrateId) -> Option<GlobalDefId> {
295        self.crates.get(&krate)?.root_def
296    }
297
298    #[inline]
299    fn prelude_module(&self, krate: CrateId) -> Option<GlobalDefId> {
300        self.crates.get(&krate)?.prelude_mod
301    }
302
303    #[inline]
304    fn macro_rules_body(&self, krate: CrateId, _module_path: &str, call_path: &str) -> Option<&str> {
305        let m = &self.crates.get(&krate)?.macros;
306        m.get(call_path).or_else(|| call_path.rsplit("::").next().and_then(|s| m.get(s))).map(String::as_str)
307    }
308
309    #[inline]
310    fn macro_rules_by_def(&self, from_krate: CrateId, def: GlobalDefId) -> Option<(&str, &str)> {
311        let (body, dc) = self.macro_defs.get(&def)?;
312        let eff_dc = if def.krate == from_krate { "crate" } else { dc.as_str() };
313        Some((body.as_str(), eff_dc))
314    }
315
316    #[inline]
317    fn def_kind(&self, def: GlobalDefId) -> Option<super::db::ItemKind> {
318        self.def_kinds.get(&def).copied()
319    }
320
321    #[inline]
322    fn def_file(&self, def: GlobalDefId) -> FileId {
323        self.def_files.get(&def).copied().unwrap_or(FileId::NONE)
324    }
325
326    #[inline]
327    fn type_alias_target(&self, alias_def: GlobalDefId) -> Option<ImplTargetKey> {
328        self.alias_targets.get(&alias_def).copied()
329    }
330
331    fn impls_for_target(&self, target: ImplTargetKey, out: &mut Vec<IndexedImpl>) {
332        if let Some(list) = self.impls_by_target.get(&target) {
333            out.extend_from_slice(list);
334        }
335    }
336
337    fn crate_impls(&self, krate: CrateId, out: &mut Vec<IndexedImpl>) {
338        if let Some(list) = self.impls_by_crate.get(&krate) {
339            out.extend_from_slice(list);
340        }
341    }
342
343    fn module_defs<'a>(&'a self, module_def: GlobalDefId, out: &mut Vec<IndexedDef<'a>>) {
344        if let Some(list) = self.module_defs.get(&module_def) {
345            out.extend(list.iter().map(|d| IndexedDef { id: d.id, name: &d.name, kind: d.kind, vis: d.vis, has_value_ctor: d.has_value_ctor }));
346        }
347    }
348
349    fn enum_variants<'a>(&'a self, enum_def: GlobalDefId, out: &mut Vec<IndexedDef<'a>>) {
350        self.module_defs(enum_def, out);
351        if let Some(list) = self.assoc_items.get(&enum_def) {
352            out.extend(list.iter().filter(|d| d.kind == super::db::ItemKind::Variant).map(|d| IndexedDef {
353                id: d.id,
354                name: &d.name,
355                kind: d.kind,
356                vis: d.vis,
357                has_value_ctor: d.has_value_ctor,
358            }));
359        }
360    }
361
362    fn module_uses<'a>(&'a self, module_def: GlobalDefId, out: &mut Vec<IndexedUse<'a>>) {
363        if let Some(list) = self.module_uses.get(&module_def) {
364            out.extend(list.iter().map(|u| IndexedUse {
365                name: &u.name,
366                type_def: u.type_def,
367                value_def: u.value_def,
368                macro_def: u.macro_def,
369                vis: u.vis,
370                is_glob: u.is_glob,
371                is_reexport: u.is_reexport,
372                is_prelude: u.is_prelude,
373                is_underscore: u.is_underscore,
374                prim_ty_code: u.prim_ty_code,
375            }));
376        }
377    }
378
379    fn assoc_items<'a>(&'a self, owner_def: GlobalDefId, out: &mut Vec<IndexedDef<'a>>) {
380        if let Some(list) = self.assoc_items.get(&owner_def) {
381            out.extend(list.iter().map(|d| IndexedDef { id: d.id, name: &d.name, kind: d.kind, vis: d.vis, has_value_ctor: d.has_value_ctor }));
382        }
383    }
384
385    fn trait_supertraits(&self, trait_def: GlobalDefId, out: &mut Vec<GlobalDefId>) {
386        if let Some(list) = self.supertraits.get(&trait_def) {
387            out.extend_from_slice(list);
388        }
389    }
390
391    fn adt_field(&self, adt_or_variant_def: GlobalDefId, field_name: &str) -> Option<GlobalDefId> {
392        self.assoc_items.get(&adt_or_variant_def)?.iter().find(|d| d.kind == super::db::ItemKind::Field && d.name == field_name).map(|d| d.id)
393    }
394
395    fn lang_item(&self, lang_kind: u16) -> Option<GlobalDefId> {
396        self.lang_items.get(&lang_kind).copied()
397    }
398}