Skip to main content

ridx_format/
writer.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//! Builder and serializer for the RIDX binary index format.
12
13use std::collections::{HashMap, HashSet};
14
15use crate::format::*;
16
17mod encode;
18mod typed;
19mod typed_cfg;
20pub(crate) mod typed_generics;
21mod typed_macro;
22
23pub use self::typed_macro::RawMacroDef;
24
25#[cfg(test)]
26use self::encode::align_up;
27/// Raw definition to be added to the index builder.
28#[derive(Debug, Clone)]
29pub struct RawDefinition {
30    pub def_id: u32,
31    pub kind: DefKind,
32    pub visibility: u8,
33    pub is_macro_expansion: bool,
34    pub name: String,
35    pub path: String,
36    pub signature: Option<String>,
37    pub file: String,
38    pub start_line: u32,
39    pub start_col: u32,
40    pub end_line: u32,
41    pub end_col: u32,
42}
43
44/// Raw reference to be added to the index builder.
45#[derive(Debug, Clone)]
46pub struct RawReference {
47    pub file: String,
48    pub start_line: u32,
49    pub start_col: u32,
50    pub end_line: u32,
51    pub end_col: u32,
52    pub target_def_id: Option<u32>,
53    pub target_path: String,
54    pub target_file: Option<String>,
55    pub target_unit: Option<String>,
56    pub target_line: u32,
57    pub target_col: u32,
58    pub kind: DefKind,
59    pub is_write: bool,
60    pub is_macro_expansion: bool,
61}
62
63/// Raw expression type to be added to the index builder.
64#[derive(Debug, Clone)]
65pub struct RawType {
66    pub file: String,
67    pub start_line: u32,
68    pub start_col: u32,
69    pub end_line: u32,
70    pub end_col: u32,
71    pub type_name: String,
72}
73
74/// Raw note to be added to the index builder: a text about a span (see `NOTE_CALL_ARGS`, `NOTE_LAYOUT`).
75#[derive(Debug, Clone)]
76pub struct RawNote {
77    pub file: String,
78    pub start_line: u32,
79    pub start_col: u32,
80    pub end_line: u32,
81    pub end_col: u32,
82    pub kind: u32,
83    pub text: String,
84}
85
86/// In-memory builder for constructing and serializing `.ridx` files.
87pub struct IndexWriter {
88    crate_name: String,
89    crate_version: String,
90
91    /// Interned string bytes (null-terminated UTF-8 strings)
92    string_pool: Vec<u8>,
93    string_map: HashMap<String, u32>,
94
95    /// Files table: maps file path string to file ID
96    file_map: HashMap<String, u32>,
97    file_offsets: Vec<u32>,
98
99    definitions: Vec<RawDefinition>,
100    def_owners: Vec<(u32, String)>,
101    references: Vec<RawReference>,
102    types: Vec<(RawType, Option<String>)>,
103    derefs: Vec<(String, String)>,
104    notes: Vec<RawNote>,
105    ty_interner: crate::ty_arena::TyInterner,
106    fn_sigs: Vec<FnSigEntry>,
107    impls: Vec<typed::PendingImpl>,
108    fields: Vec<FieldEntry>,
109    def_tys: Vec<DefTyEntry>,
110    def_generic_params: Vec<GenericParamEntry>,
111    def_where_preds: Vec<WherePredEntry>,
112    lang_items: Vec<LangItemEntry>,
113    uses: Vec<UseEntry>,
114    cfgs: Vec<CfgEntry>,
115    macro_defs: Vec<MacroDefEntry>,
116    target_triple: Option<String>,
117    unit_key: Option<String>,
118    generation: Option<String>,
119    file_hashes: HashMap<String, u64>,
120    reexport_indices: HashSet<u32>,
121}
122
123impl IndexWriter {
124    pub fn new(crate_name: impl Into<String>, crate_version: impl Into<String>) -> Self {
125        let mut writer = Self {
126            crate_name: crate_name.into(),
127            crate_version: crate_version.into(),
128            string_pool: Vec::with_capacity(64 * 1024),
129            string_map: HashMap::new(),
130            file_map: HashMap::new(),
131            file_offsets: Vec::new(),
132            definitions: Vec::new(),
133            def_owners: Vec::new(),
134            references: Vec::new(),
135            types: Vec::new(),
136            derefs: Vec::new(),
137            notes: Vec::new(),
138            ty_interner: crate::ty_arena::TyInterner::new(),
139            fn_sigs: Vec::new(),
140            impls: Vec::new(),
141            fields: Vec::new(),
142            def_tys: Vec::new(),
143            def_generic_params: Vec::new(),
144            def_where_preds: Vec::new(),
145            lang_items: Vec::new(),
146            uses: Vec::new(),
147            cfgs: Vec::new(),
148            macro_defs: Vec::new(),
149            target_triple: None,
150            unit_key: None,
151            generation: None,
152            file_hashes: HashMap::new(),
153            reexport_indices: HashSet::new(),
154        };
155        // Offset 0 is reserved for empty string
156        writer.string_pool.push(0);
157        writer.string_map.insert(String::new(), 0);
158        writer
159    }
160}
161
162impl Default for IndexWriter {
163    fn default() -> Self {
164        Self::new("", "")
165    }
166}
167
168impl IndexWriter {
169    /// Sets the compilation unit key for this index shard.
170    pub fn set_unit_key(&mut self, unit_key: impl Into<String>) {
171        self.unit_key = Some(unit_key.into());
172    }
173
174    /// Returns the compilation unit key if set.
175    pub fn unit_key(&self) -> Option<&str> {
176        self.unit_key.as_deref()
177    }
178
179    /// Sets the source snapshot generation digest for this index shard.
180    pub fn set_generation(&mut self, generation: impl Into<String>) {
181        self.generation = Some(generation.into());
182    }
183
184    /// Returns the source snapshot generation digest if set.
185    pub fn generation(&self) -> Option<&str> {
186        self.generation.as_deref()
187    }
188
189    /// Sets the source file provenance hashes for files indexed in this shard.
190    pub fn set_file_hashes(&mut self, hashes: HashMap<String, u64>) {
191        self.file_hashes = hashes;
192    }
193
194    /// Records or updates the source text provenance hash for a single indexed file.
195    pub fn add_file_hash(&mut self, file: &str, hash: u64) {
196        self.file_hashes.insert(file.to_string(), hash);
197    }
198
199    /// Intern a string into the pool, returning its byte offset.
200    /// Offset 0 is always reserved for the empty string (and used as a sentinel for 'no owner').
201    pub fn intern_string(&mut self, s: &str) -> u32 {
202        Self::intern_in_pool(&mut self.string_pool, &mut self.string_map, s)
203    }
204
205    pub(crate) fn intern_in_pool(string_pool: &mut Vec<u8>, string_map: &mut HashMap<String, u32>, s: &str) -> u32 {
206        if string_pool.is_empty() {
207            string_pool.push(0);
208            string_map.insert(String::new(), 0);
209        }
210        if let Some(&offset) = string_map.get(s) {
211            return offset;
212        }
213        let offset = string_pool.len() as u32;
214        string_pool.extend_from_slice(s.as_bytes());
215        string_pool.push(0); // Null terminator
216        string_map.insert(s.to_string(), offset);
217        offset
218    }
219
220    /// Get or assign a numeric ID for a file path.
221    pub fn get_or_insert_file(&mut self, path: &str) -> u32 {
222        if let Some(&id) = self.file_map.get(path) {
223            return id;
224        }
225        let id = self.file_offsets.len() as u32;
226        let offset = self.intern_string(path);
227        self.file_offsets.push(offset);
228        self.file_map.insert(path.to_string(), id);
229        id
230    }
231
232    pub fn add_definition(&mut self, def: RawDefinition) -> u32 {
233        let idx = self.definitions.len() as u32;
234        if let Some((parent, _)) = def.path.rsplit_once("::") {
235            if !parent.is_empty() {
236                self.def_owners.push((idx, parent.to_string()));
237            }
238        }
239        self.definitions.push(def);
240        idx
241    }
242
243    /// Adds a definition without registering its lexical parent in the legacy `defs_by_owner`
244    /// table (used for nightly-`#[unstable]` sysroot lang items materialized strictly for v5
245    /// `lang_items` / `fn_sigs` / `where_preds`).
246    pub fn add_definition_unowned(&mut self, def: RawDefinition) -> u32 {
247        let idx = self.definitions.len() as u32;
248        self.definitions.push(def);
249        idx
250    }
251
252    pub fn add_definition_with_owners(&mut self, def: RawDefinition, owners: Vec<String>) -> u32 {
253        let idx = self.definitions.len() as u32;
254        for owner in owners {
255            if !owner.is_empty() {
256                self.def_owners.push((idx, owner));
257            }
258        }
259        // Also add module parent if not present
260        if let Some((parent, _)) = def.path.rsplit_once("::") {
261            if !parent.is_empty() {
262                self.def_owners.push((idx, parent.to_string()));
263            }
264        }
265        self.definitions.push(def);
266        idx
267    }
268
269    /// Adds a definition marked with FLAG_REEXPORT and associates it with owners.
270    pub fn add_reexport_with_owners(&mut self, def: RawDefinition, owners: Vec<String>) -> u32 {
271        let idx = self.definitions.len() as u32;
272        self.reexport_indices.insert(idx);
273        self.add_definition_with_owners(def, owners)
274    }
275
276    pub fn add_def_owner(&mut self, def_id: u32, owner: String) {
277        if let Some(idx) = self.definitions.iter().position(|d| d.def_id == def_id) {
278            self.def_owners.push((idx as u32, owner));
279        }
280    }
281
282    pub fn add_def_owner_by_index(&mut self, idx: u32, owner: String) {
283        debug_assert!((idx as usize) < self.definitions.len(), "def index {idx} out of bounds");
284        if (idx as usize) < self.definitions.len() && !owner.is_empty() {
285            self.def_owners.push((idx, owner));
286        }
287    }
288
289    pub fn add_reference(&mut self, r: RawReference) {
290        self.references.push(r);
291    }
292
293    pub fn add_type(&mut self, t: RawType) {
294        self.types.push((t, None));
295    }
296
297    pub fn add_type_with_owner(&mut self, t: RawType, owner_path: Option<String>) {
298        self.types.push((t, owner_path));
299    }
300
301    pub fn add_deref(&mut self, source_type: impl Into<String>, target_type: impl Into<String>) {
302        self.derefs.push((source_type.into(), target_type.into()));
303    }
304
305    pub fn add_note(&mut self, note: RawNote) {
306        self.notes.push(note);
307    }
308
309    /// Total count of notes queued.
310    pub fn note_count(&self) -> usize {
311        self.notes.len()
312    }
313
314    /// Total count of definitions queued.
315    pub fn definition_count(&self) -> usize {
316        self.definitions.len()
317    }
318
319    /// Total count of references queued.
320    pub fn reference_count(&self) -> usize {
321        self.references.len()
322    }
323
324    /// Total count of types queued.
325    pub fn type_count(&self) -> usize {
326        self.types.len()
327    }
328
329    /// Total count of deref mappings queued.
330    pub fn deref_count(&self) -> usize {
331        self.derefs.len()
332    }
333
334    /// Returns all unique file paths known to this writer.
335    pub fn indexed_files(&self) -> Vec<String> {
336        let mut set = std::collections::HashSet::new();
337        for k in self.file_map.keys() {
338            set.insert(k.clone());
339        }
340        for def in &self.definitions {
341            set.insert(def.file.clone());
342        }
343        for r in &self.references {
344            set.insert(r.file.clone());
345        }
346        for t in &self.types {
347            set.insert(t.0.file.clone());
348        }
349        let mut list: Vec<String> = set.into_iter().collect();
350        list.sort();
351        list
352    }
353}
354
355#[cfg(test)]
356mod tests;