Skip to main content

ridx_format/workspace/
file_module.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//! File-to-crate reader mapping and canonical module path resolution.
12
13use super::WorkspaceIndex;
14use std::path::Path;
15
16mod candidates;
17mod stored_forms;
18
19#[inline]
20pub(crate) fn is_clean_posix_bytes(b: &[u8]) -> bool {
21    if b.is_empty() || b.starts_with(b"./") || b == b"." || b.ends_with(b"/.") || b.contains(&b'\\') {
22        return false;
23    }
24    let mut i = 0;
25    while i + 1 < b.len() {
26        if b[i] == b'/' && (b[i + 1] == b'/' || b[i + 1] == b'.') {
27            return false;
28        }
29        i += 1;
30    }
31    true
32}
33
34#[inline]
35pub(crate) fn fast_path_starts_with(base: &Path, base_clean: bool, root: &Path) -> bool {
36    let r = root.as_os_str().as_encoded_bytes();
37    if base_clean && is_clean_posix_bytes(r) {
38        let b = base.as_os_str().as_encoded_bytes();
39        let r_trimmed = if r.len() > 1 && r.last() == Some(&b'/') { &r[..r.len() - 1] } else { r };
40        if b.len() < r_trimmed.len() || !b.starts_with(r_trimmed) {
41            return false;
42        }
43        return b.len() == r_trimmed.len() || r_trimmed == b"/" || b.get(r_trimmed.len()) == Some(&b'/');
44    }
45    base.starts_with(root)
46}
47
48impl WorkspaceIndex {
49    /// Returns the index in `self.readers` for the crate that contains or owns the specified file path.
50    pub fn reader_index_for_file(&self, file_path: &str) -> Option<usize> {
51        let indices = self.reader_indices_for_file(file_path);
52        self.reader_index_from_indices(&indices, file_path)
53    }
54
55    pub(crate) fn reader_index_from_indices(&self, indices: &[usize], file_path: &str) -> Option<usize> {
56        let has_file = |i: usize| self.target_file_id_for_reader(i, file_path).is_some();
57        let is_lib = |i: usize| {
58            self.target_kinds.get(i).copied().flatten().is_some_and(|k| k.is_lib()) || self.unit_keys.get(i).and_then(|u| u.as_deref()).is_some_and(|uk| uk.contains("(lib)"))
59        };
60        if let Some(i) = indices.iter().copied().find(|&i| is_lib(i) && has_file(i)) {
61            return Some(i);
62        }
63        if let Some(i) = indices.iter().copied().find(|&i| !is_lib(i) && has_file(i)) {
64            return Some(i);
65        }
66        indices.iter().copied().find(|&i| is_lib(i)).or_else(|| indices.first().copied())
67    }
68
69    /// Whether `file_path` is compiled into a binary target (`src/main.rs`, a module of it, a `[[bin]]` path) and not
70    /// into the package's library: its `crate::` is the binary, the library is another crate to it.
71    pub fn file_in_bin_only(&self, file_path: &str) -> bool {
72        let indices = self.reader_indices_for_file(file_path);
73        let kind = |i: usize| self.target_kinds.get(i).copied().flatten();
74        let has_file = |i: usize| self.target_file_id_for_reader(i, file_path).is_some();
75        let in_lib = indices.iter().any(|&i| kind(i).is_some_and(|k| k.is_lib()) && has_file(i));
76        let in_bin = indices.iter().any(|&i| kind(i) == Some(super::target_kind::TargetKind::Bin) && has_file(i));
77        in_bin && !in_lib
78    }
79
80    /// Returns the target kind for the reader at index `idx` if known.
81    pub fn target_kind_at(&self, idx: usize) -> Option<super::target_kind::TargetKind> {
82        self.target_kinds.get(idx).copied().flatten()
83    }
84
85    /// The root a reader's relative stored paths are resolved against: its recorded source root,
86    /// else, for a shard opened without any workspace root (a lone `.ridx` file), the directory
87    /// the shard lies in. Readers of a rooted workspace that record no source root (the sysroot
88    /// shards) have none.
89    pub(crate) fn reader_root(&self, idx: usize) -> Option<&Path> {
90        if let Some(Some(root)) = self.source_roots.get(idx) {
91            return Some(root.as_path());
92        }
93        if self.workspace_root.is_none() {
94            return self.paths.get(idx).and_then(|p| p.parent());
95        }
96        None
97    }
98
99    /// Returns the indices in `self.readers` for all crate units that contain or own the specified file path.
100    /// Employs longest prefix matching on `source_roots` so that subpackage targets are returned
101    /// rather than broader ancestor workspace roots, invariant to reader insertion order.
102    pub fn reader_indices_for_file(&self, file_path: &str) -> Vec<usize> {
103        let p = Path::new(file_path);
104        let p_is_abs = p.is_absolute();
105        let p_clean = is_clean_posix_bytes(p.as_os_str().as_encoded_bytes());
106        let abs_p = if p_is_abs { None } else { self.workspace_root.as_ref().map(|ws| ws.join(p)) };
107        let abs_p_clean = abs_p.as_ref().is_some_and(|ap| is_clean_posix_bytes(ap.as_os_str().as_encoded_bytes()));
108
109        // 1. Longest prefix match against source_roots (fast lexical path, then canonical fallback)
110        if let Some(top) = self.match_source_roots(p, file_path, p_clean, abs_p.as_deref(), abs_p_clean, self.workspace_root.as_deref(), false) {
111            return self.or_includers(top, file_path);
112        }
113        let canon_p_opt = if p_is_abs || abs_p.is_some() {
114            let candidate = abs_p.as_deref().unwrap_or(p);
115            let canon_p = crate::paths::canonicalize_cached(candidate);
116            let canon_ws = self.workspace_root.as_deref().map(crate::paths::canonicalize_cached);
117            if let Some(canon_str) = canon_p.to_str() {
118                let canon_clean = is_clean_posix_bytes(canon_p.as_os_str().as_encoded_bytes());
119                if let Some(top) = self.match_source_roots(&canon_p, canon_str, canon_clean, None, false, canon_ws.as_deref(), true) {
120                    return self.or_includers(top, file_path);
121                }
122            }
123            Some(canon_p)
124        } else {
125            None
126        };
127
128        let abs_str = abs_p.as_deref().and_then(|ap| ap.to_str());
129
130        // 2. Exact match for workspace-anchored path if relative
131        if let Some(ap) = abs_str {
132            let indices: Vec<usize> = self
133                .readers
134                .iter()
135                .enumerate()
136                .filter(|&(i, _)| self.reader_find_file_id(i, ap).is_some() || self.reader_file_hashes.get(i).is_some_and(|h| h.contains_key(ap)))
137                .map(|(i, _)| i)
138                .collect();
139            if !indices.is_empty() {
140                return indices;
141            }
142        }
143
144        // 3. reader.find_file_id match (direct index match, including canonical alias)
145        let canon_str = canon_p_opt.as_deref().and_then(|cp| cp.to_str()).filter(|&cs| cs != file_path);
146        let indices: Vec<usize> = (0..self.readers.len())
147            .filter(|&i| self.reader_find_file_id(i, file_path).is_some() || canon_str.is_some_and(|cs| self.reader_find_file_id(i, cs).is_some()))
148            .collect();
149        if !indices.is_empty() {
150            return indices;
151        }
152
153        // 4. reader_file_hashes exact match
154        let indices: Vec<usize> = self.reader_file_hashes.iter().enumerate().filter(|&(_, h)| h.contains_key(file_path)).map(|(i, _)| i).collect();
155        if !indices.is_empty() {
156            let cname_matches: Vec<usize> = indices
157                .iter()
158                .copied()
159                .filter(|&i| {
160                    let c = self.readers[i].crate_name();
161                    file_path.contains(&format!("/{c}/")) || file_path.contains(&format!("\\{c}\\"))
162                })
163                .collect();
164            return if cname_matches.is_empty() { indices } else { cname_matches };
165        }
166
167        // 5. Crate name contained in path
168        let indices: Vec<usize> = self
169            .readers
170            .iter()
171            .enumerate()
172            .filter(|&(_, r)| {
173                let c = r.crate_name();
174                file_path.contains(&format!("/{c}/")) || file_path.contains(&format!("\\{c}\\"))
175            })
176            .map(|(i, _)| i)
177            .collect();
178        if !indices.is_empty() {
179            return indices;
180        }
181
182        // 5. Fallback for single crate workspace
183        if self.readers.len() == 1 {
184            return vec![0];
185        }
186
187        // 6. Fallback for single non-sysroot crate
188        let non_sysroot: Vec<usize> = self.readers.iter().enumerate().filter(|(_, r)| !matches!(r.crate_name(), "core" | "alloc" | "std")).map(|(i, _)| i).collect();
189        if non_sysroot.len() == 1 {
190            return non_sysroot;
191        }
192
193        Vec::new()
194    }
195
196    /// The names under which the compilation unit of `file_path` links other crates (its `extern` names), when the
197    /// index records them; `None` when it does not.
198    pub fn extern_crate_names_for_file(&self, file_path: &str) -> Option<Vec<&str>> {
199        let idx = self.reader_index_for_file(file_path)?;
200        let names = self.reader_extern_units.get(idx).filter(|m| !m.is_empty())?;
201        Some(names.keys().map(String::as_str).collect())
202    }
203
204    /// The crate-relative module `file_path` is (`flags::complete::fish`, `""` for the crate root), read from the
205    /// module-level items the index holds for it (functions, types, traits, consts, statics, modules): the shallowest
206    /// of their parents, so an inline `mod tests { … }` of the file does not stand for it. `None` when the file
207    /// declares no such item.
208    pub fn module_of_file(&self, file_path: &str) -> Option<String> {
209        use crate::format::DefKind;
210        let idx = self.reader_index_for_file(file_path)?;
211        let reader = &self.readers[idx];
212        let cname = reader.crate_name();
213        let fid = self.target_file_id_for_reader(idx, file_path)?;
214        let defs = reader.definitions();
215        let mut best: Option<String> = None;
216        for &(_, _, def_idx) in self.unit_match.defs_in_file_up_to(idx, fid, u32::MAX) {
217            let Some(def) = defs.get(def_idx as usize) else { continue };
218            let module_level = matches!(
219                DefKind::from(def.kind),
220                DefKind::Fn | DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait | DefKind::Const | DefKind::Static | DefKind::TyAlias | DefKind::Mod
221            );
222            if !module_level || def.is_macro_expansion() {
223                continue;
224            }
225            let path = reader.get_str(def.path_offset());
226            let rel = path.strip_prefix(cname).and_then(|r| r.strip_prefix("::")).unwrap_or(path);
227            let parent = rel.rsplit_once("::").map_or("", |(p, _)| p);
228            if parent.contains(['<', ' ']) {
229                continue;
230            }
231            if best.as_deref().is_none_or(|b| parent.matches("::").count() + usize::from(!parent.is_empty()) < b.matches("::").count() + usize::from(!b.is_empty())) {
232                best = Some(parent.to_string());
233            }
234        }
235        best
236    }
237
238    /// Returns the canonical module path corresponding to `file_path` in the owning crate
239    /// (e.g. `serde::de::impls` for `serde/src/de/impls.rs`).
240    pub fn module_path_for_file(&self, file_path: &str) -> Option<String> {
241        let idx = self.reader_index_for_file(file_path)?;
242        self.module_path_for_reader(idx, file_path)
243    }
244
245    pub(crate) fn module_path_for_reader(&self, idx: usize, file_path: &str) -> Option<String> {
246        let reader = &self.readers[idx];
247        let cname = reader.crate_name();
248
249        // 1. Inspect definitions declared directly in this file; a reader that does not store
250        //    the file contributes nothing here and the path-based fallback below decides.
251        if let Some(fid) = self.target_file_id_for_reader(idx, file_path) {
252            let defs = reader.definitions();
253            for &(_, _, def_idx) in self.unit_match.defs_in_file_up_to(idx, fid, u32::MAX) {
254                let Some(def) = defs.get(def_idx as usize) else {
255                    continue;
256                };
257                let path = reader.get_str(def.path_offset());
258                let name = reader.get_str(def.name_offset());
259                let suffix = format!("::{name}");
260                if let Some(parent) = path.strip_suffix(&suffix) {
261                    if parent == cname || parent.starts_with(&format!("{cname}::")) {
262                        return Some(parent.to_string());
263                    }
264                }
265            }
266        }
267
268        // 2. Fallback based on relative file path
269        let norm = file_path.replace('\\', "/");
270        let p = Path::new(&norm);
271        let file_stem = p.file_stem()?.to_str()?;
272
273        if file_stem == "lib" || file_stem == "main" {
274            return Some(cname.to_string());
275        }
276
277        let sub = if let Some(pos) = norm.find("/src/") {
278            &norm[pos + 5..]
279        } else if let Some(stripped) = norm.strip_prefix("src/") {
280            stripped
281        } else {
282            &norm
283        };
284
285        let sub_p = Path::new(sub);
286        let mut segs = vec![cname];
287        if let Some(parent) = sub_p.parent() {
288            for comp in parent.components() {
289                if let Some(s) = comp.as_os_str().to_str() {
290                    if !s.is_empty() && s != "." {
291                        segs.push(s);
292                    }
293                }
294            }
295        }
296        if file_stem != "mod" {
297            segs.push(file_stem);
298        }
299        Some(segs.join("::"))
300    }
301
302    pub(crate) fn enclosing_inline_mod_path(&self, file: &str, line: u32, col: u32) -> Option<&str> {
303        for i in self.reader_indices_for_file(file) {
304            let reader = &self.readers[i];
305            let Some(tf) = self.target_file_for_reader(i, file) else {
306                continue;
307            };
308            let Some(fid) = reader.find_file_id(tf.as_ref()) else {
309                continue;
310            };
311            let defs = reader.definitions();
312            let mut best: Option<(&str, u64)> = None;
313            for &(_, _, di) in self.unit_match.defs_in_file_up_to(i, fid, line) {
314                let Some(def) = defs.get(di as usize) else {
315                    continue;
316                };
317                if crate::format::DefKind::from(def.kind) != crate::format::DefKind::Mod {
318                    continue;
319                }
320                let span = def.span();
321                let path = reader.get_str(def.path_offset());
322                if !path.is_empty() && span.contains(fid, line, col) {
323                    let sz = span.approximate_size();
324                    if best.is_none_or(|(_, bsz)| sz < bsz) {
325                        best = Some((path, sz));
326                    }
327                }
328            }
329            if let Some((p, _)) = best {
330                return Some(p);
331            }
332        }
333        None
334    }
335}