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    /// Whether every compilation unit recording a source hash for `file_path` recorded the same one. A failed build of
169    /// one unit (`lib test` with an error in `mod tests`) leaves that unit's data from the text before while the units
170    /// that built record the new text: no single text then matches all of the file's data.
171    pub fn units_agree_on_source(&self, file_path: &str) -> bool {
172        let mut seen: Option<u64> = None;
173        for idx in self.candidate_reader_indices_for_file(file_path) {
174            // Only the units the file belongs to: another crate's `src/lib.rs` is another file.
175            let Some(target) = self.target_file_for_reader(idx, file_path) else { continue };
176            let (reader, name) = (&self.readers[idx], target.as_ref());
177            let from_reader = reader.find_file_id(name).map(|fid| reader.file_source_hash(fid)).filter(|&h| h != 0);
178            let h = from_reader.or_else(|| self.reader_file_hashes.get(idx).and_then(|m| m.get(name)).copied().filter(|&h| h != 0));
179            match (h, seen) {
180                (Some(h), Some(s)) if h != s => return false,
181                (Some(h), None) => seen = Some(h),
182                _ => {}
183            }
184        }
185        true
186    }
187
188    /// Returns the compiled source hash (from rustc compilation provenance) for a file if available.
189    pub fn source_hash_for_file(&self, file_path: &str) -> Option<u64> {
190        // Fast path: query candidate readers prioritized for this file using in-memory indices
191        if self.path_index.may_match_fast_path(self, file_path) {
192            for idx in self.candidate_reader_indices_for_file(file_path) {
193                if let Some(target_file) = self.target_file_for_reader(idx, file_path) {
194                    let reader = &self.readers[idx];
195                    if let Some(fid) = reader.find_file_id(target_file.as_ref()) {
196                        let h = reader.file_source_hash(fid);
197                        if h != 0 {
198                            return Some(h);
199                        }
200                    }
201                    if let Some(hashes) = self.reader_file_hashes.get(idx) {
202                        if let Some(&h) = hashes.get(target_file.as_ref()) {
203                            if h != 0 {
204                                return Some(h);
205                            }
206                        }
207                    }
208                }
209                if let Some(hashes) = self.reader_file_hashes.get(idx) {
210                    if let Some(&h) = hashes.get(file_path) {
211                        if h != 0 {
212                            return Some(h);
213                        }
214                    }
215                }
216            }
217        }
218        self.path_index.source_hash_slow(self, file_path)
219    }
220}