Skip to main content

ridx_syntax/name_res/
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//! Core `u32`-keyed identifiers and trait boundaries (`SourceDb`, `ItemDb`) decoupling
12//! `ridx-syntax::name_res` from binary index storage (`ridx-format`).
13
14use super::db_impls::{ImplTargetKey, IndexedImpl};
15
16/// Dense crate or compilation-unit identifier (`u32::MAX` = absent sentinel).
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct CrateId(pub u32);
19
20impl CrateId {
21    pub const NONE: Self = Self(u32::MAX);
22    /// Synthetic crate slot used for dirty-file local items not yet present in the compiler index.
23    pub const LOCAL_OVERLAY: Self = Self(u32::MAX - 1);
24
25    #[inline]
26    pub const fn is_some(self) -> bool {
27        self.0 != Self::NONE.0
28    }
29}
30
31impl Default for CrateId {
32    #[inline]
33    fn default() -> Self {
34        Self::NONE
35    }
36}
37
38/// Dense source-file identifier inside a [`SourceDb`].
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct FileId(pub u32);
41
42impl FileId {
43    pub const NONE: Self = Self(u32::MAX);
44
45    #[inline]
46    pub const fn is_some(self) -> bool {
47        self.0 != Self::NONE.0
48    }
49}
50
51impl Default for FileId {
52    #[inline]
53    fn default() -> Self {
54        Self::NONE
55    }
56}
57
58/// Dense module identifier inside a crate's [`super::mod_tree::ModuleTree`].
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
60pub struct ModuleId(pub u32);
61
62impl ModuleId {
63    pub const ROOT: Self = Self(0);
64    pub const NONE: Self = Self(u32::MAX);
65
66    #[inline]
67    pub const fn is_some(self) -> bool {
68        self.0 != Self::NONE.0
69    }
70}
71
72impl Default for ModuleId {
73    #[inline]
74    fn default() -> Self {
75        Self::NONE
76    }
77}
78
79/// Compact 8-byte global definition key (`(CrateId, def_index)`), mapping 1-to-1 to `(shard_idx, def_idx)`
80/// in `WorkspaceIndex` or `(CrateId::LOCAL_OVERLAY, local_idx)` for dirty-file definitions.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
82pub struct GlobalDefId {
83    pub krate: CrateId,
84    pub index: u32,
85}
86
87impl GlobalDefId {
88    pub const NONE: Self = Self { krate: CrateId::NONE, index: u32::MAX };
89
90    #[inline]
91    pub const fn new(krate: CrateId, index: u32) -> Self {
92        Self { krate, index }
93    }
94
95    #[inline]
96    pub const fn is_some(self) -> bool {
97        self.krate.is_some() && self.index != u32::MAX
98    }
99
100    #[inline]
101    pub const fn is_overlay(self) -> bool {
102        self.krate.0 == CrateId::LOCAL_OVERLAY.0 && self.index != u32::MAX
103    }
104}
105
106impl Default for GlobalDefId {
107    #[inline]
108    fn default() -> Self {
109        Self::NONE
110    }
111}
112
113/// Rust language edition of a crate.
114#[repr(u8)]
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
116pub enum Edition {
117    Edition2015 = 0,
118    Edition2018 = 1,
119    #[default]
120    Edition2021 = 2,
121    Edition2024 = 3,
122}
123
124impl Edition {
125    #[inline]
126    pub const fn has_uniform_paths(self) -> bool {
127        (self as u8) >= (Self::Edition2018 as u8)
128    }
129}
130
131/// Visibility class aligned with `ridx-format::ItemVis`, extended with local `super` / `self` forms.
132#[repr(u8)]
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
134pub enum VisKind {
135    Public = 0,
136    Crate = 1,
137    Restricted = 2,
138    #[default]
139    Private = 3,
140    Super = 4,
141}
142
143/// Kind of an indexed or local definition, aligned with `ridx-format::DefKind`.
144#[repr(u8)]
145#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
146pub enum ItemKind {
147    Mod = 0,
148    Struct = 1,
149    Enum = 2,
150    Union = 3,
151    Trait = 4,
152    Fn = 5,
153    TypeAlias = 6,
154    Const = 7,
155    Static = 8,
156    Variant = 9,
157    Field = 10,
158    AssocFn = 11,
159    AssocTy = 12,
160    AssocConst = 13,
161    Macro = 14,
162    Impl = 15,
163    Use = 16,
164    ExternCrate = 17,
165}
166
167impl ItemKind {
168    /// Bitmask of Rust namespaces (`NsMask`) occupied by a definition of this kind.
169    #[inline]
170    pub const fn ns_mask(self, has_value_ctor: bool) -> NsMask {
171        match self {
172            Self::Mod | Self::Enum | Self::Union | Self::Trait | Self::TypeAlias | Self::AssocTy => NsMask::TYPE,
173            Self::Struct | Self::Variant => {
174                if has_value_ctor {
175                    NsMask(NsMask::TYPE.0 | NsMask::VALUE.0)
176                } else {
177                    NsMask::TYPE
178                }
179            }
180            Self::Fn | Self::Const | Self::Static | Self::Field | Self::AssocFn | Self::AssocConst => NsMask::VALUE,
181            Self::Macro => NsMask::MACRO,
182            Self::ExternCrate => NsMask::TYPE,
183            Self::Impl | Self::Use => NsMask::EMPTY,
184        }
185    }
186}
187
188/// Bitmask over the three Rust namespaces (`type`, `value`, `macro`).
189#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
190pub struct NsMask(pub u8);
191
192impl NsMask {
193    pub const EMPTY: Self = Self(0);
194    pub const TYPE: Self = Self(1 << 0);
195    pub const VALUE: Self = Self(1 << 1);
196    pub const MACRO: Self = Self(1 << 2);
197    pub const ALL: Self = Self(Self::TYPE.0 | Self::VALUE.0 | Self::MACRO.0);
198
199    #[inline]
200    pub const fn contains(self, other: Self) -> bool {
201        (self.0 & other.0) == other.0
202    }
203
204    #[inline]
205    pub const fn union(self, other: Self) -> Self {
206        Self(self.0 | other.0)
207    }
208}
209
210/// Indexed definition summary surfaced by [`ItemDb`] for module children and associated items.
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub struct IndexedDef<'a> {
213    pub id: GlobalDefId,
214    pub name: &'a str,
215    pub kind: ItemKind,
216    pub vis: VisKind,
217    pub has_value_ctor: bool,
218}
219
220/// Indexed `use` / re-export row surfaced by [`ItemDb`] (matching `v5` `UseEntry`).
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222pub struct IndexedUse<'a> {
223    pub name: &'a str,
224    pub type_def: GlobalDefId,
225    pub value_def: GlobalDefId,
226    pub macro_def: GlobalDefId,
227    pub vis: VisKind,
228    pub is_glob: bool,
229    pub is_reexport: bool,
230    pub is_prelude: bool,
231    pub is_underscore: bool,
232    pub prim_ty_code: u8,
233}
234
235/// Read-only virtual filesystem / source provider for workspace `.rs` files.
236pub trait SourceDb {
237    /// Maps a forward-slash normalized crate-relative or workspace-relative path to its [`FileId`].
238    fn resolve_path(&self, normalized_path: &str) -> Option<FileId>;
239
240    /// Forward-slash normalized path of `file`.
241    fn file_path(&self, file: FileId) -> &str;
242
243    /// UTF-8 source text of `file` (including any unsaved editor overlay).
244    fn file_text(&self, file: FileId) -> &str;
245}
246
247/// Compiler-index query boundary (`v5` `.ridx` adapter or in-memory test database).
248pub trait ItemDb {
249    /// Returns `true` when bare `#[cfg(key)]` is active for `krate` (e.g. `unix`, `test`).
250    fn cfg_flag(&self, krate: CrateId, key: &str) -> bool;
251
252    /// Returns `true` when `#[cfg(key = "value")]` is active for `krate` (e.g. `feature = "rt"`).
253    fn cfg_key_value(&self, krate: CrateId, key: &str, value: &str) -> bool;
254
255    /// Language edition of `krate`.
256    fn crate_edition(&self, _krate: CrateId) -> Edition {
257        Edition::Edition2021
258    }
259
260    /// Canonical crate name of `krate` (underscores, e.g. `"ridx_syntax"`).
261    fn crate_name(&self, _krate: CrateId) -> &str {
262        ""
263    }
264
265    /// Looks up a compile-time Cargo/rustc environment variable (`OUT_DIR`, `CARGO_MANIFEST_DIR`, ...)
266    /// recorded for `krate`.
267    fn crate_env(&self, _krate: CrateId, _key: &str) -> Option<&str> {
268        None
269    }
270
271    /// Resolves an `include!(...)` target relative to `from_file` (or absolute) to `(FileId, source_text)`
272    /// when a backing [`SourceDb`] is attached to this [`ItemDb`].
273    fn resolve_include_file(&self, _from_file: FileId, _rel_or_abs: &str) -> Option<(FileId, &str)> {
274        None
275    }
276
277    /// Returns the exact byte length of an `include_bytes!(...)` target relative to `from_file` (or absolute).
278    fn include_bytes_len(&self, _from_file: FileId, _rel_or_abs: &str) -> Option<u64> {
279        None
280    }
281
282    /// Resolves an external dependency crate available to `from_krate` under `extern_name`.
283    fn extern_crate(&self, _from_krate: CrateId, _extern_name: &str) -> Option<CrateId> {
284        None
285    }
286
287    /// Appends all external dependency crates visible to `from_krate` as `(extern_name, CrateId)`.
288    fn extern_crates<'a>(&'a self, _from_krate: CrateId, _out: &mut Vec<(&'a str, CrateId)>) {}
289
290    /// Returns the crate root [`GlobalDefId`] of `krate`, if indexed.
291    fn crate_root_def(&self, _krate: CrateId) -> Option<GlobalDefId> {
292        None
293    }
294
295    /// Returns the prelude module [`GlobalDefId`] configured for `krate`, if any.
296    fn prelude_module(&self, _krate: CrateId) -> Option<GlobalDefId> {
297        None
298    }
299
300    /// Looks up a declarative `macro_rules!` body (`($pat) => { $body }; ...`) for item-level
301    /// expansion when `call_path` (e.g. `"cfg_if"` or `"cfg::alloc"`) is invoked in `module_path`.
302    fn macro_rules_body(&self, _krate: CrateId, _module_path: &str, _call_path: &str) -> Option<&str> {
303        None
304    }
305
306    /// Like [`ItemDb::macro_rules_body`], also returning the `$crate` substitution token
307    /// (`"crate"` for crate-local macros or the dependency crate alias for external macros).
308    fn macro_rules_with_crate(&self, krate: CrateId, module_path: &str, call_path: &str) -> Option<(&str, &str)> {
309        self.macro_rules_body(krate, module_path, call_path).map(|b| (b, "crate"))
310    }
311
312    /// Looks up the declarative `macro_rules!` `(body, dollar_crate)` for a resolved macro [`GlobalDefId`]
313    /// invoked inside `from_krate`.
314    fn macro_rules_by_def(&self, _from_krate: CrateId, _def: GlobalDefId) -> Option<(&str, &str)> {
315        None
316    }
317
318    /// Returns the [`ItemKind`] of an indexed [`GlobalDefId`], if known (`O(1)` in `.ridx`).
319    fn def_kind(&self, _def: GlobalDefId) -> Option<ItemKind> {
320        None
321    }
322
323    /// Returns the defining workspace [`FileId`] of `def` (`FileId::NONE` for external crates).
324    fn def_file(&self, _def: GlobalDefId) -> FileId {
325        FileId::NONE
326    }
327
328    /// Underlying [`ImplTargetKey`] of an indexed `type Alias = Target;` (`None` if not an alias or unknown).
329    fn type_alias_target(&self, _alias_def: GlobalDefId) -> Option<ImplTargetKey> {
330        None
331    }
332
333    /// Appends indexed `impl` blocks matching `target` across `krate` + visible dependency crates.
334    fn impls_for_target(&self, _target: ImplTargetKey, _out: &mut Vec<IndexedImpl>) {}
335
336    /// Appends indexed `impl` blocks defined inside `krate`.
337    fn crate_impls(&self, _krate: CrateId, _out: &mut Vec<IndexedImpl>) {}
338
339    /// Appends direct child definitions of `module_def` into `out`.
340    fn module_defs<'a>(&'a self, _module_def: GlobalDefId, _out: &mut Vec<IndexedDef<'a>>) {}
341
342    /// Appends variants of an indexed `enum_def` into `out` (defaults to `module_defs`).
343    fn enum_variants<'a>(&'a self, enum_def: GlobalDefId, out: &mut Vec<IndexedDef<'a>>) {
344        self.module_defs(enum_def, out);
345    }
346
347    /// Appends `UseEntry` rows belonging to `module_def` (or crate root) into `out`.
348    fn module_uses<'a>(&'a self, _module_def: GlobalDefId, _out: &mut Vec<IndexedUse<'a>>) {}
349
350    /// Appends inherent and trait associated items on `owner_def` into `out`.
351    fn assoc_items<'a>(&'a self, _owner_def: GlobalDefId, _out: &mut Vec<IndexedDef<'a>>) {}
352
353    /// Appends direct supertrait [`GlobalDefId`]s declared on `trait_def` (`trait Sub: Super`).
354    fn trait_supertraits(&self, _trait_def: GlobalDefId, _out: &mut Vec<GlobalDefId>) {}
355
356    /// Resolves a named field on `adt_or_variant_def` (`Struct`, `Union`, or `Variant`), if indexed.
357    fn adt_field(&self, _adt_or_variant_def: GlobalDefId, _field_name: &str) -> Option<GlobalDefId> {
358        None
359    }
360
361    /// Resolves an indexed definition in `(krate, file)` whose identifier byte span is `[start..end)`.
362    fn def_at_byte_span(&self, _krate: CrateId, _file: FileId, _start: u32, _end: u32) -> GlobalDefId {
363        GlobalDefId::NONE
364    }
365
366    /// Looks up a lang item (`u16` discriminant matching `LangItemKind`) across visible shards.
367    fn lang_item(&self, _lang_kind: u16) -> Option<GlobalDefId> {
368        None
369    }
370}