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