Skip to main content

ridx_format/workspace/
mod.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//! Multi-crate workspace index support for Rust Intelligence.
12//!
13//! Provides unified zero-copy queries across all crates in a cargo workspace.
14
15pub mod cache_resolver;
16pub mod cargo_targets;
17mod cursor_path;
18mod cursor_path_assoc;
19mod definition_at;
20mod discover;
21pub mod file_module;
22pub mod manifest;
23pub mod navigation;
24mod notes;
25mod open;
26pub mod path_index;
27pub mod prelude;
28pub mod provenance;
29pub mod qualifier;
30pub mod reload;
31pub mod rename_cache;
32pub mod rename_factory_idx;
33pub mod rename_parse;
34pub mod rename_refusal;
35pub mod std_map;
36pub mod sysroot;
37pub mod target_kind;
38pub mod unit_match;
39mod warmup;
40
41#[cfg(test)]
42mod cache_resolver_tests;
43#[cfg(test)]
44mod cursor_path_tests;
45#[cfg(test)]
46mod definition_at_tests;
47#[cfg(test)]
48mod file_id_routing_tests;
49#[cfg(test)]
50mod file_module_tests;
51#[cfg(test)]
52mod path_index_tests;
53#[cfg(test)]
54mod qualified_consumer_tests;
55#[cfg(test)]
56mod root_module_tests;
57#[cfg(test)]
58mod routing_tests;
59#[cfg(test)]
60mod sibling_tests;
61#[cfg(test)]
62mod sysroot_tests;
63#[cfg(test)]
64mod target_kind_routing_tests;
65#[cfg(test)]
66mod target_kind_tests;
67#[cfg(test)]
68mod tests;
69#[cfg(test)]
70mod transitive_consumer_tests;
71#[cfg(test)]
72mod unit_match_tests;
73#[cfg(test)]
74mod variant_definition_tests;
75
76pub(crate) use discover::collect_ridx_files;
77pub use manifest::*;
78pub use path_index::PathIndex;
79pub use prelude::is_prelude_trait;
80pub use rename_refusal::RenameRefusal;
81pub use target_kind::{classify_target, classify_target_with_manifest, TargetKind};
82pub use unit_match::UnitMatchIndex;
83
84use crate::reader::IndexReader;
85use memmap2::Mmap;
86use std::collections::{HashMap, HashSet};
87use std::fs;
88use std::path::{Path, PathBuf};
89use std::sync::atomic::{AtomicU64, Ordering};
90
91static WORKSPACE_INSTANCE_COUNTER: AtomicU64 = AtomicU64::new(1);
92
93pub(super) fn next_workspace_instance_id() -> u64 {
94    WORKSPACE_INSTANCE_COUNTER.fetch_add(1, Ordering::Relaxed)
95}
96
97/// Unified multi-crate index for a cargo workspace or multi-index directory.
98pub struct WorkspaceIndex {
99    pub(crate) readers: Vec<IndexReader<Mmap>>,
100    pub(crate) paths: Vec<PathBuf>,
101    pub(crate) mtimes: Vec<Option<std::time::SystemTime>>,
102    pub(crate) source_roots: Vec<Option<PathBuf>>,
103    pub(crate) unit_keys: Vec<Option<String>>,
104    pub(crate) unit_match: UnitMatchIndex,
105    pub(crate) path_index: PathIndex,
106    pub(crate) target_kinds: Vec<Option<TargetKind>>,
107    pub(crate) reader_generations: Vec<Option<String>>,
108    pub(crate) reader_dependencies: Vec<Vec<String>>,
109    pub(crate) reader_extern_units: Vec<HashMap<String, String>>,
110    pub(crate) reader_file_hashes: Vec<HashMap<String, u64>>,
111    /// Per shard path, the `own_sources` of its sidecar, read with its hashes when the shard was loaded.
112    pub(crate) own_sources: HashMap<PathBuf, HashSet<String>>,
113    pub(crate) reader_is_dependency: Vec<bool>,
114    pub(crate) meta_paths: Vec<Option<PathBuf>>,
115    pub(crate) meta_mtimes: Vec<Option<std::time::SystemTime>>,
116    pub(crate) last_reloaded_files: HashSet<String>,
117    pub(crate) root_dir: Option<PathBuf>,
118    pub(crate) workspace_root: Option<PathBuf>,
119    pub(crate) manifest_path: Option<PathBuf>,
120    pub(crate) manifest_mtime: Option<std::time::SystemTime>,
121    pub(crate) manifest_len: Option<u64>,
122    pub(crate) manifest_hash: Option<u64>,
123    pub(crate) manifest_generation: Option<u64>,
124    pub(crate) manifest_ino: Option<u64>,
125    pub(crate) active_variant_id: Option<String>,
126    pub(crate) sysroot_cas_key: Option<String>,
127    pub(crate) instance_id: u64,
128    pub(crate) generation: u64,
129}
130
131impl std::fmt::Debug for WorkspaceIndex {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.debug_struct("WorkspaceIndex").field("readers_count", &self.readers.len()).field("workspace_root", &self.workspace_root).finish()
134    }
135}
136
137impl WorkspaceIndex {
138    /// Number of crates loaded in this workspace index.
139    pub fn crate_count(&self) -> usize {
140        self.readers.len()
141    }
142
143    /// Rebuilds the internal unit matching index after readers or extern units change.
144    pub(crate) fn rebuild_unit_match(&mut self) {
145        self.unit_match = UnitMatchIndex::build_with_deps(&self.readers, &self.unit_keys, &self.reader_extern_units, &self.reader_dependencies);
146    }
147
148    /// Bumps generation and rebuilds the internal file path provenance lookup index.
149    pub(crate) fn rebuild_path_index(&mut self) {
150        self.generation = self.generation.wrapping_add(1);
151        self.path_index = PathIndex::build(self);
152    }
153
154    /// Reference to the internal unit matching index.
155    #[inline]
156    pub fn unit_match(&self) -> &UnitMatchIndex {
157        &self.unit_match
158    }
159
160    /// Slice of crate index readers.
161    pub fn readers(&self) -> &[IndexReader<Mmap>] {
162        &self.readers
163    }
164
165    /// Paths to the loaded .ridx index files.
166    pub fn paths(&self) -> &[PathBuf] {
167        &self.paths
168    }
169
170    /// Returns the snapshot generation for reader at index i.
171    pub fn generation_at(&self, idx: usize) -> Option<&str> {
172        self.reader_generations.get(idx).and_then(|g| g.as_deref())
173    }
174
175    /// Returns the sidecar metadata path for reader at index i.
176    pub fn meta_path_at(&self, idx: usize) -> Option<&Path> {
177        self.meta_paths.get(idx).and_then(|p| p.as_deref())
178    }
179
180    /// Returns the sidecar metadata modification time for reader at index i.
181    pub fn meta_mtime_at(&self, idx: usize) -> Option<std::time::SystemTime> {
182        self.meta_mtimes.get(idx).copied().flatten()
183    }
184
185    /// Returns the source root path for reader at index i, if known.
186    pub fn source_root_at(&self, idx: usize) -> Option<&Path> {
187        self.source_roots.get(idx).and_then(|p| p.as_deref())
188    }
189
190    /// Aggregated statistics across all crates in the workspace.
191    pub fn stats(&self) -> WorkspaceStats {
192        let mut stats = WorkspaceStats { total_crates: self.readers.len(), active_variant: self.active_variant_id.clone(), ..Default::default() };
193
194        for (i, reader) in self.readers.iter().enumerate() {
195            let h = reader.header();
196            let size = fs::metadata(&self.paths[i]).map(|m| m.len()).unwrap_or(0);
197
198            stats.total_defs += h.defs_count as usize;
199            stats.total_refs += h.refs_count as usize;
200            stats.total_types += h.types_count as usize;
201            stats.total_files += h.files_count as usize;
202            stats.total_bytes += size;
203
204            stats.crate_summaries.push(CrateSummary {
205                name: reader.crate_name().to_string(),
206                version: reader.crate_version().to_string(),
207                path: self.paths[i].clone(),
208                file_size: size,
209                defs_count: h.defs_count,
210                refs_count: h.refs_count,
211                types_count: h.types_count,
212                files_count: h.files_count,
213                is_dependency: self.reader_is_dependency.get(i).copied().unwrap_or(false),
214            });
215        }
216
217        stats
218    }
219
220    /// Currently active build variant ID, if loaded from a variant manifest.
221    pub fn active_variant_id(&self) -> Option<&str> {
222        self.active_variant_id.as_deref()
223    }
224
225    /// Returns the sysroot CAS key from the active variant manifest, if present.
226    pub fn sysroot_cas_key(&self) -> Option<&str> {
227        self.sysroot_cas_key.as_deref()
228    }
229
230    /// Root directory of the workspace if known.
231    pub fn workspace_root(&self) -> Option<&Path> {
232        self.workspace_root.as_deref()
233    }
234
235    /// Sets or overrides the workspace root directory.
236    pub fn set_workspace_root(&mut self, root: Option<PathBuf>) {
237        self.workspace_root = root;
238        self.rebuild_path_index();
239    }
240
241    /// Checks whether a target file, path, or unit key belongs to an external dependency or outside the workspace.
242    pub fn is_external_target(&self, target_file: &str, target_path: &Path, target_unit_key: Option<&str>) -> bool {
243        // 1. Explicit sentinel for external reference
244        if target_file == "external" {
245            return true;
246        }
247
248        // 2. Unit-based check: if unit_key is known in the workspace and marked as dependency
249        if let Some(unit_key) = target_unit_key {
250            let matching = self.readers_for_unit_fast(unit_key);
251            if let Some(&i) = matching.first() {
252                return self.reader_is_dependency.get(i).copied().unwrap_or(false);
253            }
254            if self.manifest_path.is_some() {
255                return true;
256            }
257        }
258
259        // 3. Path-based check
260        if target_file.is_empty() {
261            return false;
262        }
263
264        if is_external_dependency_path(target_path) {
265            return true;
266        }
267
268        let effective_root = self.workspace_root().or(self.root_dir.as_deref());
269
270        if let Some(ws_root) = effective_root {
271            if target_path.is_absolute() {
272                let in_ws = target_path.starts_with(ws_root) || crate::paths::canonicalize_cached(target_path).starts_with(crate::paths::canonicalize_cached(ws_root));
273                if !in_ws {
274                    return true;
275                }
276            }
277        }
278
279        false
280    }
281
282    /// Checks whether an arbitrary path belongs to an external dependency or outside the workspace.
283    pub fn is_external_path(&self, path: &Path) -> bool {
284        let s = path.to_str().unwrap_or("");
285        self.is_external_target(s, path, None)
286    }
287
288    /// Returns whether the reader at index `idx` is marked as a dependency.
289    #[inline]
290    pub fn is_reader_dependency(&self, idx: usize) -> bool {
291        self.reader_is_dependency.get(idx).copied().unwrap_or(false)
292    }
293
294    /// Checks whether the reader at index `idx` belongs to an external dependency or outside the workspace.
295    pub fn is_reader_external(&self, idx: usize) -> bool {
296        if self.is_reader_dependency(idx) {
297            return true;
298        }
299
300        let uk = self.unit_keys.get(idx).and_then(|u| u.as_deref());
301        let sroot = self.source_root_at(idx);
302        let p = self.paths.get(idx).map(|p| p.as_path());
303        let path_to_check = sroot.or(p).unwrap_or_else(|| Path::new(""));
304        let file_str = path_to_check.to_str().unwrap_or("");
305        if let Some(u) = uk.filter(|s| !s.is_empty()) {
306            if file_str != "external" && self.unit_match.readers_for_unit(u) == Some(std::slice::from_ref(&idx)) {
307                return false;
308            }
309        }
310
311        self.is_external_target(file_str, path_to_check, uk)
312    }
313
314    /// Checks whether two readers represent sibling units of the same workspace package
315    /// (e.g. `lib` and `lib test` shards of the same package).
316    ///
317    /// Sibling units share the same non-external source root and crate name, but may have
318    /// distinct unit keys (e.g. `unit_lib` vs `unit_test`).
319    pub fn are_sibling_workspace_units(&self, idx1: usize, idx2: usize) -> bool {
320        if idx1 >= self.readers.len() || idx2 >= self.readers.len() {
321            return false;
322        }
323        if self.is_reader_external(idx1) || self.is_reader_external(idx2) {
324            return false;
325        }
326        if idx1 == idx2 {
327            return true;
328        }
329        if self.readers[idx1].crate_name() != self.readers[idx2].crate_name() {
330            return false;
331        }
332        let (Some(sr1), Some(sr2)) = (self.source_root_at(idx1), self.source_root_at(idx2)) else {
333            return false;
334        };
335        sr1 == sr2
336            || match (sr1.canonicalize(), sr2.canonicalize()) {
337                (Ok(c1), Ok(c2)) => c1 == c2,
338                _ => false,
339            }
340    }
341
342    /// Returns the unique instance ID for this workspace.
343    #[inline]
344    pub fn instance_id(&self) -> u64 {
345        self.instance_id
346    }
347
348    /// Returns the current index generation counter.
349    /// Incremented on each index reload or modification.
350    #[inline]
351    pub fn generation(&self) -> u64 {
352        self.generation
353    }
354
355    /// Explicitly bumps the index generation counter.
356    #[inline]
357    pub fn bump_generation(&mut self) -> u64 {
358        self.generation = self.generation.wrapping_add(1);
359        self.generation
360    }
361}
362
363/// Checks whether a path points to an external dependency cache or toolchain
364/// (e.g. Cargo registry, Cargo git checkouts, Rustup toolchains, standard library).
365pub fn is_external_dependency_path(path: &Path) -> bool {
366    if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
367        let ch = Path::new(&cargo_home);
368        if path.starts_with(ch.join("registry")) || path.starts_with(ch.join("git")) {
369            return true;
370        }
371    }
372
373    // One separator: a Windows path can mix them (`<temp>\.cargo/registry\...`).
374    let path_str = path.to_string_lossy().replace('\\', "/");
375    ["/.cargo/registry/", "/.cargo/git/", "/.rustup/toolchains/", "/lib/rustlib/", "/target/ridx/dependencies/"].iter().any(|c| path_str.contains(c))
376}
377
378#[cfg(test)]
379pub(crate) static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());