Skip to main content

ridx_format/
lib.rs

1/*
2 * rust-intelligence — Compiler-backed, mmap-indexed 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//! # ridx-format
12//!
13//! Compact, zero-copy binary index format and reader/writer for Rust Intelligence.
14//!
15//! Provides ultra-low latency (<50 µs) code navigation (go to definition, find references,
16//! hover/type-at) using memory-mapped `.ridx` files without persistent background daemon RSS.
17
18pub mod audit;
19pub mod driver_hash;
20pub mod format;
21pub(crate) mod paths;
22pub mod reader;
23pub mod relocate;
24pub mod ty_arena;
25pub mod workspace;
26pub mod writer;
27
28pub use format::*;
29pub use paths::{canonicalize_best_effort, canonicalize_cached, normalize_path};
30pub use reader::{IndexReader, MacroDefView, ResolvedDefinition};
31pub use ty_arena::{
32    AssocBindingIter, AssocBindingView, AssocTyIter, AssocTyView, DefTyView, FieldIter, FieldView, FnSigView, GenericArgIter, GenericArgView, GenericParamIter, GenericParamView,
33    ImplIter, ImplView, LangItemIter, LangItemView, RawAssocTy, RawDefTy, RawField, RawFnSig, RawGenericArg, RawGenericParam, RawImpl, RawLangItem, RawTy, RawTyBound, RawTyDef,
34    RawUse, RawWherePred, TyArenaView, TyBoundIter, TyBoundView, TyDefView, TyInterner, TyKindView, TyListIter, U32ListIter, UseIter, UseView, WherePredIter, WherePredView,
35};
36pub use workspace::*;
37pub use writer::{IndexWriter, RawDefinition, RawMacroDef, RawNote, RawReference, RawType};
38
39/// `=1` in the driver's environment: no build script or procedural macro is executed while indexing (prod-code,
40/// m=20739).
41pub const NO_BUILD_ENV: &str = "RIDX_NO_BUILD_SCRIPTS";
42/// The start of the name of the Cargo target directory of an index built so: the procedural macros the driver loads
43/// then are only stubs built under it.
44pub const NO_BUILD_DIR_PREFIX: &str = "nobuild-";
45/// The start of the name of the source the driver compiles in place of a dependency that did not compile
46/// (`ridx-stand-in-<crate><extra-filename>.rs`, next to the crate's outputs in the Cargo target directory).
47pub const STAND_IN_PREFIX: &str = "ridx-stand-in-";
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use std::io::Cursor;
53
54    #[test]
55    fn test_roundtrip_basic() {
56        let mut writer = IndexWriter::new("test_crate", "0.1.0");
57
58        // Add definitions
59        writer.add_definition(RawDefinition {
60            def_id: 100,
61            kind: DefKind::Fn,
62            visibility: 0,
63            is_macro_expansion: false,
64            name: "calculate".to_string(),
65            path: "test_crate::math::calculate".to_string(),
66            signature: Some("fn(i32, i32) -> i32".to_string()),
67            file: "src/math.rs".to_string(),
68            start_line: 10,
69            start_col: 1,
70            end_line: 10,
71            end_col: 30,
72        });
73
74        writer.add_definition(RawDefinition {
75            def_id: 101,
76            kind: DefKind::Struct,
77            visibility: 0,
78            is_macro_expansion: false,
79            name: "Calculator".to_string(),
80            path: "test_crate::math::Calculator".to_string(),
81            signature: None,
82            file: "src/math.rs".to_string(),
83            start_line: 5,
84            start_col: 1,
85            end_line: 8,
86            end_col: 2,
87        });
88
89        // Add reference (calling calculate from main.rs)
90        writer.add_reference(RawReference {
91            file: "src/main.rs".to_string(),
92            start_line: 15,
93            start_col: 18,
94            end_line: 15,
95            end_col: 27,
96            target_def_id: Some(100),
97            target_path: "test_crate::math::calculate".to_string(),
98            target_unit: None,
99            target_file: Some("src/math.rs".to_string()),
100            target_line: 10,
101            target_col: 1,
102            kind: DefKind::Fn,
103            is_write: false,
104            is_macro_expansion: false,
105        });
106
107        // Add expression types (outer and inner)
108        writer.add_type(RawType { file: "src/main.rs".to_string(), start_line: 15, start_col: 18, end_line: 15, end_col: 35, type_name: "i32".to_string() });
109
110        writer.add_type(RawType {
111            file: "src/main.rs".to_string(),
112            start_line: 15,
113            start_col: 5,
114            end_line: 15,
115            end_col: 36,
116            type_name: "std::result::Result<i32, String>".to_string(),
117        });
118
119        let mut buffer = Cursor::new(Vec::new());
120        writer.write_to(&mut buffer).expect("write failed");
121        let bytes = buffer.into_inner();
122
123        let reader = IndexReader::from_buffer(&bytes).expect("reader parse failed");
124        assert_eq!(reader.crate_name(), "test_crate");
125        assert_eq!(reader.crate_version(), "0.1.0");
126
127        // Verify definitions lookup by path
128        let def = reader.find_definition_by_path("test_crate::math::calculate").expect("def not found");
129        assert_eq!(reader.get_str(def.name_offset), "calculate");
130        assert_eq!(reader.get_str(def.sig_offset), "fn(i32, i32) -> i32");
131
132        // Verify go-to-definition at reference site
133        let target = reader.find_definition_at("src/main.rs", 15, 20).expect("ref definition not found");
134        assert_eq!(target.name, "calculate");
135        assert_eq!(target.path, "test_crate::math::calculate");
136        assert_eq!(target.file, "src/math.rs");
137        assert_eq!(target.start_line, 10);
138        assert_eq!(target.signature, Some("fn(i32, i32) -> i32"));
139
140        // Verify find_references
141        let refs = reader.find_references("test_crate::math::calculate");
142        assert_eq!(refs.len(), 1);
143        assert_eq!(reader.get_file(refs[0].span.file_id), "src/main.rs");
144        assert_eq!(refs[0].span.start_line, 15);
145
146        // Verify type_at selects innermost type
147        let ty_inner = reader.type_at("src/main.rs", 15, 22).expect("type not found");
148        assert_eq!(ty_inner, "i32");
149
150        let ty_outer = reader.type_at("src/main.rs", 15, 10).expect("type not found");
151        assert_eq!(ty_outer, "std::result::Result<i32, String>");
152    }
153
154    #[test]
155    fn test_string_deduplication() {
156        let mut writer = IndexWriter::new("dedup_crate", "0.1.0");
157        let off1 = writer.intern_string("std::option::Option<T>");
158        let off2 = writer.intern_string("std::option::Option<T>");
159        let off3 = writer.intern_string("std::option::Option<T>");
160        assert_eq!(off1, off2);
161        assert_eq!(off2, off3);
162    }
163
164    #[test]
165    fn test_structural_validation_guards() {
166        // 1. Buffer too small
167        let small_buf = vec![0u8; 64];
168        assert!(IndexReader::from_buffer(&small_buf).is_err());
169
170        // 2. Invalid magic
171        let mut bad_magic = vec![0u8; std::mem::size_of::<Header>()];
172        bad_magic[0..4].copy_from_slice(b"NOPE");
173        assert!(IndexReader::from_buffer(&bad_magic).is_err());
174
175        // 3. Out-of-bounds table offset in valid header
176        let mut writer = IndexWriter::new("test", "0.1.0");
177        let mut buf = std::io::Cursor::new(Vec::new());
178        writer.write_to(&mut buf).unwrap();
179        let mut bytes = buf.into_inner();
180
181        // Corrupt defs_offset to point way beyond buffer
182        let bad_offset = (bytes.len() as u64) + 10000;
183        // defs_offset is at byte 32 of Header
184        bytes[32..40].copy_from_slice(&bad_offset.to_le_bytes());
185        assert!(IndexReader::from_buffer(&bytes).is_err());
186    }
187}