Skip to main content

ridx_format/workspace/
provenance.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//! Source provenance, hash resolution, and shard metadata loading.
12
13mod metadata;
14#[cfg(test)]
15mod tests;
16
17use super::target_kind;
18use super::WorkspaceIndex;
19#[cfg(test)]
20use crate::paths::normalize_path;
21use std::fs;
22use std::path::{Path, PathBuf};
23
24/// Checks whether a path contains a `ParentDir` (`..`) that pops across a symlink component,
25/// meaning lexical normalization would diverge from the true filesystem target.
26pub(crate) fn path_traverses_symlink_parent(path: &Path) -> bool {
27    let mut current = PathBuf::new();
28    for c in path.components() {
29        match c {
30            std::path::Component::Normal(seg) => {
31                current.push(seg);
32            }
33            std::path::Component::ParentDir => {
34                if let Ok(meta) = fs::symlink_metadata(&current) {
35                    if meta.file_type().is_symlink() {
36                        return true;
37                    }
38                }
39                current.pop();
40            }
41            std::path::Component::RootDir | std::path::Component::Prefix(_) => {
42                current.push(c);
43            }
44            std::path::Component::CurDir => {}
45        }
46    }
47    false
48}
49
50/// Matches an entry path from an index shard or sidecar map against a requested file path.
51/// Resolves real filesystem identity for both entry and request before any lexical collapse,
52/// guaranteeing that lexical collapse never overrides known unequal canonical paths.
53#[cfg(test)]
54pub(crate) fn file_entry_matches(entry_str: &str, reader_origin: Option<&Path>, req_path: &Path, req_canon: Option<&Path>) -> bool {
55    if entry_str.is_empty() {
56        return false;
57    }
58
59    // 0. Fast literal string match before any filesystem syscalls
60    if entry_str == req_path.to_str().unwrap_or("") {
61        return true;
62    }
63
64    let entry_p = Path::new(entry_str);
65
66    // 1. Resolve original uncollapsed entry path under reader's origin
67    let entry_orig = if entry_p.is_absolute() {
68        entry_p.to_path_buf()
69    } else if let Some(orig) = reader_origin {
70        orig.join(entry_p)
71    } else {
72        entry_p.to_path_buf()
73    };
74
75    // 1b. Fast path equality before filesystem syscalls
76    if entry_orig == req_path {
77        return true;
78    }
79
80    // 2. Resolve canonical identities on the filesystem before any lexical collapse
81    use super::path_index_tests::oracle::cached_canonicalize;
82    let entry_canon = cached_canonicalize(&entry_orig);
83    let effective_req_canon = req_canon.map(Path::to_path_buf).or_else(|| req_path.is_absolute().then(|| cached_canonicalize(req_path))?);
84
85    // 3. Authoritative filesystem identity comparison
86    if let (Some(ref c_entry), Some(ref c_req)) = (&entry_canon, &effective_req_canon) {
87        if c_entry == c_req {
88            return true;
89        }
90        // When both filesystem identities are known and unequal,
91        // lexical collapse MUST NOT override known unequal canonical paths.
92        return false;
93    }
94
95    // 4. Literal string match (only when canonical comparison did not rule it out)
96    if entry_str == req_path.to_str().unwrap_or("") {
97        return true;
98    }
99
100    // 5. Lexical fallback: only allowed where it cannot reinterpret a symlink traversal
101    if path_traverses_symlink_parent(&entry_orig)
102        || path_traverses_symlink_parent(req_path)
103        || reader_origin.is_some_and(|orig| path_traverses_symlink_parent(&orig.join(req_path)))
104    {
105        return false;
106    }
107
108    let norm_entry = normalize_path(&entry_orig);
109
110    if req_path.is_absolute() {
111        let norm_req = normalize_path(req_path);
112        if norm_entry == norm_req {
113            return true;
114        }
115    } else {
116        // Requested path is relative (e.g. "src/lib.rs")
117        let norm_req = normalize_path(req_path);
118        if norm_entry.is_relative() {
119            if norm_entry == norm_req {
120                return true;
121            }
122        } else if let Some(orig) = reader_origin {
123            let norm_orig = normalize_path(orig);
124            if let Ok(rel) = norm_entry.strip_prefix(&norm_orig) {
125                if rel == norm_req || normalize_path(rel) == norm_req {
126                    return true;
127                }
128            }
129            if let (Some(ref c_entry), Some(c_orig)) = (&entry_canon, cached_canonicalize(orig)) {
130                if let Ok(rel) = c_entry.strip_prefix(&c_orig) {
131                    if rel == norm_req || normalize_path(rel) == norm_req {
132                        return true;
133                    }
134                }
135            }
136        }
137    }
138    false
139}
140
141impl WorkspaceIndex {
142    /// Returns the file modification timestamp of the index shard containing the given source file.
143    pub fn shard_mtime_for_file(&self, file_path: &str) -> Option<std::time::SystemTime> {
144        // Fast path: query candidate readers prioritized for this file using in-memory indices
145        if self.path_index.may_match_fast_path(self, file_path) {
146            for idx in self.candidate_reader_indices_for_file(file_path) {
147                if let Some(target_file) = self.target_file_for_reader(idx, file_path) {
148                    let reader = &self.readers[idx];
149                    if reader.find_file_id(target_file.as_ref()).is_some() {
150                        return self.mtimes.get(idx).copied().flatten();
151                    }
152                    if let Some(hashes) = self.reader_file_hashes.get(idx) {
153                        if hashes.contains_key(target_file.as_ref()) {
154                            return self.mtimes.get(idx).copied().flatten();
155                        }
156                    }
157                }
158                if let Some(hashes) = self.reader_file_hashes.get(idx) {
159                    if hashes.contains_key(file_path) {
160                        return self.mtimes.get(idx).copied().flatten();
161                    }
162                }
163            }
164        }
165        self.path_index.shard_mtime_slow(self, file_path)
166    }
167
168    /// Records the `own_sources` of the sidecar just loaded for the shard at `path`, or forgets them when it has none.
169    pub(crate) fn set_own_sources(&mut self, path: &Path, own: Option<std::collections::HashSet<String>>) {
170        match own {
171            Some(own) => self.own_sources.insert(path.to_path_buf(), own),
172            None => self.own_sources.remove(path),
173        };
174    }
175
176    /// The reader's root as routing resolves it: a relative recorded root (`source_root: "shop"`) lies under the workspace
177    /// root, never under the process's working directory (review of bbed0a7e).
178    fn rooted_reader_root(&self, idx: usize) -> Option<PathBuf> {
179        let root = self.reader_root(idx)?;
180        Some(match self.workspace_root.as_deref() {
181            Some(ws) if root.is_relative() => ws.join(root),
182            _ => root.to_path_buf(),
183        })
184    }
185
186    /// The names the sidecar of reader `idx` may record one file under: its path as given, its canonical path, and its
187    /// path relative to the reader's root, then to the workspace root (from the given and the canonical spellings of
188    /// both), with that relative path joined back onto the root as it is spelled. All of them name `file` only: never a
189    /// union of alternative resolutions, which may be other files (review of c94616ac).
190    fn names_of_one_file(&self, idx: usize, file: &Path) -> Vec<String> {
191        let canonical = crate::canonicalize_best_effort(file);
192        let mut names = vec![file.display().to_string(), canonical.display().to_string()];
193        for root in [self.rooted_reader_root(idx), self.workspace_root.clone()].into_iter().flatten() {
194            let canonical_root = crate::canonicalize_best_effort(&root);
195            for rel in [file.strip_prefix(&root).ok(), canonical.strip_prefix(&canonical_root).ok()].into_iter().flatten() {
196                names.push(rel.display().to_string());
197                names.push(root.join(rel).display().to_string());
198            }
199        }
200        let mut seen = std::collections::HashSet::new();
201        names.retain(|n| seen.insert(n.clone()));
202        names
203    }
204
205    /// The one file `query` names for reader `idx`, which path routing stores as `key` (`None`: not routed). An absolute
206    /// query is that file as spelled, whatever form routing stores it in (relative to the workspace or to the reader's
207    /// root: review of 4d8906dc). A relative query is the workspace's, else the reader root's: the first of them whose
208    /// file routing stored as `key`, as spelled or, as routing canonicalizes a candidate, through its canonical path
209    /// against the canonical roots (`W/shop/alias -> W/shop/src`: `alias/gen.rs` is `src/gen.rs` of `W/shop`, review of
210    /// a0634347); an absolute `key` is that file itself. The file keeps the query's spelling.
211    fn file_of_query(&self, idx: usize, query: &str, key: Option<&str>) -> PathBuf {
212        let q = Path::new(query);
213        if q.is_absolute() {
214            return q.to_path_buf();
215        }
216        if let Some(k) = key.filter(|k| Path::new(k).is_absolute()) {
217            return PathBuf::from(k);
218        }
219        let anchors: Vec<PathBuf> = [self.workspace_root.clone(), self.rooted_reader_root(idx)].into_iter().flatten().collect();
220        let files: Vec<PathBuf> = anchors.iter().map(|a| a.join(q)).collect();
221        let Some(k) = key else { return files.first().cloned().unwrap_or_else(|| q.to_path_buf()) };
222        let is_key = |file: &Path, roots: &[PathBuf]| roots.iter().any(|a| file.strip_prefix(a).ok().and_then(|r| r.to_str()) == Some(k));
223        if let Some(f) = files.iter().find(|f| is_key(f, &anchors)) {
224            return f.clone();
225        }
226        let canonical: Vec<PathBuf> = anchors.iter().map(|a| crate::canonicalize_best_effort(a)).collect();
227        files.iter().find(|f| is_key(&crate::canonicalize_best_effort(f), &canonical)).or(files.first()).cloned().unwrap_or_else(|| q.to_path_buf())
228    }
229
230    /// The hash the sidecar of reader `idx` recorded for the file `query` names (routing stores it as `key`) that has no
231    /// entry in its shard, unless the unit only read the file through a dependency: the sidecar loaded with the reader
232    /// lists its own sources (`own_sources`) and the file is not among them. Both come from the same bytes, kept in
233    /// memory: a sidecar rewritten on disk since never changes the answer (review of 2f7a84e3). The hash and the
234    /// ownership are looked up under the names of that one file: the query as spelled, the stored key, and the
235    /// absolute, canonical and relative names of the file. Without `own_sources` the unit counts as holding the file: a
236    /// doubt is a disagreement, never a coverage (review of 9f9c7bba).
237    fn sidecar_only_hash(&self, idx: usize, query: &str, key: Option<&str>) -> Option<u64> {
238        let hashes = self.reader_file_hashes.get(idx)?;
239        let file = self.file_of_query(idx, query, key);
240        let mut names = self.names_of_one_file(idx, &file);
241        names.extend(key.filter(|k| !names.iter().any(|n| n == k)).map(str::to_string));
242        let h = names.iter().find_map(|n| hashes.get(n.as_str())).copied().filter(|&h| h != 0)?;
243        let not_own = self.paths.get(idx).and_then(|p| self.own_sources.get(p)).is_some_and(|own| !names.iter().any(|n| own.contains(n)));
244        (!not_own).then_some(h)
245    }
246
247    /// Whether every compilation unit recording a source hash for `file_path` recorded the same one. A failed build of
248    /// one unit (`lib test` with an error in `mod tests`) leaves that unit's data from the text before while the units
249    /// that built record the new text: no single text then matches all of the file's data.
250    /// Every unit, not the candidates navigation ranks (those prefer the innermost source root): an integration test
251    /// of an outer package including the file with `#[path]` holds it too (review of 503071cb). Dependencies hold no
252    /// workspace file.
253    pub fn units_agree_on_source(&self, file_path: &str) -> bool {
254        let mut seen: Option<u64> = None;
255        for idx in (0..self.readers.len()).filter(|&i| !self.reader_is_dependency.get(i).copied().unwrap_or(false)) {
256            // Only the units the file belongs to: another crate's `src/lib.rs` is another file.
257            // A file with an entry in the reader's shard was compiled by it; one with only a hash in its sidecar (brought
258            // in with `include!`, or read through a dependency's metadata) is weighed by `sidecar_only_hash`, whether
259            // asked for by an absolute or a relative path (reviews of 3650f8e3 and 9f9c7bba).
260            let target = self.target_file_for_reader(idx, file_path);
261            let key = target.as_deref().unwrap_or(file_path);
262            let reader = &self.readers[idx];
263            let h = match reader.find_file_id(key) {
264                Some(fid) => Some(reader.file_source_hash(fid)).filter(|&h| h != 0).or_else(|| self.sidecar_only_hash(idx, file_path, target.as_deref())),
265                None => self.sidecar_only_hash(idx, file_path, target.as_deref()),
266            };
267            match (h, seen) {
268                (Some(h), Some(s)) if h != s => return false,
269                (Some(h), None) => seen = Some(h),
270                _ => {}
271            }
272        }
273        true
274    }
275
276    /// Returns the compiled source hash (from rustc compilation provenance) for a file if available.
277    pub fn source_hash_for_file(&self, file_path: &str) -> Option<u64> {
278        // Fast path: query candidate readers prioritized for this file using in-memory indices
279        if self.path_index.may_match_fast_path(self, file_path) {
280            for idx in self.candidate_reader_indices_for_file(file_path) {
281                if let Some(target_file) = self.target_file_for_reader(idx, file_path) {
282                    let reader = &self.readers[idx];
283                    if let Some(fid) = reader.find_file_id(target_file.as_ref()) {
284                        let h = reader.file_source_hash(fid);
285                        if h != 0 {
286                            return Some(h);
287                        }
288                    }
289                    if let Some(hashes) = self.reader_file_hashes.get(idx) {
290                        if let Some(&h) = hashes.get(target_file.as_ref()) {
291                            if h != 0 {
292                                return Some(h);
293                            }
294                        }
295                    }
296                }
297                if let Some(hashes) = self.reader_file_hashes.get(idx) {
298                    if let Some(&h) = hashes.get(file_path) {
299                        if h != 0 {
300                            return Some(h);
301                        }
302                    }
303                }
304            }
305        }
306        self.path_index.source_hash_slow(self, file_path)
307    }
308}