Skip to main content

ridx_format/workspace/
sysroot.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//! Discovery and attachment of cached sysroot index shards (`core`, `alloc`, `std`).
12
13use std::collections::HashMap;
14use std::fs;
15use std::path::{Path, PathBuf};
16
17use crate::reader::IndexReader;
18
19/// Discovers cached sysroot shard paths (`core.ridx`, `alloc.ridx`, `std.ridx`) for a specific CAS key
20/// inside the global cache directory `~/.cache/ridx/v3/sysroot/<cas_key>/`.
21pub fn discover_sysroot_shards_for_key(cas_key: &str) -> Vec<PathBuf> {
22    let base_cache = crate::resolve_cache_dir().join("sysroot");
23    discover_sysroot_shards_for_key_in(&base_cache, cas_key)
24}
25
26/// Discovers cached sysroot shard paths for a specific CAS key inside a specified base cache path.
27pub fn discover_sysroot_shards_for_key_in(base_cache: &Path, cas_key: &str) -> Vec<PathBuf> {
28    let target_dir = base_cache.join(cas_key);
29    if !target_dir.is_dir() {
30        return Vec::new();
31    }
32
33    let mut shards = Vec::new();
34    for cname in ["core", "alloc", "std"] {
35        let p = target_dir.join(format!("{cname}.ridx"));
36        if p.is_file() {
37            shards.push(p);
38        }
39    }
40    shards
41}
42
43impl super::WorkspaceIndex {
44    /// Returns true if sysroot shards (`core`) are attached to the workspace.
45    pub fn has_sysroot(&self) -> bool {
46        self.readers.iter().any(|r| r.crate_name() == "core")
47    }
48
49    /// Resolves `kind` across attached shards (`core`, `alloc`, workspace), returning `(reader_idx, view)`.
50    pub fn lang_item(&self, kind: crate::format::LangItemKind) -> Option<(usize, crate::ty_arena::LangItemView)> {
51        for (idx, reader) in self.readers.iter().enumerate() {
52            if reader.header().lang_items_count > 0 {
53                if let Some(view) = reader.lang_item(kind) {
54                    return Some((idx, view));
55                }
56            }
57        }
58        None
59    }
60
61    /// Attaches cached sysroot shards for the given `cas_key` to the workspace if not already present.
62    pub fn attach_sysroot_shards_for_key(&mut self, cas_key: &str) {
63        if self.has_sysroot() {
64            return;
65        }
66        let shards = discover_sysroot_shards_for_key(cas_key);
67        if shards.is_empty() {
68            static LOGGED_ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
69            if !LOGGED_ONCE.swap(true, std::sync::atomic::Ordering::Relaxed) {
70                eprintln!("[ridx] Warning: no sysroot shards found for cas_key {:?} in cache", cas_key);
71            }
72            return;
73        }
74        self.attach_shard_paths(&shards);
75    }
76
77    /// Attaches cached sysroot shards for the given `cas_key` located in `base_cache`.
78    pub fn attach_sysroot_shards_for_key_in(&mut self, base_cache: &Path, cas_key: &str) {
79        if self.has_sysroot() {
80            return;
81        }
82        let shards = discover_sysroot_shards_for_key_in(base_cache, cas_key);
83        self.attach_shard_paths(&shards);
84    }
85
86    pub fn attach_shard_paths(&mut self, shards: &[PathBuf]) {
87        for sys_path in shards {
88            if let Ok(reader) = IndexReader::open(sys_path) {
89                let mtime = fs::metadata(sys_path).and_then(|m| m.modified()).ok();
90                let ukey = (!reader.unit_key().is_empty()).then(|| reader.unit_key().to_string());
91                let gen = if !reader.generation().is_empty() { Some(reader.generation().to_string()) } else { None };
92                self.readers.push(reader);
93                self.paths.push(sys_path.clone());
94                self.mtimes.push(mtime);
95                self.source_roots.push(None);
96                self.unit_keys.push(ukey);
97                self.target_kinds.push(Some(super::TargetKind::Lib));
98                self.reader_generations.push(gen);
99                self.reader_dependencies.push(Vec::new());
100                self.reader_extern_units.push(HashMap::new());
101                self.reader_file_hashes.push(HashMap::new());
102                self.reader_is_dependency.push(true);
103                self.meta_paths.push(None);
104                self.meta_mtimes.push(None);
105            }
106        }
107        self.rebuild_unit_match();
108        self.rebuild_path_index();
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::IndexWriter;
116
117    #[test]
118    fn test_discover_and_attach_sysroot() {
119        let temp_dir = std::env::temp_dir().join(format!("ridx_sysroot_test_{}", std::process::id()));
120        let _ = fs::remove_dir_all(&temp_dir);
121        let base_cache = temp_dir.join("sysroot");
122        let sys_dir = base_cache.join("test_cas_key");
123        fs::create_dir_all(&sys_dir).unwrap();
124
125        for cname in ["core", "alloc", "std"] {
126            let mut writer = IndexWriter::new(cname, "1.97.1");
127            writer.set_unit_key(format!("{cname}-1.97.1"));
128            let mut buf = Vec::new();
129            writer.write_to(&mut std::io::Cursor::new(&mut buf)).unwrap();
130            fs::write(sys_dir.join(format!("{cname}.ridx")), buf).unwrap();
131        }
132
133        let shards = discover_sysroot_shards_for_key_in(&base_cache, "test_cas_key");
134        assert_eq!(shards.len(), 3, "must discover 3 sysroot shards");
135
136        // Create a dummy project directory with a crate index
137        let proj_dir = temp_dir.join("user_crate");
138        fs::create_dir_all(&proj_dir).unwrap();
139        let mut user_writer = IndexWriter::new("user_crate", "0.1.0");
140        user_writer.set_unit_key("user_crate-0.1.0");
141        let mut user_buf = Vec::new();
142        user_writer.write_to(&mut std::io::Cursor::new(&mut user_buf)).unwrap();
143        fs::write(proj_dir.join("user_crate.ridx"), user_buf).unwrap();
144
145        let mut ws = super::super::WorkspaceIndex::open(&proj_dir).expect("open must succeed");
146        assert_eq!(ws.readers.len(), 1);
147
148        ws.attach_sysroot_shards_for_key_in(&base_cache, "test_cas_key");
149        // Must contain user_crate + core + alloc + std
150        assert_eq!(ws.readers.len(), 4);
151        assert_eq!(ws.readers[0].crate_name(), "user_crate");
152        assert_eq!(ws.readers[1].crate_name(), "core");
153        assert_eq!(ws.readers[2].crate_name(), "alloc");
154        assert_eq!(ws.readers[3].crate_name(), "std");
155
156        // Calling attach again should be idempotent
157        ws.attach_sysroot_shards_for_key_in(&base_cache, "test_cas_key");
158        assert_eq!(ws.readers.len(), 4);
159
160        let _ = fs::remove_dir_all(&temp_dir);
161    }
162}