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
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use std::io::Cursor;
49
50    #[test]
51    fn test_roundtrip_basic() {
52        let mut writer = IndexWriter::new("test_crate", "0.1.0");
53
54        // Add definitions
55        writer.add_definition(RawDefinition {
56            def_id: 100,
57            kind: DefKind::Fn,
58            visibility: 0,
59            is_macro_expansion: false,
60            name: "calculate".to_string(),
61            path: "test_crate::math::calculate".to_string(),
62            signature: Some("fn(i32, i32) -> i32".to_string()),
63            file: "src/math.rs".to_string(),
64            start_line: 10,
65            start_col: 1,
66            end_line: 10,
67            end_col: 30,
68        });
69
70        writer.add_definition(RawDefinition {
71            def_id: 101,
72            kind: DefKind::Struct,
73            visibility: 0,
74            is_macro_expansion: false,
75            name: "Calculator".to_string(),
76            path: "test_crate::math::Calculator".to_string(),
77            signature: None,
78            file: "src/math.rs".to_string(),
79            start_line: 5,
80            start_col: 1,
81            end_line: 8,
82            end_col: 2,
83        });
84
85        // Add reference (calling calculate from main.rs)
86        writer.add_reference(RawReference {
87            file: "src/main.rs".to_string(),
88            start_line: 15,
89            start_col: 18,
90            end_line: 15,
91            end_col: 27,
92            target_def_id: Some(100),
93            target_path: "test_crate::math::calculate".to_string(),
94            target_unit: None,
95            target_file: Some("src/math.rs".to_string()),
96            target_line: 10,
97            target_col: 1,
98            kind: DefKind::Fn,
99            is_write: false,
100            is_macro_expansion: false,
101        });
102
103        // Add expression types (outer and inner)
104        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() });
105
106        writer.add_type(RawType {
107            file: "src/main.rs".to_string(),
108            start_line: 15,
109            start_col: 5,
110            end_line: 15,
111            end_col: 36,
112            type_name: "std::result::Result<i32, String>".to_string(),
113        });
114
115        let mut buffer = Cursor::new(Vec::new());
116        writer.write_to(&mut buffer).expect("write failed");
117        let bytes = buffer.into_inner();
118
119        let reader = IndexReader::from_buffer(&bytes).expect("reader parse failed");
120        assert_eq!(reader.crate_name(), "test_crate");
121        assert_eq!(reader.crate_version(), "0.1.0");
122
123        // Verify definitions lookup by path
124        let def = reader.find_definition_by_path("test_crate::math::calculate").expect("def not found");
125        assert_eq!(reader.get_str(def.name_offset), "calculate");
126        assert_eq!(reader.get_str(def.sig_offset), "fn(i32, i32) -> i32");
127
128        // Verify go-to-definition at reference site
129        let target = reader.find_definition_at("src/main.rs", 15, 20).expect("ref definition not found");
130        assert_eq!(target.name, "calculate");
131        assert_eq!(target.path, "test_crate::math::calculate");
132        assert_eq!(target.file, "src/math.rs");
133        assert_eq!(target.start_line, 10);
134        assert_eq!(target.signature, Some("fn(i32, i32) -> i32"));
135
136        // Verify find_references
137        let refs = reader.find_references("test_crate::math::calculate");
138        assert_eq!(refs.len(), 1);
139        assert_eq!(reader.get_file(refs[0].span.file_id), "src/main.rs");
140        assert_eq!(refs[0].span.start_line, 15);
141
142        // Verify type_at selects innermost type
143        let ty_inner = reader.type_at("src/main.rs", 15, 22).expect("type not found");
144        assert_eq!(ty_inner, "i32");
145
146        let ty_outer = reader.type_at("src/main.rs", 15, 10).expect("type not found");
147        assert_eq!(ty_outer, "std::result::Result<i32, String>");
148    }
149
150    #[test]
151    fn test_string_deduplication() {
152        let mut writer = IndexWriter::new("dedup_crate", "0.1.0");
153        let off1 = writer.intern_string("std::option::Option<T>");
154        let off2 = writer.intern_string("std::option::Option<T>");
155        let off3 = writer.intern_string("std::option::Option<T>");
156        assert_eq!(off1, off2);
157        assert_eq!(off2, off3);
158    }
159
160    #[test]
161    fn test_structural_validation_guards() {
162        // 1. Buffer too small
163        let small_buf = vec![0u8; 64];
164        assert!(IndexReader::from_buffer(&small_buf).is_err());
165
166        // 2. Invalid magic
167        let mut bad_magic = vec![0u8; std::mem::size_of::<Header>()];
168        bad_magic[0..4].copy_from_slice(b"NOPE");
169        assert!(IndexReader::from_buffer(&bad_magic).is_err());
170
171        // 3. Out-of-bounds table offset in valid header
172        let mut writer = IndexWriter::new("test", "0.1.0");
173        let mut buf = std::io::Cursor::new(Vec::new());
174        writer.write_to(&mut buf).unwrap();
175        let mut bytes = buf.into_inner();
176
177        // Corrupt defs_offset to point way beyond buffer
178        let bad_offset = (bytes.len() as u64) + 10000;
179        // defs_offset is at byte 32 of Header
180        bytes[32..40].copy_from_slice(&bad_offset.to_le_bytes());
181        assert!(IndexReader::from_buffer(&bytes).is_err());
182    }
183}