Skip to main content

ridx_format/
format.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//! Binary format specifications for the RIDX (.ridx) index file.
12//!
13//! All integer values are stored in little-endian format.
14//! Structures are designed for zero-copy memory-mapped reading with natural alignment.
15
16pub const MAGIC: [u8; 4] = *b"RIDX";
17pub const CURRENT_VERSION: u32 = 5;
18pub const CURRENT_FORMAT_VERSION: u32 = 5;
19pub const EXTRACTOR_VERSION: &str = "0.1.0";
20
21/// Whether a manifest of `format_version` can be opened: versions 3 and 4 read with empty newer tables.
22pub fn is_readable_format_version(format_version: u32) -> bool {
23    (3..=CURRENT_FORMAT_VERSION).contains(&format_version)
24}
25
26pub use crate::driver_hash::*;
27
28mod cfg_item;
29mod defs;
30mod entries;
31mod field_item;
32mod generic_item;
33mod header;
34mod header_legacy;
35mod impl_item;
36mod lang_item;
37mod macro_item;
38mod notes;
39mod ty;
40mod ty_prim;
41mod use_item;
42
43pub use self::cfg_item::{CfgEntry, NO_CFG_VALUE};
44pub use self::defs::{DefEntry, DefKind, Span, FLAG_MACRO_EXPANSION, FLAG_REEXPORT};
45pub use self::entries::{DerefEntry, HashIndexEntry, OwnerIndexEntry, RefEntry, TypeEntry};
46pub use self::field_item::{
47    CtorShape, DefTyEntry, FieldEntry, ItemVis, DEF_TY_FLAG_DEFAULT_ASSOC, DEF_TY_FLAG_FUNDAMENTAL, DEF_TY_FLAG_MUT_STATIC, DEF_TY_FLAG_NON_EXHAUSTIVE, DEF_TY_FLAG_UNSAFE_STATIC,
48    FIELD_FLAG_TUPLE, FIELD_FLAG_UNSAFE,
49};
50pub use self::generic_item::{
51    GenericOwner, GenericParamEntry, GenericParamKind, WherePredEntry, WherePredKind, GENERIC_OWNER_IMPL_BIT, GENERIC_PARAM_FLAG_HAS_DEFAULT, GENERIC_PARAM_FLAG_HOST_EFFECT,
52    GENERIC_PARAM_FLAG_IS_SELF, GENERIC_PARAM_FLAG_SIZED, GENERIC_PARAM_FLAG_SYNTHETIC, WHERE_FLAG_CONST, WHERE_FLAG_HRTB, WHERE_FLAG_NEGATIVE,
53};
54pub use self::header::{FileEntry, Header};
55pub use self::header_legacy::{HeaderV2, HEADER_V3_SIZE, HEADER_V4_SIZE};
56pub use self::impl_item::{AssocTyEntry, ImplEntry, SimplifiedSelfKind, IMPL_FLAG_CONST, IMPL_FLAG_NEGATIVE, IMPL_FLAG_RESERVATION, IMPL_FLAG_TRAIT, IMPL_FLAG_UNSAFE};
57pub use self::lang_item::{LangItemEntry, LangItemKind};
58pub use self::macro_item::{MacroDefEntry, MacroDelim, MacroEdition, MACRO_FLAG_BUILTIN, MACRO_FLAG_EXPORTED, MACRO_FLAG_LOCAL_INNER, MACRO_FLAG_MACRO_RULES};
59pub use self::notes::{NoteEntry, NOTE_CALL_ARGS, NOTE_LAYOUT};
60pub use self::ty::{FnSigEntry, TyBoundEntry, TyDefEntry, TyEntry, TyTag};
61pub use self::ty_prim::{
62    ConstArg, FloatTyWidth, FnAbiKind, GenericArgWord, IntTyWidth, TyDefId, TyId, TyMutability, UintTyWidth, BOUND_FLAG_MAYBE, FN_FLAG_ASYNC, FN_FLAG_CONST, FN_FLAG_HAS_SELF,
63    FN_FLAG_UNSAFE, FN_FLAG_VARIADIC, LIFETIME_ELIDED, LIFETIME_STATIC,
64};
65pub use self::use_item::{UseEntry, UseOwner, UsePrimTy, USE_FLAG_EXTERN_CRATE, USE_FLAG_GLOB, USE_FLAG_PRELUDE, USE_FLAG_PRIM_TY, USE_FLAG_REEXPORT, USE_FLAG_UNDERSCORE};
66
67/// Resolves the global RIDX shared cache directory for external crate dependencies.
68/// Uses `$RIDX_CACHE_DIR` if set, or platform default:
69/// - Unix: `$XDG_CACHE_HOME/ridx/v{CURRENT_VERSION}` or `$HOME/.cache/ridx/v{CURRENT_VERSION}`
70/// - Windows: `%LOCALAPPDATA%/ridx/v{CURRENT_VERSION}` or `$USERPROFILE/.cache/ridx/v{CURRENT_VERSION}`
71pub fn resolve_cache_dir() -> std::path::PathBuf {
72    resolve_cache_dir_with(std::env::var("RIDX_CACHE_DIR").ok().as_deref(), std::env::var("XDG_CACHE_HOME").ok().as_deref(), std::env::var("HOME").ok().as_deref())
73}
74
75pub fn resolve_cache_dir_with(ridx_cache_dir: Option<&str>, xdg_cache_home: Option<&str>, home: Option<&str>) -> std::path::PathBuf {
76    if let Some(dir) = ridx_cache_dir {
77        let p = std::path::PathBuf::from(dir.trim());
78        if !p.as_os_str().is_empty() {
79            return p;
80        }
81    }
82    if let Some(xdg) = xdg_cache_home {
83        let p = std::path::PathBuf::from(xdg.trim());
84        if !p.as_os_str().is_empty() {
85            return p.join("ridx").join(format!("v{}", CURRENT_VERSION));
86        }
87    }
88    if let Some(home) = home {
89        let p = std::path::PathBuf::from(home.trim());
90        if !p.as_os_str().is_empty() {
91            return p.join(".cache").join("ridx").join(format!("v{}", CURRENT_VERSION));
92        }
93    }
94    #[cfg(windows)]
95    if let Ok(local_app_data) = std::env::var("LOCALAPPDATA") {
96        let p = std::path::PathBuf::from(local_app_data.trim());
97        if !p.as_os_str().is_empty() {
98            return p.join("ridx").join(format!("v{}", CURRENT_VERSION));
99        }
100    }
101    std::path::PathBuf::from(".ridx_cache").join(format!("v{}", CURRENT_VERSION))
102}
103
104/// Returns the path to an object shard inside the global cache for a given unit key.
105pub fn cache_object_path(cache_dir: &std::path::Path, unit_key: &str) -> std::path::PathBuf {
106    let prefix = if unit_key.len() >= 2 { &unit_key[..2] } else { "00" };
107    cache_dir.join("objects").join(prefix).join(format!("{}.ridx", unit_key))
108}
109
110/// Joins a base root directory with a relative path, resolving any overlapping path prefix.
111///
112/// For instance, if `root` is `/workspace/crates/app` and `rel` is `crates/app/src/lib.rs`,
113/// naive joining yields `/workspace/crates/app/crates/app/src/lib.rs`.
114/// This helper strips the overlapping `crates/app` prefix to yield `/workspace/crates/app/src/lib.rs`.
115pub fn join_resolving_overlap(root: &std::path::Path, rel: &std::path::Path) -> std::path::PathBuf {
116    if rel.is_absolute() {
117        return rel.to_path_buf();
118    }
119    let normalize_if_dot = |p: std::path::PathBuf| -> std::path::PathBuf {
120        let rel_str = rel.to_string_lossy();
121        if rel_str.contains("..") || rel_str.contains("/.") || rel_str.starts_with("./") {
122            if !crate::workspace::provenance::path_traverses_symlink_parent(&p) {
123                return crate::paths::normalize_path(&p);
124            }
125            if let Ok(canon) = p.canonicalize() {
126                return canon;
127            }
128        }
129        p
130    };
131    let direct = root.join(rel);
132    if direct.exists() {
133        return normalize_if_dot(direct);
134    }
135    let rel_comps: Vec<_> = rel.components().collect();
136    for i in (1..rel_comps.len()).rev() {
137        let prefix: std::path::PathBuf = rel_comps[..i].iter().collect();
138        if root.ends_with(&prefix) {
139            let stripped: std::path::PathBuf = rel_comps[i..].iter().collect();
140            let cand = root.join(stripped);
141            return normalize_if_dot(cand);
142        }
143    }
144    normalize_if_dot(direct)
145}
146
147/// Computes a 64-bit FNV-1a hash over source bytes after stripping UTF-8 BOM and normalizing CRLF to LF,
148/// exactly matching rustc's internal SourceFile.src normalization.
149pub fn normalized_source_hash(bytes: &[u8]) -> u64 {
150    let b = if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) { &bytes[3..] } else { bytes };
151    let mut normalized = Vec::with_capacity(b.len());
152    let mut i = 0;
153    while i < b.len() {
154        if b[i] == b'\r' && i + 1 < b.len() && b[i + 1] == b'\n' {
155            i += 1;
156            continue;
157        }
158        normalized.push(b[i]);
159        i += 1;
160    }
161    fnv1a_64(&normalized)
162}
163
164/// Compile-time layout guarantees to ensure unambiguous on-disk structure sizes.
165const _: () = {
166    assert!(std::mem::size_of::<Header>() == 416);
167    assert!(std::mem::size_of::<CfgEntry>() == 8);
168    assert!(std::mem::align_of::<CfgEntry>() == 4);
169    assert!(std::mem::size_of::<MacroDefEntry>() == 12);
170    assert!(std::mem::align_of::<MacroDefEntry>() == 4);
171    assert!(std::mem::size_of::<NoteEntry>() == 28);
172    assert!(std::mem::align_of::<NoteEntry>() == 4);
173    assert!(std::mem::align_of::<Header>() == 8);
174    assert!(std::mem::size_of::<HeaderV2>() == 128);
175    assert!(std::mem::align_of::<HeaderV2>() == 8);
176    assert!(std::mem::size_of::<Span>() == 20);
177    assert!(std::mem::align_of::<Span>() == 4);
178    assert!(std::mem::size_of::<DefEntry>() == 40);
179    assert!(std::mem::align_of::<DefEntry>() == 4);
180    assert!(std::mem::size_of::<RefEntry>() == 48);
181    assert!(std::mem::align_of::<RefEntry>() == 4);
182    assert!(std::mem::size_of::<TypeEntry>() == 28);
183    assert!(std::mem::align_of::<TypeEntry>() == 4);
184    assert!(std::mem::size_of::<HashIndexEntry>() == 16);
185    assert!(std::mem::align_of::<HashIndexEntry>() == 8);
186    assert!(std::mem::size_of::<OwnerIndexEntry>() == 16);
187    assert!(std::mem::align_of::<OwnerIndexEntry>() == 8);
188    assert!(std::mem::size_of::<DerefEntry>() == 16);
189    assert!(std::mem::align_of::<DerefEntry>() == 8);
190    assert!(std::mem::size_of::<FileEntry>() == 16);
191    assert!(std::mem::align_of::<FileEntry>() == 8);
192    assert!(std::mem::size_of::<TyDefEntry>() == 16);
193    assert!(std::mem::align_of::<TyDefEntry>() == 8);
194    assert!(std::mem::size_of::<TyEntry>() == 16);
195    assert!(std::mem::align_of::<TyEntry>() == 4);
196    assert!(std::mem::size_of::<TyBoundEntry>() == 16);
197    assert!(std::mem::align_of::<TyBoundEntry>() == 4);
198    assert!(std::mem::size_of::<GenericArgWord>() == 4);
199    assert!(std::mem::align_of::<GenericArgWord>() == 4);
200    assert!(std::mem::size_of::<ImplEntry>() == 32);
201    assert!(std::mem::align_of::<ImplEntry>() == 4);
202    assert!(std::mem::size_of::<AssocTyEntry>() == 16);
203    assert!(std::mem::align_of::<AssocTyEntry>() == 4);
204    assert!(std::mem::size_of::<FieldEntry>() == 20);
205    assert!(std::mem::align_of::<FieldEntry>() == 4);
206    assert!(std::mem::size_of::<DefTyEntry>() == 16);
207    assert!(std::mem::align_of::<DefTyEntry>() == 4);
208    assert!(std::mem::size_of::<FnSigEntry>() == 16);
209    assert!(std::mem::align_of::<FnSigEntry>() == 4);
210    assert!(std::mem::size_of::<GenericParamEntry>() == 20);
211    assert!(std::mem::align_of::<GenericParamEntry>() == 4);
212    assert!(std::mem::size_of::<WherePredEntry>() == 28);
213    assert!(std::mem::align_of::<WherePredEntry>() == 4);
214    assert!(std::mem::size_of::<LangItemEntry>() == 12);
215    assert!(std::mem::align_of::<LangItemEntry>() == 4);
216    assert!(std::mem::size_of::<UseEntry>() == 28);
217    assert!(std::mem::align_of::<UseEntry>() == 4);
218};
219
220/// Computes an aggregate 64-bit digest over a map of file paths to their 64-bit source hashes.
221pub fn compute_source_snapshot_digest(file_hashes: &std::collections::HashMap<String, u64>) -> u64 {
222    let mut entries: Vec<(&String, &u64)> = file_hashes.iter().collect();
223    entries.sort_by_key(|(k, _)| *k);
224    let mut buf = Vec::new();
225    for (k, h) in entries {
226        buf.extend_from_slice(k.as_bytes());
227        buf.extend_from_slice(&h.to_le_bytes());
228    }
229    fnv1a_64(&buf)
230}
231
232/// Merges embedded file hashes into a file_hashes map, ensuring embedded hashes are authoritative
233/// across both package-relative and absolute/canonical aliases under `source_root`, and dropping
234/// any conflicting aliases.
235pub fn merge_embedded_hashes_authoritative(
236    file_hashes: &mut std::collections::HashMap<String, u64>,
237    embedded: &std::collections::HashMap<String, u64>,
238    source_root: Option<&std::path::Path>,
239) {
240    let mut canon_dirs: std::collections::HashMap<std::path::PathBuf, Option<std::path::PathBuf>> = std::collections::HashMap::new();
241    let mut resolve_canon = |abs: &std::path::Path, rel_path: &str| -> Option<std::path::PathBuf> {
242        let is_symlink = std::fs::symlink_metadata(abs).is_ok_and(|m| m.file_type().is_symlink());
243        if is_symlink || rel_path.contains("..") {
244            return abs.canonicalize().ok();
245        }
246        let parent = abs.parent()?;
247        let file_name = abs.file_name()?;
248        let canon_parent = canon_dirs.entry(parent.to_path_buf()).or_insert_with(|| parent.canonicalize().ok()).as_ref()?;
249        Some(canon_parent.join(file_name))
250    };
251
252    let mut resolved_embedded: Vec<(&String, u64, Option<std::path::PathBuf>, Option<std::path::PathBuf>)> = Vec::with_capacity(embedded.len());
253    let mut authoritative_by_path: std::collections::HashMap<String, u64> = std::collections::HashMap::with_capacity(embedded.len() * 3);
254    for (rel_path, &h) in embedded {
255        authoritative_by_path.insert(rel_path.clone(), h);
256        if let Some(root) = source_root {
257            let abs = root.join(rel_path);
258            let canon = resolve_canon(&abs, rel_path);
259            authoritative_by_path.insert(abs.to_string_lossy().to_string(), h);
260            if let Some(ref c) = canon {
261                authoritative_by_path.insert(c.to_string_lossy().to_string(), h);
262            }
263            resolved_embedded.push((rel_path, h, Some(abs), canon));
264        } else {
265            resolved_embedded.push((rel_path, h, None, None));
266        }
267    }
268
269    // 1. Drop any conflicting aliases in file_hashes
270    file_hashes.retain(|k, &mut v| {
271        if let Some(&emb_h) = authoritative_by_path.get(k) {
272            return v == emb_h;
273        }
274        let p = std::path::Path::new(k);
275        if let Some(root) = source_root {
276            if let Ok(rel) = p.strip_prefix(root) {
277                if let Some(&emb_h) = embedded.get(rel.to_string_lossy().as_ref()) {
278                    return v == emb_h;
279                }
280            }
281        }
282        true
283    });
284
285    // 2. Authoritatively insert embedded relative paths and their absolute/canonical aliases under source_root
286    for (rel_path, h, abs_opt, canon_opt) in resolved_embedded {
287        file_hashes.insert(rel_path.clone(), h);
288        if let Some(abs) = abs_opt {
289            file_hashes.insert(abs.to_string_lossy().to_string(), h);
290            if let Some(canon) = canon_opt {
291                if canon != abs {
292                    file_hashes.insert(canon.to_string_lossy().to_string(), h);
293                }
294            }
295        }
296    }
297}
298
299/// FNV-1a 64-bit string hash used across the RIDX format.
300#[inline]
301pub fn fnv1a_64(bytes: &[u8]) -> u64 {
302    let mut hash: u64 = 0xcbf29ce484222325;
303    for &b in bytes {
304        hash ^= b as u64;
305        hash = hash.wrapping_mul(0x100000001b3);
306    }
307    hash
308}
309
310#[cfg(test)]
311mod tests;