1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
* rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
* Copyright (c) 2026 Alexander Panasenko
*
* Contact: alex@prod.codes
* Author: https://prod.codes/about/
* Project: https://github.com/alex09x/rust-intelligence
* SPDX-License-Identifier: MIT OR Apache-2.0
*/
//! An absolute path in the coordinates a reader stores its files in, looked up by spelling, and the workspace crates
//! that compile a file from outside their package.
use super::{fast_path_starts_with, is_clean_posix_bytes};
use crate::paths::{canonicalize_cached, normalize_path, resolve_cached};
use crate::workspace::WorkspaceIndex;
use std::collections::HashSet;
use std::path::{Component, Path};
impl WorkspaceIndex {
/// `top`, the readers whose source root holds `file_path`, unless none of them compiles it while workspace crates
/// elsewhere do: they include it from outside their package by `#[path]` (a `crates/core` that takes all of `src/`,
/// the root package's directory, from modules the root package's own crates do not compile). Then those crates.
pub(super) fn or_includers(&self, top: Vec<usize>, file_path: &str) -> Vec<usize> {
let p = Path::new(file_path);
let ws = self.workspace_root.as_deref();
let anchored = ws.filter(|_| p.is_relative()).map(|ws| ws.join(p));
let abs = anchored.as_deref().unwrap_or(p);
let names: Vec<&str> = [Some(file_path), anchored.as_deref().and_then(Path::to_str)].into_iter().flatten().collect();
// The file as the file system resolves it, once per request and remembered: own sources are recorded that way, and
// an includer may store a linked file by its target (review of PR #22).
let resolved = std::cell::OnceCell::new();
let canonical = || resolved.get_or_init(|| abs.is_absolute().then(|| canonicalize_cached(abs)).filter(|c| c != abs)).as_deref();
// A reader also holds a file its sidecar hashes, as a reader with an empty file table knows its files, but only
// as one of its own sources when it lists them: a unit hashes files it only read spans from too, a dependency's
// generic or inline item, which another crate compiles (reviews of PR #22).
// Both under the names asked for and under the resolved one (review of PR #22).
let named = |set: &dyn Fn(&str) -> bool| names.iter().any(|n| set(n)) || canonical().and_then(Path::to_str).is_some_and(set);
let recorded = |i: usize| {
let hashed = self.reader_file_hashes.get(i).is_some_and(|h| named(&|n| h.contains_key(n)));
let own = self.paths.get(i).and_then(|path| self.own_sources.get(path));
hashed && own.is_none_or(|own: &HashSet<String>| named(&|n| own.contains(n)))
};
if top.iter().any(|&i| self.target_file_id_for_reader(i, file_path).is_some() || recorded(i)) {
return top;
}
// The candidates come from the tables of stored spellings, under the request's path and the one it resolves to, as
// given and relative to the workspace root: proving that no crate includes a new file costs a few hash lookups,
// not a scan of every package (review of PR #22). Without valid tables, every reader is a candidate.
let mut candidates: Vec<usize> = (0..self.readers.len()).filter(|&i| !self.is_reader_dependency(i) && recorded(i)).collect();
let um = &self.unit_match;
if um.is_valid_for_readers(&self.readers) {
for q in std::iter::once(abs).chain(canonical()) {
for key in [q.to_str(), ws.and_then(|w| q.strip_prefix(w).ok()).and_then(|r| r.to_str())].into_iter().flatten() {
candidates.extend(um.file_to_readers.get(key).into_iter().chain(um.dotted_files.get(key)).flatten().map(|&(r, _)| r));
}
}
} else {
candidates.extend(0..self.readers.len());
}
candidates.sort_unstable();
candidates.dedup();
// Each one confirmed by spelling, never resolving paths of other packages (`lexical_file_id`).
let spelled = |i: usize, q: &Path| {
if q.is_absolute() {
self.lexical_file_id(i, q, is_clean_posix_bytes(q.as_os_str().as_encoded_bytes())).is_some()
} else {
q.to_str().is_some_and(|s| self.reader_find_file_id(i, s).is_some())
}
};
let includes = |i: usize| recorded(i) || spelled(i, abs) || canonical().is_some_and(|c| spelled(i, c));
let includers: Vec<usize> = candidates.into_iter().filter(|&i| !self.is_reader_dependency(i) && !top.contains(&i) && includes(i)).collect();
if includers.is_empty() {
top
} else {
includers
}
}
/// `p` (absolute) as the reader at `reader_idx` may store it, to try in order: relative to the workspace root, then
/// relative to the reader's source root, each with the root it is relative to. A file under the reader's source root
/// (under the workspace root, for a reader that records none) is tried in both forms. A workspace crate stores every
/// file relative to the workspace root, also one outside its package that it includes by `#[path]` or `include!`
/// (`crates/core/src/../../../src/api/client.rs`), so for it a file anywhere under the workspace root is tried in that
/// form as well: a crate that takes all of the root package's `src/` that way had no go to definition in those files.
/// A dependency stores its paths relative to its own package, where that form would name another file.
fn stored_forms_of_absolute<'p, 's>(&'s self, reader_idx: usize, p: &'p Path, p_clean: bool) -> [Option<(&'p str, &'s Path)>; 2] {
let root_opt = self.reader_root(reader_idx);
let ws_opt = self.workspace_root.as_deref();
let in_root = match (root_opt, ws_opt) {
(Some(root), _) if root.is_absolute() => fast_path_starts_with(p, p_clean, root),
(Some(root), Some(ws)) => p.starts_with(ws.join(root)),
(Some(_), None) => false,
(None, Some(ws)) => fast_path_starts_with(p, p_clean, ws),
(None, None) => true,
};
let relative_to = |base: &'s Path| p.strip_prefix(base).ok().and_then(|r| r.to_str()).map(|s| (s, base));
let ws_rel = ws_opt.filter(|_| in_root || !self.is_reader_dependency(reader_idx)).and_then(relative_to);
let root_rel = root_opt.filter(|_| in_root).and_then(relative_to);
[ws_rel, root_rel]
}
/// The file id of the absolute `p` in the file table of the reader at `reader_idx`, and the spelling that found it:
/// `p` as stored, else one of its stored forms, compared without the file system. A stored spelling with `..` (a
/// `#[path]` from outside the package) is taken only when it reaches `p` on the file system: through a symlinked
/// directory `..` leads elsewhere than its lexical reading. A `p` on disk needs the spelling to resolve to it, and a
/// spelling that does not resolve at all (a directory on the way gone) is no proof; only a `p` not on disk (a buffer
/// never saved) is compared by its lexical reading (reviews of PR #22). Resolutions are remembered, so the check
/// costs no file system call after the first.
pub(crate) fn lexical_file_id<'p>(&self, reader_idx: usize, p: &'p Path, p_clean: bool) -> Option<(u32, &'p str)> {
let (reader, file) = (self.readers.get(reader_idx)?, p.to_str()?);
let mut forms = std::iter::once((file, None)).chain(self.stored_forms_of_absolute(reader_idx, p, p_clean).into_iter().flatten().map(|(s, base)| (s, Some(base))));
let (fid, spelling, base) = forms.find_map(|(s, base)| self.reader_find_file_id(reader_idx, s).map(|fid| (fid, s, base)))?;
let stored = Path::new(reader.get_file(fid));
if stored.components().any(|c| c == Component::ParentDir) {
let stored_abs = base.filter(|_| stored.is_relative()).map_or_else(|| stored.to_path_buf(), |b| b.join(stored));
// Not on disk is a missing path; any other failure to resolve `p` (a directory it may not read) proves
// nothing (review of PR #22, round 7).
let missing = || std::fs::symlink_metadata(p).is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory));
let same = match resolve_cached(p) {
Some(on_disk) => resolve_cached(&stored_abs).is_some_and(|s| s == on_disk),
None => missing() && normalize_path(&stored_abs) == normalize_path(p),
};
if !same {
return None;
}
}
Some((fid, spelling))
}
}