Skip to main content

ridx_format/workspace/file_module/
candidates.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
11use super::{fast_path_starts_with, is_clean_posix_bytes};
12use crate::workspace::WorkspaceIndex;
13use std::path::Path;
14
15impl WorkspaceIndex {
16    /// Resolves `file` via canonicalized paths when direct prefix/table lookup misses (e.g.
17    /// symlinked directories like `/var/folders` vs `/private/var/folders`).
18    fn canonical_target_for_reader(&self, reader_idx: usize, p: &Path, check_hashes: bool) -> Option<(String, Option<u32>)> {
19        let root_opt = self.reader_root(reader_idx);
20        let canon_ws = self.workspace_root.as_deref().map(crate::paths::canonicalize_cached);
21        let canon_root = root_opt.map(|root| {
22            if root.is_absolute() {
23                crate::paths::canonicalize_cached(root)
24            } else if let Some(ws) = canon_ws.as_deref() {
25                crate::paths::canonicalize_cached(&ws.join(root))
26            } else {
27                crate::paths::canonicalize_cached(root)
28            }
29        });
30        let lookup_stored = |s: &str| self.reader_find_file_id(reader_idx, s).map(|fid| (s.to_string(), Some(fid)));
31
32        if p.is_absolute() {
33            let canon_p = crate::paths::canonicalize_cached(p);
34            // No link on the path, the root or the workspace root: the lexical lookups that missed were
35            // already these. The common case, and the one that must stay free.
36            let root_abs = root_opt.map(|r| if r.is_absolute() { r.to_path_buf() } else { self.workspace_root.as_deref().map_or_else(|| r.to_path_buf(), |ws| ws.join(r)) });
37            if canon_p == p && canon_ws.as_deref() == self.workspace_root.as_deref() && canon_root.as_deref() == root_abs.as_deref() {
38                return None;
39            }
40            // The resolved path as stored or in a stored form, by the same rules as the path asked for: a workspace crate
41            // may store a linked file's target relative to the workspace root, outside its own package (review of PR #22).
42            if let Some((fid, s)) = self.lexical_file_id(reader_idx, &canon_p, is_clean_posix_bytes(canon_p.as_os_str().as_encoded_bytes())) {
43                return Some((s.to_string(), Some(fid)));
44            }
45            if let Some(ref cr) = canon_root {
46                if !canon_p.starts_with(cr) {
47                    return None;
48                }
49            } else if let Some(ref cws) = canon_ws {
50                if !canon_p.starts_with(cws) {
51                    return None;
52                }
53            }
54            for base in [canon_ws.as_deref(), canon_root.as_deref()].into_iter().flatten() {
55                if let Some(s) = canon_p.strip_prefix(base).ok().and_then(|r| r.to_str()) {
56                    if let Some(found) = lookup_stored(s) {
57                        return Some(found);
58                    }
59                }
60            }
61            return None;
62        }
63
64        let canon_roots = [canon_ws.as_deref(), canon_root.as_deref()];
65        for anchor in canon_roots.into_iter().flatten() {
66            let joined = crate::paths::canonicalize_cached(&anchor.join(p));
67            if let Some(s) = joined.to_str() {
68                if let Some(found) = lookup_stored(s) {
69                    return Some(found);
70                }
71            }
72            for base in canon_roots.into_iter().flatten() {
73                if let Some(s) = joined.strip_prefix(base).ok().and_then(|r| r.to_str()) {
74                    if let Some(found) = lookup_stored(s) {
75                        return Some(found);
76                    }
77                }
78            }
79        }
80        if check_hashes {
81            if let Some(hashes) = self.reader_file_hashes.get(reader_idx) {
82                for anchor in canon_roots.into_iter().flatten() {
83                    let joined = crate::paths::canonicalize_cached(&anchor.join(p));
84                    if let Some(s) = joined.to_str() {
85                        if hashes.contains_key(s) {
86                            return Some((s.to_string(), None));
87                        }
88                    }
89                }
90            }
91        }
92        None
93    }
94
95    /// Resolves `file` directly to its `file_id` in `reader_idx` without allocating intermediate strings on fast path.
96    pub(crate) fn target_file_id_for_reader(&self, reader_idx: usize, file: &str) -> Option<u32> {
97        let _ = self.readers.get(reader_idx)?;
98        let p = Path::new(file);
99        let root_opt = self.reader_root(reader_idx);
100
101        if p.is_absolute() {
102            let p_clean = is_clean_posix_bytes(p.as_os_str().as_encoded_bytes());
103            if let Some((fid, _)) = self.lexical_file_id(reader_idx, p, p_clean) {
104                return Some(fid);
105            }
106            return self.canonical_target_for_reader(reader_idx, p, false).and_then(|(_, fid)| fid);
107        }
108
109        if let Some(fid) = self.reader_find_file_id(reader_idx, file) {
110            return Some(fid);
111        }
112        let roots = [self.workspace_root.as_deref(), root_opt];
113        for anchor in roots.into_iter().flatten() {
114            let joined = anchor.join(p);
115            if let Some(s) = joined.to_str() {
116                if let Some(fid) = self.reader_find_file_id(reader_idx, s) {
117                    return Some(fid);
118                }
119            }
120            for base in roots.into_iter().flatten() {
121                if let Some(s) = joined.strip_prefix(base).ok().and_then(|r| r.to_str()) {
122                    if let Some(fid) = self.reader_find_file_id(reader_idx, s) {
123                        return Some(fid);
124                    }
125                }
126            }
127        }
128        self.canonical_target_for_reader(reader_idx, p, false).and_then(|(_, fid)| fid)
129    }
130
131    /// Returns prioritized `(reader_idx, file_id)` pairs for `file` (library targets first).
132    pub fn resolved_reader_file_ids(&self, file: &str) -> Vec<(usize, u32)> {
133        let mut direct: Vec<(usize, u32)> = self.reader_indices_for_file(file).into_iter().filter_map(|i| self.target_file_id_for_reader(i, file).map(|fid| (i, fid))).collect();
134        if !direct.is_empty() {
135            direct.sort_by_key(|&(idx, _)| usize::from(!self.target_kinds.get(idx).copied().flatten().is_some_and(|k| k.is_lib())));
136            return direct;
137        }
138        self.candidate_reader_indices_for_file(file).into_iter().filter_map(|i| self.target_file_id_for_reader(i, file).map(|fid| (i, fid))).collect()
139    }
140
141    /// Resolves `file` (absolute, relative to the workspace root, or relative to the reader's
142    /// source root) to the path string the reader at `reader_idx` stores for it, or `None` when
143    /// this reader does not index the file. Every string returned is accepted by that reader's
144    /// exact `find_file_id`: the input is re-expressed in the reader's coordinates (relative to
145    /// the workspace root or to the source root) and compared whole, never by suffix.
146    pub fn target_file_for_reader<'a>(&self, reader_idx: usize, file: &'a str) -> Option<std::borrow::Cow<'a, str>> {
147        let _ = self.readers.get(reader_idx)?;
148        let p = Path::new(file);
149        let root_opt = self.reader_root(reader_idx);
150        let stored = |s: &str| self.reader_find_file_id(reader_idx, s).is_some();
151        let owned = |s: &str| Some(std::borrow::Cow::Owned(s.to_string()));
152
153        if p.is_absolute() {
154            // C. Stored as an absolute path: the reader names this very file, whatever the roots; else A. relative to the
155            // workspace root (workspace crates) or B. relative to the source root (dependencies indexed from their
156            // package root).
157            let p_clean = is_clean_posix_bytes(p.as_os_str().as_encoded_bytes());
158            if let Some((_, s)) = self.lexical_file_id(reader_idx, p, p_clean) {
159                return if s == file { Some(std::borrow::Cow::Borrowed(file)) } else { owned(s) };
160            }
161            return self.canonical_target_for_reader(reader_idx, p, false).map(|(s, _)| std::borrow::Cow::Owned(s));
162        }
163
164        // Relative input: the stored form itself; else the path anchored to the workspace root or
165        // to the source root and re-expressed relative to each of them, which are the two stored
166        // forms (`src/lib.rs` typed for the crate stored as `serde/src/lib.rs` becomes
167        // `<ws>/serde/src/lib.rs`, then `serde/src/lib.rs`). A bare relative path that no root
168        // anchors to a stored file is not resolved.
169        if stored(file) {
170            return Some(std::borrow::Cow::Borrowed(file));
171        }
172        let roots = [self.workspace_root.as_deref(), root_opt];
173        for anchor in roots.into_iter().flatten() {
174            let joined = anchor.join(p);
175            if let Some(s) = joined.to_str() {
176                if stored(s) {
177                    return owned(s);
178                }
179            }
180            for base in roots.into_iter().flatten() {
181                if let Some(s) = joined.strip_prefix(base).ok().and_then(|r| r.to_str()) {
182                    if stored(s) {
183                        return owned(s);
184                    }
185                }
186            }
187        }
188        // Readers that know the file only through their recorded hashes (an empty file table):
189        // the sidecar records both forms, the absolute one is compared here.
190        if let Some(hashes) = self.reader_file_hashes.get(reader_idx) {
191            for anchor in roots.into_iter().flatten() {
192                if let Some(s) = anchor.join(p).to_str() {
193                    if hashes.contains_key(s) {
194                        return owned(s);
195                    }
196                }
197            }
198        }
199        self.canonical_target_for_reader(reader_idx, p, true).map(|(s, _)| std::borrow::Cow::Owned(s))
200    }
201
202    /// Matches `p` (and `abs_p`) against reader `source_roots` using longest prefix match.
203    #[allow(clippy::too_many_arguments)]
204    pub(super) fn match_source_roots(
205        &self,
206        p: &Path,
207        file_path: &str,
208        p_clean: bool,
209        abs_p: Option<&Path>,
210        abs_p_clean: bool,
211        ws_root: Option<&Path>,
212        canonicalize_roots: bool,
213    ) -> Option<Vec<usize>> {
214        let mut matching_roots: Vec<(usize, usize, usize)> = Vec::new();
215        let mut last_root_meta: Option<(&Path, bool, usize, usize)> = None;
216        for (i, _) in self.readers.iter().enumerate() {
217            if let Some(root) = self.reader_root(i) {
218                if !root.as_os_str().is_empty() {
219                    let (matches, comps, len) = match last_root_meta {
220                        Some((prev, m, c, l)) if prev == root => (m, c, l),
221                        _ => {
222                            let resolved_owned;
223                            let root_cmp = if canonicalize_roots {
224                                resolved_owned = if root.is_absolute() {
225                                    crate::paths::canonicalize_cached(root)
226                                } else if let Some(ws) = ws_root {
227                                    crate::paths::canonicalize_cached(&ws.join(root))
228                                } else {
229                                    crate::paths::canonicalize_cached(root)
230                                };
231                                resolved_owned.as_path()
232                            } else {
233                                root
234                            };
235                            let m = fast_path_starts_with(p, p_clean, root_cmp)
236                                || abs_p.is_some_and(|ap| fast_path_starts_with(ap, abs_p_clean, root_cmp))
237                                || (!canonicalize_roots && p.is_absolute() && root.is_relative() && ws_root.is_some_and(|ws| p.starts_with(ws.join(root))));
238                            let (c, l) = if m { (root_cmp.components().count(), root_cmp.as_os_str().len()) } else { (0, 0) };
239                            last_root_meta = Some((root, m, c, l));
240                            (m, c, l)
241                        }
242                    };
243                    if matches {
244                        matching_roots.push((i, comps, len));
245                    }
246                }
247            }
248        }
249        let (_, max_comps, max_len) = matching_roots.iter().max_by_key(|(_, comps, len)| (*comps, *len)).copied()?;
250        let top: Vec<usize> = matching_roots.into_iter().filter(|(_, comps, len)| *comps == max_comps && *len == max_len).map(|(i, _, _)| i).collect();
251        if top.len() > 1 {
252            let ws_rel = ws_root.and_then(|ws| p.strip_prefix(ws).ok()).and_then(|r| r.to_str());
253            let mut filtered = Vec::with_capacity(top.len());
254            let mut any_exact = false;
255            let fast_valid = self.unit_match.is_valid_for_readers(&self.readers);
256            let exact_full = if fast_valid { self.unit_match.readers_for_clean_file(file_path) } else { None };
257            let exact_rel = if fast_valid {
258                match ws_rel {
259                    Some(rel) => self.unit_match.readers_for_clean_file(rel),
260                    None => Some(&[][..]),
261                }
262            } else {
263                None
264            };
265            for &i in &top {
266                let exact = if let (Some(ef), Some(er)) = (exact_full, exact_rel) {
267                    if !self.unit_match.reader_has_special(i) {
268                        ef.binary_search_by_key(&i, |&(r, _)| r).is_ok() || er.binary_search_by_key(&i, |&(r, _)| r).is_ok()
269                    } else {
270                        self.reader_find_file_id(i, file_path).is_some() || ws_rel.is_some_and(|rel| self.reader_find_file_id(i, rel).is_some())
271                    }
272                } else {
273                    self.reader_find_file_id(i, file_path).is_some() || ws_rel.is_some_and(|rel| self.reader_find_file_id(i, rel).is_some())
274                };
275                if exact {
276                    any_exact = true;
277                }
278                if exact || self.readers[i].files_count() == 0 || self.target_kinds.get(i).copied().flatten().is_some_and(|k| k.is_lib()) {
279                    filtered.push(i);
280                }
281            }
282            if any_exact {
283                return Some(filtered);
284            }
285        }
286        Some(top)
287    }
288
289    /// Returns reader indices prioritized for querying items in `file`:
290    /// matching readers first (ordered with library targets before tests/benchmarks),
291    /// followed by any remaining workspace readers.
292    pub fn candidate_reader_indices_for_file(&self, file: &str) -> Vec<usize> {
293        let raw_candidates = self.reader_indices_for_file(file);
294        let mut candidates: Vec<usize> = raw_candidates
295            .into_iter()
296            .filter(|&idx| {
297                let is_non_lib = self.target_kinds.get(idx).copied().flatten().map(|k| !k.is_lib()).unwrap_or(false);
298                if is_non_lib {
299                    if self.readers[idx].files_count() > 0 {
300                        self.target_file_for_reader(idx, file).is_some()
301                    } else {
302                        true
303                    }
304                } else {
305                    true
306                }
307            })
308            .collect();
309        candidates.sort_by_key(|&idx| if self.target_kinds.get(idx).copied().flatten().map(|k| k.is_lib()).unwrap_or(false) { 0 } else { 1 });
310        let mut non_dep_others = Vec::new();
311        let mut sysroot_others = Vec::new();
312        let mut dep_others = Vec::new();
313
314        for idx in 0..self.readers.len() {
315            if !candidates.contains(&idx) {
316                let is_inaccessible = self.target_kinds.get(idx).copied().flatten().map(|k| !k.is_lib()).unwrap_or(false);
317                if !is_inaccessible {
318                    let is_sysroot = matches!(self.readers[idx].crate_name(), "core" | "alloc" | "std");
319                    let is_dep = self.reader_is_dependency.get(idx).copied().unwrap_or(false);
320                    if is_sysroot {
321                        sysroot_others.push(idx);
322                    } else if !is_dep {
323                        non_dep_others.push(idx);
324                    } else {
325                        dep_others.push(idx);
326                    }
327                }
328            }
329        }
330        candidates.extend(non_dep_others);
331        candidates.extend(sysroot_others);
332        candidates.extend(dep_others);
333        candidates
334    }
335}