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            if let Some(cs) = canon_p.to_str() {
41                if let Some(found) = lookup_stored(cs) {
42                    return Some(found);
43                }
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 p_clean = is_clean_posix_bytes(p.as_os_str().as_encoded_bytes());
100        let root_opt = self.reader_root(reader_idx);
101
102        if p.is_absolute() {
103            if let Some(fid) = self.reader_find_file_id(reader_idx, file) {
104                return Some(fid);
105            }
106            let matches_container = if let Some(root) = root_opt {
107                if root.is_absolute() {
108                    fast_path_starts_with(p, p_clean, root)
109                } else if let Some(ws_root) = &self.workspace_root {
110                    p.starts_with(ws_root.join(root))
111                } else {
112                    false
113                }
114            } else if let Some(ws_root) = &self.workspace_root {
115                fast_path_starts_with(p, p_clean, ws_root)
116            } else {
117                true
118            };
119            if matches_container {
120                if let Some(ws_root) = &self.workspace_root {
121                    if let Some(s) = p.strip_prefix(ws_root).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                if let Some(root) = root_opt {
128                    if let Some(s) = p.strip_prefix(root).ok().and_then(|r| r.to_str()) {
129                        if let Some(fid) = self.reader_find_file_id(reader_idx, s) {
130                            return Some(fid);
131                        }
132                    }
133                }
134            }
135            return self.canonical_target_for_reader(reader_idx, p, false).and_then(|(_, fid)| fid);
136        }
137
138        if let Some(fid) = self.reader_find_file_id(reader_idx, file) {
139            return Some(fid);
140        }
141        let roots = [self.workspace_root.as_deref(), root_opt];
142        for anchor in roots.into_iter().flatten() {
143            let joined = anchor.join(p);
144            if let Some(s) = joined.to_str() {
145                if let Some(fid) = self.reader_find_file_id(reader_idx, s) {
146                    return Some(fid);
147                }
148            }
149            for base in roots.into_iter().flatten() {
150                if let Some(s) = joined.strip_prefix(base).ok().and_then(|r| r.to_str()) {
151                    if let Some(fid) = self.reader_find_file_id(reader_idx, s) {
152                        return Some(fid);
153                    }
154                }
155            }
156        }
157        self.canonical_target_for_reader(reader_idx, p, false).and_then(|(_, fid)| fid)
158    }
159
160    /// Returns prioritized `(reader_idx, file_id)` pairs for `file` (library targets first).
161    pub fn resolved_reader_file_ids(&self, file: &str) -> Vec<(usize, u32)> {
162        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();
163        if !direct.is_empty() {
164            direct.sort_by_key(|&(idx, _)| usize::from(!self.target_kinds.get(idx).copied().flatten().is_some_and(|k| k.is_lib())));
165            return direct;
166        }
167        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()
168    }
169
170    /// Resolves `file` (absolute, relative to the workspace root, or relative to the reader's
171    /// source root) to the path string the reader at `reader_idx` stores for it, or `None` when
172    /// this reader does not index the file. Every string returned is accepted by that reader's
173    /// exact `find_file_id`: the input is re-expressed in the reader's coordinates (relative to
174    /// the workspace root or to the source root) and compared whole, never by suffix.
175    pub fn target_file_for_reader<'a>(&self, reader_idx: usize, file: &'a str) -> Option<std::borrow::Cow<'a, str>> {
176        let _ = self.readers.get(reader_idx)?;
177        let p = Path::new(file);
178        let p_clean = is_clean_posix_bytes(p.as_os_str().as_encoded_bytes());
179        let root_opt = self.reader_root(reader_idx);
180        let stored = |s: &str| self.reader_find_file_id(reader_idx, s).is_some();
181        let owned = |s: &str| Some(std::borrow::Cow::Owned(s.to_string()));
182
183        if p.is_absolute() {
184            // C. Stored as an absolute path: the reader names this very file, whatever the roots.
185            if stored(file) {
186                return Some(std::borrow::Cow::Borrowed(file));
187            }
188            // Otherwise the file must lie under the reader's source root, else under the
189            // workspace root, before it is re-expressed in the reader's coordinates.
190            let matches_container = if let Some(root) = root_opt {
191                if root.is_absolute() {
192                    fast_path_starts_with(p, p_clean, root)
193                } else if let Some(ws_root) = &self.workspace_root {
194                    p.starts_with(ws_root.join(root))
195                } else {
196                    false
197                }
198            } else if let Some(ws_root) = &self.workspace_root {
199                fast_path_starts_with(p, p_clean, ws_root)
200            } else {
201                true
202            };
203            if matches_container {
204                // A. Relative to the workspace root (workspace crates).
205                if let Some(ws_root) = &self.workspace_root {
206                    if let Some(s) = p.strip_prefix(ws_root).ok().and_then(|r| r.to_str()) {
207                        if stored(s) {
208                            return owned(s);
209                        }
210                    }
211                }
212                // B. Relative to the source root (dependencies indexed from their package root).
213                if let Some(root) = root_opt {
214                    if let Some(s) = p.strip_prefix(root).ok().and_then(|r| r.to_str()) {
215                        if stored(s) {
216                            return owned(s);
217                        }
218                    }
219                }
220            }
221            return self.canonical_target_for_reader(reader_idx, p, false).map(|(s, _)| std::borrow::Cow::Owned(s));
222        }
223
224        // Relative input: the stored form itself; else the path anchored to the workspace root or
225        // to the source root and re-expressed relative to each of them, which are the two stored
226        // forms (`src/lib.rs` typed for the crate stored as `serde/src/lib.rs` becomes
227        // `<ws>/serde/src/lib.rs`, then `serde/src/lib.rs`). A bare relative path that no root
228        // anchors to a stored file is not resolved.
229        if stored(file) {
230            return Some(std::borrow::Cow::Borrowed(file));
231        }
232        let roots = [self.workspace_root.as_deref(), root_opt];
233        for anchor in roots.into_iter().flatten() {
234            let joined = anchor.join(p);
235            if let Some(s) = joined.to_str() {
236                if stored(s) {
237                    return owned(s);
238                }
239            }
240            for base in roots.into_iter().flatten() {
241                if let Some(s) = joined.strip_prefix(base).ok().and_then(|r| r.to_str()) {
242                    if stored(s) {
243                        return owned(s);
244                    }
245                }
246            }
247        }
248        // Readers that know the file only through their recorded hashes (an empty file table):
249        // the sidecar records both forms, the absolute one is compared here.
250        if let Some(hashes) = self.reader_file_hashes.get(reader_idx) {
251            for anchor in roots.into_iter().flatten() {
252                if let Some(s) = anchor.join(p).to_str() {
253                    if hashes.contains_key(s) {
254                        return owned(s);
255                    }
256                }
257            }
258        }
259        self.canonical_target_for_reader(reader_idx, p, true).map(|(s, _)| std::borrow::Cow::Owned(s))
260    }
261
262    /// Matches `p` (and `abs_p`) against reader `source_roots` using longest prefix match.
263    #[allow(clippy::too_many_arguments)]
264    pub(super) fn match_source_roots(
265        &self,
266        p: &Path,
267        file_path: &str,
268        p_clean: bool,
269        abs_p: Option<&Path>,
270        abs_p_clean: bool,
271        ws_root: Option<&Path>,
272        canonicalize_roots: bool,
273    ) -> Option<Vec<usize>> {
274        let mut matching_roots: Vec<(usize, usize, usize)> = Vec::new();
275        let mut last_root_meta: Option<(&Path, bool, usize, usize)> = None;
276        for (i, _) in self.readers.iter().enumerate() {
277            if let Some(root) = self.reader_root(i) {
278                if !root.as_os_str().is_empty() {
279                    let (matches, comps, len) = match last_root_meta {
280                        Some((prev, m, c, l)) if prev == root => (m, c, l),
281                        _ => {
282                            let resolved_owned;
283                            let root_cmp = if canonicalize_roots {
284                                resolved_owned = if root.is_absolute() {
285                                    crate::paths::canonicalize_cached(root)
286                                } else if let Some(ws) = ws_root {
287                                    crate::paths::canonicalize_cached(&ws.join(root))
288                                } else {
289                                    crate::paths::canonicalize_cached(root)
290                                };
291                                resolved_owned.as_path()
292                            } else {
293                                root
294                            };
295                            let m = fast_path_starts_with(p, p_clean, root_cmp)
296                                || abs_p.is_some_and(|ap| fast_path_starts_with(ap, abs_p_clean, root_cmp))
297                                || (!canonicalize_roots && p.is_absolute() && root.is_relative() && ws_root.is_some_and(|ws| p.starts_with(ws.join(root))));
298                            let (c, l) = if m { (root_cmp.components().count(), root_cmp.as_os_str().len()) } else { (0, 0) };
299                            last_root_meta = Some((root, m, c, l));
300                            (m, c, l)
301                        }
302                    };
303                    if matches {
304                        matching_roots.push((i, comps, len));
305                    }
306                }
307            }
308        }
309        let (_, max_comps, max_len) = matching_roots.iter().max_by_key(|(_, comps, len)| (*comps, *len)).copied()?;
310        let top: Vec<usize> = matching_roots.into_iter().filter(|(_, comps, len)| *comps == max_comps && *len == max_len).map(|(i, _, _)| i).collect();
311        if top.len() > 1 {
312            let ws_rel = ws_root.and_then(|ws| p.strip_prefix(ws).ok()).and_then(|r| r.to_str());
313            let mut filtered = Vec::with_capacity(top.len());
314            let mut any_exact = false;
315            let fast_valid = self.unit_match.is_valid_for_readers(&self.readers);
316            let exact_full = if fast_valid { self.unit_match.readers_for_clean_file(file_path) } else { None };
317            let exact_rel = if fast_valid {
318                match ws_rel {
319                    Some(rel) => self.unit_match.readers_for_clean_file(rel),
320                    None => Some(&[][..]),
321                }
322            } else {
323                None
324            };
325            for &i in &top {
326                let exact = if let (Some(ef), Some(er)) = (exact_full, exact_rel) {
327                    if !self.unit_match.reader_has_special(i) {
328                        ef.binary_search_by_key(&i, |&(r, _)| r).is_ok() || er.binary_search_by_key(&i, |&(r, _)| r).is_ok()
329                    } else {
330                        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())
331                    }
332                } else {
333                    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())
334                };
335                if exact {
336                    any_exact = true;
337                }
338                if exact || self.readers[i].files_count() == 0 || self.target_kinds.get(i).copied().flatten().is_some_and(|k| k.is_lib()) {
339                    filtered.push(i);
340                }
341            }
342            if any_exact {
343                return Some(filtered);
344            }
345        }
346        Some(top)
347    }
348
349    /// Returns reader indices prioritized for querying items in `file`:
350    /// matching readers first (ordered with library targets before tests/benchmarks),
351    /// followed by any remaining workspace readers.
352    pub fn candidate_reader_indices_for_file(&self, file: &str) -> Vec<usize> {
353        let raw_candidates = self.reader_indices_for_file(file);
354        let mut candidates: Vec<usize> = raw_candidates
355            .into_iter()
356            .filter(|&idx| {
357                let is_non_lib = self.target_kinds.get(idx).copied().flatten().map(|k| !k.is_lib()).unwrap_or(false);
358                if is_non_lib {
359                    if self.readers[idx].files_count() > 0 {
360                        self.target_file_for_reader(idx, file).is_some()
361                    } else {
362                        true
363                    }
364                } else {
365                    true
366                }
367            })
368            .collect();
369        candidates.sort_by_key(|&idx| if self.target_kinds.get(idx).copied().flatten().map(|k| k.is_lib()).unwrap_or(false) { 0 } else { 1 });
370        let mut non_dep_others = Vec::new();
371        let mut sysroot_others = Vec::new();
372        let mut dep_others = Vec::new();
373
374        for idx in 0..self.readers.len() {
375            if !candidates.contains(&idx) {
376                let is_inaccessible = self.target_kinds.get(idx).copied().flatten().map(|k| !k.is_lib()).unwrap_or(false);
377                if !is_inaccessible {
378                    let is_sysroot = matches!(self.readers[idx].crate_name(), "core" | "alloc" | "std");
379                    let is_dep = self.reader_is_dependency.get(idx).copied().unwrap_or(false);
380                    if is_sysroot {
381                        sysroot_others.push(idx);
382                    } else if !is_dep {
383                        non_dep_others.push(idx);
384                    } else {
385                        dep_others.push(idx);
386                    }
387                }
388            }
389        }
390        candidates.extend(non_dep_others);
391        candidates.extend(sysroot_others);
392        candidates.extend(dep_others);
393        candidates
394    }
395}