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