ridx_format/workspace/navigation/
blast_radius.rs1use super::reference_record::{is_raw_ident_keyword, matches_reference_target, ReferenceTarget};
18use super::*;
19use crate::format::fnv1a_64;
20use std::collections::{HashMap, HashSet};
21use std::path::Path;
22
23const FIELD_KEY_SALT: u64 = 0x9e37_79b9_7f4a_7c15;
24const MACRO_KEY_SALT: u64 = 0xbf58_476d_1ce4_e5b9;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub struct DirectBlastRadius {
29 pub direct_refs: usize,
30 pub files: usize,
31 pub crates: usize,
32}
33
34#[derive(Clone, Copy)]
35struct RawBlastEntry {
36 key_hash: u64,
37 loc_key: u64,
38 file_id: u32,
39 pkg_id: u16,
40}
41
42#[derive(Debug, Clone, Default)]
45pub struct BlastRadiusIndex {
46 counts: HashMap<u64, DirectBlastRadius>,
47}
48
49#[inline]
50fn fnv1a_64_concat(prefix: &str, sep: &str, suffix: &str) -> u64 {
51 let mut hash: u64 = 0xcbf29ce484222325;
52 for &b in prefix.as_bytes().iter().chain(sep.as_bytes()).chain(suffix.as_bytes()) {
53 hash ^= b as u64;
54 hash = hash.wrapping_mul(0x100000001b3);
55 }
56 hash
57}
58
59#[inline]
60fn hash_with_kind(base_hash: u64, kind: DefKind) -> u64 {
61 match kind {
62 DefKind::Field => base_hash ^ FIELD_KEY_SALT,
63 DefKind::Macro => base_hash ^ MACRO_KEY_SALT,
64 _ => base_hash,
65 }
66}
67
68pub(crate) fn normalize_workspace_file_key(ws: &WorkspaceIndex, reader_idx: usize, r_file: &str) -> String {
71 let ws_root = ws.workspace_root.as_deref().or(ws.root_dir.as_deref());
72 let sroot = ws.source_roots.get(reader_idx).and_then(|r| r.as_deref());
73 let p = Path::new(r_file);
74 if p.is_absolute() {
75 if let Some(root) = ws_root {
76 if let Ok(rel) = p.strip_prefix(root) {
77 return rel.to_string_lossy().trim_start_matches("./").to_string();
78 }
79 }
80 return r_file.to_string();
81 }
82 if let (Some(sr), Some(root)) = (sroot, ws_root) {
83 if let Ok(sr_rel) = sr.strip_prefix(root) {
84 if !sr_rel.as_os_str().is_empty() && !p.starts_with(sr_rel) {
85 return sr_rel.join(p).to_string_lossy().trim_start_matches("./").to_string();
86 }
87 }
88 }
89 r_file.trim_start_matches("./").to_string()
90}
91
92pub(crate) fn package_key_for_file(ws: &WorkspaceIndex, reader_idx: usize, norm_file: &str) -> String {
95 for marker in ["/src/", "/tests/", "/benches/", "/examples/"] {
96 if let Some(pos) = norm_file.find(marker) {
97 if pos > 0 {
98 return norm_file[..pos].to_string();
99 }
100 }
101 }
102 if let Some(prefix) = norm_file.strip_suffix("/build.rs") {
103 if !prefix.is_empty() {
104 return prefix.to_string();
105 }
106 }
107 if norm_file.starts_with("src/") || norm_file.starts_with("tests/") || norm_file.starts_with("benches/") || norm_file.starts_with("examples/") || norm_file == "build.rs" {
108 return "<root>".to_string();
109 }
110 if let Some(sr) = ws.source_roots.get(reader_idx).and_then(|r| r.as_deref()) {
111 return sr.to_string_lossy().to_string();
112 }
113 let cname = ws.readers[reader_idx].crate_name();
114 cname.strip_suffix("_test").unwrap_or(cname).to_string()
115}
116
117impl BlastRadiusIndex {
118 pub fn build(ws: &WorkspaceIndex) -> Self {
120 let mut known_crates: HashSet<&str> = HashSet::with_capacity(ws.readers.len() * 2 + 8);
121 for k in ["std", "core", "alloc", "proc_macro", "test"] {
122 known_crates.insert(k);
123 }
124 for r in &ws.readers {
125 known_crates.insert(r.crate_name());
126 }
127 for ext_map in &ws.reader_extern_units {
128 for k in ext_map.keys() {
129 known_crates.insert(k.as_str());
130 }
131 }
132
133 let mut file_interner: HashMap<String, u32> = HashMap::new();
134 let mut pkg_interner: HashMap<String, u16> = HashMap::new();
135 let mut entries: Vec<RawBlastEntry> = Vec::new();
136
137 for (i, reader) in ws.readers.iter().enumerate() {
138 if ws.is_reader_external(i) {
139 continue;
140 }
141 let fcount = reader.files_count();
142 let mut file_map: Vec<(u32, u16)> = Vec::with_capacity(fcount as usize);
143 for fid in 0..fcount {
144 let raw_f = reader.get_file(fid);
145 let norm_f = normalize_workspace_file_key(ws, i, raw_f);
146 let pkg_k = package_key_for_file(ws, i, &norm_f);
147 let next_fid = file_interner.len() as u32;
148 let g_fid = *file_interner.entry(norm_f).or_insert(next_fid);
149 let next_pid = pkg_interner.len() as u16;
150 let g_pid = *pkg_interner.entry(pkg_k).or_insert(next_pid);
151 file_map.push((g_fid, g_pid));
152 }
153
154 let cname = reader.crate_name();
155 for r in reader.references() {
156 let r_kind = DefKind::from(r.kind);
157 let s = r.span();
158 if r_kind != DefKind::Macro && s.start_line() != s.end_line() {
159 continue;
160 }
161 let raw_target = reader.get_str(r.target_path_offset());
162 if raw_target.is_empty() {
163 continue;
164 }
165 let name = raw_target.rsplit("::").next().unwrap_or(raw_target);
166 if r_kind != DefKind::Macro {
167 let width = s.end_col().saturating_sub(s.start_col());
168 let clean_name = name.strip_prefix("r#").unwrap_or(name);
169 let name_chars = clean_name.chars().count() as u32;
170 if r.is_macro_expansion() && width != name_chars && width != name.chars().count() as u32 {
171 continue;
172 }
173 if !r.is_macro_expansion() && width == name_chars + 2 && !is_raw_ident_keyword(clean_name) {
174 continue;
175 }
176 }
177 if !reader.is_name_reference(r) {
178 continue;
179 }
180 let Some(&(g_fid, g_pid)) = file_map.get(s.file_id() as usize) else {
181 continue;
182 };
183 let loc_key = ((g_fid as u64) << 36) | (((s.start_line() as u64) & 0xFFFFF) << 16) | (((s.start_col() as u64) & 0xFF) << 8) | ((s.end_col() as u64) & 0xFF);
184
185 let has_crate_prefix = raw_target.strip_prefix(cname).and_then(|rest| rest.strip_prefix("::")).is_some();
186 let base_hash = if has_crate_prefix {
187 fnv1a_64(raw_target.as_bytes())
188 } else {
189 let first_seg = raw_target.split("::").next().unwrap_or(raw_target);
190 if r.target_def_id() == u32::MAX && raw_target.contains("::") && known_crates.contains(first_seg) {
191 fnv1a_64(raw_target.as_bytes())
192 } else {
193 fnv1a_64_concat(cname, "::", raw_target)
194 }
195 };
196
197 if r_kind == DefKind::Other {
198 for k in [DefKind::Struct, DefKind::Field] {
199 entries.push(RawBlastEntry { key_hash: hash_with_kind(base_hash, k), loc_key, file_id: g_fid, pkg_id: g_pid });
200 }
201 } else {
202 entries.push(RawBlastEntry { key_hash: hash_with_kind(base_hash, r_kind), loc_key, file_id: g_fid, pkg_id: g_pid });
203 }
204 }
205 }
206
207 entries.sort_unstable_by_key(|e| (e.key_hash, e.loc_key));
208 let mut counts = HashMap::new();
209 let mut files_set: HashSet<u32> = HashSet::new();
210 let mut pkgs_set: HashSet<u16> = HashSet::new();
211
212 let mut idx = 0;
213 while idx < entries.len() {
214 let kh = entries[idx].key_hash;
215 files_set.clear();
216 pkgs_set.clear();
217 let mut direct_refs = 0usize;
218 let mut prev_loc = u64::MAX;
219 while idx < entries.len() && entries[idx].key_hash == kh {
220 let e = &entries[idx];
221 if e.loc_key != prev_loc {
222 prev_loc = e.loc_key;
223 direct_refs += 1;
224 files_set.insert(e.file_id);
225 pkgs_set.insert(e.pkg_id);
226 }
227 idx += 1;
228 }
229 counts.insert(kh, DirectBlastRadius { direct_refs, files: files_set.len(), crates: pkgs_set.len() });
230 }
231
232 Self { counts }
233 }
234
235 #[inline]
236 pub fn lookup(&self, global_path: &str, kind: DefKind) -> DirectBlastRadius {
237 let kh = hash_with_kind(fnv1a_64(global_path.as_bytes()), kind);
238 self.counts.get(&kh).copied().unwrap_or_default()
239 }
240}
241
242impl WorkspaceIndex {
243 pub fn direct_blast_radius(&self, def: &ResolvedDefinition<'_>) -> DirectBlastRadius {
246 if def.path.is_empty() || def.kind == DefKind::Local {
247 return DirectBlastRadius::default();
248 }
249 let target_crate = def.reader_idx.and_then(|idx| self.readers.get(idx)).map(|r| r.crate_name()).unwrap_or_else(|| def.path.split("::").next().unwrap_or(def.path));
250 let local_path = def.path.strip_prefix(&format!("{target_crate}::")).unwrap_or(def.path);
251 let global_path = format!("{target_crate}::{local_path}");
252 if self.path_index.is_current(self) {
253 return self.path_index.blast_radius.lookup(&global_path, def.kind);
254 }
255
256 let disambiguate_line = def.reader_idx.is_some_and(|t| {
257 let r = &self.readers[t];
258 r.has_multiple_definitions_at_path(def.path) || r.has_multiple_definitions_at_path(local_path) || r.has_multiple_definitions_at_path(&global_path)
259 });
260
261 let ref_target = ReferenceTarget {
262 kind: Some(def.kind),
263 name: Some(def.name),
264 coords: (!def.file.is_empty() && def.start_line > 0).then(|| (def.file.to_string(), def.file.to_string(), def.start_line)),
265 disambiguate_line,
266 is_qualified_path: def.path.contains("::"),
267 };
268
269 let mut seen_refs: HashSet<(String, u32, u32, u32)> = HashSet::new();
270 let mut files: HashSet<String> = HashSet::new();
271 let mut crates: HashSet<String> = HashSet::new();
272
273 for (i, reader) in self.readers.iter().enumerate() {
274 if self.is_reader_external(i) {
275 continue;
276 }
277 let cname = reader.crate_name();
278 let queries: &[&str] = if cname == target_crate && local_path != global_path { &[local_path, global_path.as_str()] } else { &[global_path.as_str()] };
279 for &q in queries {
280 for r in reader.find_references(q) {
281 if !matches_reference_target(reader, r, &ref_target) {
282 continue;
283 }
284 let s = r.span();
285 let norm_f = normalize_workspace_file_key(self, i, reader.get_file(s.file_id()));
286 if seen_refs.insert((norm_f.clone(), s.start_line(), s.start_col(), s.end_col())) {
287 let pkg_k = package_key_for_file(self, i, &norm_f);
288 files.insert(norm_f);
289 crates.insert(pkg_k);
290 }
291 }
292 }
293 }
294
295 DirectBlastRadius { direct_refs: seen_refs.len(), files: files.len(), crates: crates.len() }
296 }
297}