Skip to main content

ridx_format/workspace/
rename_cache.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//! Per-workspace precomputed rename index: Cargo target tables, associated-item reference lookup,
12//! `macro_rules!` expansion body index, `proc-macro` source Coupling cache, and unindexed targets.
13
14use super::cargo_targets::CargoWorkspaceTargets;
15use super::rename_factory_idx::{build_factory_return_index, FactoryFnCandidate};
16use super::rename_parse::{
17    extract_macro_rules_blocks, has_self_receiver, parse_unindexed_rust_file, scan_proc_macro_dir, ParsedMacroBlock, ParsedUnindexedTarget, ProcMacroSourceFile,
18};
19use super::WorkspaceIndex;
20use crate::format::DefKind;
21use std::collections::{HashMap, HashSet};
22use std::path::Path;
23use std::sync::{Arc, Mutex, OnceLock};
24
25/// Cached workspace-wide structures shared by `prepareRename` and `rename`.
26pub struct RenameWorkspaceCache {
27    pub cargo_targets: CargoWorkspaceTargets,
28    /// Short associated item name -> `(reader_idx, ref_idx)` across workspace shards.
29    pub assoc_refs_by_name: HashMap<String, Vec<(u32, u32)>>,
30    /// Uppercase-starting short path segment -> deduplicated `(reader_idx, file_id)` pairs referencing it.
31    pub trait_ref_files_by_short: HashMap<String, Vec<(u32, u32)>>,
32    /// Short identifier names that participate in at least one dual-bound macro call-site token (`M2`).
33    pub dual_bound_short_names: HashSet<String>,
34    /// Short names of all `Trait` definitions across workspace shards.
35    pub ws_trait_short_names: HashSet<String>,
36    /// Type/trait short name -> workspace crate names defining a non-reexport type/trait of that name.
37    pub type_def_crates_by_name: HashMap<String, HashSet<String>>,
38    /// Inherent method names coupled to string literals + `.#ident` synthesis in workspace `proc-macro` crates.
39    pub proc_macro_coupled_methods: HashMap<String, String>,
40    /// Pre-loaded workspace `proc-macro` source files.
41    pub proc_macro_files: Vec<ProcMacroSourceFile>,
42    /// Crate name -> `(reader_idx, ParsedMacroBlock)` for indexed `macro_rules!` files.
43    pub macro_blocks_by_crate: HashMap<String, Vec<(usize, ParsedMacroBlock)>>,
44    /// `(file, method_name)` -> count of distinct root owners with `fn method(...self...)` in `file`.
45    pub file_self_method_owners: HashMap<(String, String), usize>,
46    /// `(module_path_suffix, method_name)` -> count of distinct root owners in that module.
47    pub mod_self_method_owners: HashMap<(String, String), usize>,
48    /// Method name -> `(crate_name, owner_short, is_trait)` for workspace `AssocFn` items with a `self` receiver.
49    pub self_methods_by_name: HashMap<String, Vec<(String, String, bool)>>,
50    /// Nominal return type short name -> workspace functions/methods whose return type mentions it.
51    pub factory_fns_by_return_short: HashMap<String, Vec<FactoryFnCandidate>>,
52    /// Pre-parsed unindexed Cargo target files (`bin`/`example`/`test`/`bench`/`custom-build`).
53    pub unindexed_targets: Vec<ParsedUnindexedTarget>,
54    /// Identifier token -> indices into `unindexed_targets`.
55    pub unindexed_ident_map: HashMap<String, Vec<usize>>,
56}
57
58type CacheKey = (u64, u64, usize);
59static RENAME_WS_CACHE: OnceLock<Mutex<HashMap<CacheKey, Arc<RenameWorkspaceCache>>>> = OnceLock::new();
60
61fn extract_root_owner_key(reader_crate: &str, def_path: &str, enclosing_impl_trait: Option<&str>, trait_paths: &HashSet<&str>) -> Option<String> {
62    if let Some(tr) = super::navigation::qualified_path::extract_impl_trait(def_path).or(enclosing_impl_trait) {
63        let base = tr.split('<').next().unwrap_or(tr).trim();
64        let short = base.rsplit("::").next().unwrap_or(base);
65        return (!short.is_empty()).then(|| format!("trait:{short}"));
66    }
67    let (raw_parent, _) = def_path.rsplit_once("::")?;
68    let parent = raw_parent.trim();
69    let unwrapped = parent.strip_prefix('<').and_then(|s| s.strip_suffix('>')).unwrap_or(parent);
70    let base_parent = unwrapped.split('<').next().unwrap_or(unwrapped).trim();
71    if trait_paths.contains(base_parent) {
72        let short = base_parent.rsplit("::").next().unwrap_or(base_parent);
73        return Some(format!("trait:{short}"));
74    }
75    let local_p = base_parent.strip_prefix(&format!("{reader_crate}::")).unwrap_or(base_parent);
76    Some(format!("inherent:{reader_crate}::{local_p}"))
77}
78
79fn collect_declared_submodules(root_rs: &Path, out: &mut Vec<std::path::PathBuf>) {
80    let Some(base_dir) = root_rs.parent() else { return };
81    let Ok(src) = std::fs::read_to_string(root_rs) else { return };
82    let mod_search_dir = if matches!(root_rs.file_stem().and_then(|s| s.to_str()), Some("main" | "lib" | "mod")) {
83        base_dir.to_path_buf()
84    } else if let Some(stem) = root_rs.file_stem() {
85        base_dir.join(stem)
86    } else {
87        base_dir.to_path_buf()
88    };
89    let mut pending_path_attr: Option<String> = None;
90    for raw_ln in src.lines() {
91        let ln = crate::workspace::rename_parse::strip_line_comment(raw_ln).trim();
92        if let Some(rest) = ln.strip_prefix("#[path").map(str::trim_start).and_then(|r| r.strip_prefix('=')) {
93            if let Some(q1) = rest.find('"') {
94                if let Some(q2) = rest[q1 + 1..].find('"') {
95                    pending_path_attr = Some(rest[q1 + 1..q1 + 1 + q2].to_string());
96                }
97            }
98            continue;
99        }
100        let mod_rest = ln.strip_prefix("mod ").or_else(|| ln.strip_prefix("pub mod ")).or_else(|| ln.strip_prefix("pub(crate) mod "));
101        if let Some(mr) = mod_rest {
102            if let Some(semi) = mr.strip_suffix(';') {
103                let mod_name = semi.trim();
104                if let Some(rel) = pending_path_attr.take() {
105                    let p = crate::paths::normalize_path(&base_dir.join(rel));
106                    if p.is_file() {
107                        out.push(p);
108                    }
109                } else if !mod_name.is_empty() {
110                    for cand in [mod_search_dir.join(format!("{mod_name}.rs")), mod_search_dir.join(mod_name).join("mod.rs"), base_dir.join(format!("{mod_name}.rs"))] {
111                        if cand.is_file() {
112                            out.push(cand);
113                            break;
114                        }
115                    }
116                }
117            } else {
118                pending_path_attr = None;
119            }
120        } else if !ln.starts_with("#[") && !ln.is_empty() {
121            pending_path_attr = None;
122        }
123    }
124}
125
126impl RenameWorkspaceCache {
127    pub fn get(ws: &WorkspaceIndex) -> Arc<Self> {
128        let key = (ws.instance_id, ws.generation, ws.readers.len());
129        let mutex = RENAME_WS_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
130        if let Some(existing) = mutex.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
131            return Arc::clone(existing);
132        }
133        let built = Arc::new(Self::build(ws));
134        let mut guard = mutex.lock().unwrap_or_else(|e| e.into_inner());
135        guard.retain(|&(inst, gen, _), _| inst != ws.instance_id || gen == ws.generation);
136        guard.insert(key, Arc::clone(&built));
137        built
138    }
139
140    fn build(ws: &WorkspaceIndex) -> Self {
141        let cargo_targets = CargoWorkspaceTargets::discover(ws);
142        let mut assoc_refs_by_name: HashMap<String, Vec<(u32, u32)>> = HashMap::new();
143        let mut trait_ref_files_by_short: HashMap<String, Vec<(u32, u32)>> = HashMap::new();
144        let mut dual_bound_short_names: HashSet<String> = HashSet::new();
145        let mut ws_trait_short_names: HashSet<String> = HashSet::new();
146        let mut type_def_crates_by_name: HashMap<String, HashSet<String>> = HashMap::new();
147        let mut macro_blocks_by_crate: HashMap<String, Vec<(usize, ParsedMacroBlock)>> = HashMap::new();
148        let mut scanned_macro_files: HashSet<(String, String)> = HashSet::new();
149        let mut file_owner_sets: HashMap<(String, String), HashSet<String>> = HashMap::new();
150        let mut mod_owner_sets: HashMap<(String, String), HashSet<String>> = HashMap::new();
151        let mut self_methods_by_name: HashMap<String, Vec<(String, String, bool)>> = HashMap::new();
152
153        for (i, reader) in ws.readers.iter().enumerate() {
154            if ws.is_reader_external(i) {
155                continue;
156            }
157            let cname = reader.crate_name();
158            let refs = reader.references();
159            let mut span_name_refs: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
160            for (r_idx, r) in refs.iter().enumerate() {
161                let r_kind = DefKind::from(r.kind);
162                let tp = reader.get_str(r.target_path_offset());
163                let short = tp.rsplit("::").next().unwrap_or(tp);
164                if !short.is_empty() && (r_kind == DefKind::Trait || short.as_bytes()[0].is_ascii_uppercase()) {
165                    let pair = (i as u32, r.span().file_id());
166                    let list = trait_ref_files_by_short.entry(short.to_string()).or_default();
167                    if list.last() != Some(&pair) {
168                        list.push(pair);
169                    }
170                }
171                if matches!(r_kind, DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst) && reader.is_name_reference(r) && !short.is_empty() {
172                    assoc_refs_by_name.entry(short.to_string()).or_default().push((i as u32, r_idx as u32));
173                }
174                let sp = r.span();
175                if !short.is_empty()
176                    && !matches!(r_kind, DefKind::Macro | DefKind::Use)
177                    && reader.is_name_reference(r)
178                    && sp.start_line() > 0
179                    && sp.start_line() == sp.end_line()
180                    && sp.end_col().saturating_sub(sp.start_col()) == short.chars().count() as u32
181                {
182                    span_name_refs.push((sp.file_id(), sp.start_line(), sp.start_col(), sp.end_col(), r_idx as u32));
183                }
184            }
185            span_name_refs.sort_unstable();
186            for win in span_name_refs.windows(2) {
187                if (win[0].0, win[0].1, win[0].2, win[0].3) != (win[1].0, win[1].1, win[1].2, win[1].3) {
188                    continue;
189                }
190                let (r1, r2) = (&refs[win[0].4 as usize], &refs[win[1].4 as usize]);
191                if !r1.is_macro_expansion() && !r2.is_macro_expansion() {
192                    continue;
193                }
194                let (tp1, tp2) = (reader.get_str(r1.target_path_offset()), reader.get_str(r2.target_path_offset()));
195                let (Some(s1), Some(s2)) = (tp1.rsplit("::").next(), tp2.rsplit("::").next()) else { continue };
196                if s1 == s2 && !s1.is_empty() {
197                    let c1 = super::navigation::rename_check::canonicalize_symbol_path(ws, cname, tp1);
198                    let c2 = super::navigation::rename_check::canonicalize_symbol_path(ws, cname, tp2);
199                    if c1 != c2 && !super::navigation::rename_check::same_trait_assoc_family(tp1, tp2) {
200                        dual_bound_short_names.insert(s1.to_string());
201                    }
202                }
203            }
204            let defs = reader.definitions();
205            let mut trait_paths: HashSet<&str> = HashSet::new();
206            let mut impls_by_file: HashMap<u32, Vec<(u32, u32, &str)>> = HashMap::new();
207            for d in defs {
208                let dk = DefKind::from(d.kind);
209                if !d.is_reexport() && matches!(dk, DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait | DefKind::TyAlias) {
210                    let short = reader.get_str(d.name_offset());
211                    if !short.is_empty() {
212                        type_def_crates_by_name.entry(short.to_string()).or_default().insert(cname.to_string());
213                    }
214                }
215                if dk == DefKind::Trait {
216                    let short = reader.get_str(d.name_offset());
217                    let dp = reader.get_str(d.path_offset());
218                    trait_paths.insert(dp);
219                    if !short.is_empty() {
220                        ws_trait_short_names.insert(short.to_string());
221                        let list = trait_ref_files_by_short.entry(short.to_string()).or_default();
222                        for r in reader.find_references(dp) {
223                            let pair = (i as u32, r.span().file_id());
224                            if !list.contains(&pair) {
225                                list.push(pair);
226                            }
227                        }
228                    }
229                } else if dk == DefKind::Impl {
230                    if let (Some(tr), _) = super::navigation::impl_parse::parse_impl_def_path(reader.get_str(d.path_offset())) {
231                        let sp = d.span();
232                        impls_by_file.entry(sp.file_id()).or_default().push((sp.start_line(), sp.end_line(), tr));
233                    }
234                }
235            }
236
237            let mut macro_fids = Vec::new();
238            for d in defs {
239                let kind = DefKind::from(d.kind);
240                if kind == DefKind::Macro && !d.is_reexport() {
241                    macro_fids.push(d.span().file_id());
242                } else if kind == DefKind::AssocFn && d.sig_offset() != 0 && has_self_receiver(reader.get_str(d.sig_offset())) {
243                    let name = reader.get_str(d.name_offset());
244                    let dp = reader.get_str(d.path_offset());
245                    let sp = d.span();
246                    let file = reader.get_file(sp.file_id());
247                    let enc_tr = super::navigation::qualified_path::extract_impl_trait(dp).or_else(|| {
248                        impls_by_file.get(&sp.file_id()).and_then(|v| v.iter().find_map(|&(sl, el, tr)| (sl <= sp.start_line() && sp.start_line() <= el).then_some(tr)))
249                    });
250                    if let Some(root_key) = extract_root_owner_key(cname, dp, enc_tr, &trait_paths) {
251                        let (owner_short, is_tr) = if let Some(tr_s) = root_key.strip_prefix("trait:") {
252                            (tr_s.to_string(), true)
253                        } else {
254                            let s = root_key.rsplit("::").next().unwrap_or(&root_key).to_string();
255                            (s, false)
256                        };
257                        if !owner_short.is_empty() && (is_tr || d.visibility == 0) {
258                            let list = self_methods_by_name.entry(name.to_string()).or_default();
259                            if !list.iter().any(|(c, o, t)| *t == is_tr && o == &owner_short && (is_tr || c == cname)) {
260                                list.push((cname.to_string(), owner_short, is_tr));
261                            }
262                        }
263                        file_owner_sets.entry((file.to_string(), name.to_string())).or_default().insert(root_key.clone());
264                        if let Some((parent, _)) = dp.rsplit_once("::") {
265                            let clean_p = parent.split('<').next().unwrap_or(parent).trim();
266                            if let Some((mod_path, _)) = clean_p.rsplit_once("::") {
267                                let local_mod = mod_path.strip_prefix(&format!("{cname}::")).unwrap_or(mod_path);
268                                if !local_mod.is_empty() {
269                                    mod_owner_sets.entry((local_mod.to_string(), name.to_string())).or_default().insert(root_key.clone());
270                                    if let Some((_, last_seg)) = local_mod.rsplit_once("::") {
271                                        mod_owner_sets.entry((last_seg.to_string(), name.to_string())).or_default().insert(root_key);
272                                    }
273                                }
274                            }
275                        }
276                    }
277                }
278            }
279
280            macro_fids.sort_unstable();
281            macro_fids.dedup();
282            for fid in macro_fids {
283                let f = reader.get_file(fid);
284                if !scanned_macro_files.insert((cname.to_string(), f.to_string())) {
285                    continue;
286                }
287                if let Some(content) = ws.read_source_file(f) {
288                    for blk in extract_macro_rules_blocks(fid, f, &content) {
289                        macro_blocks_by_crate.entry(cname.to_string()).or_default().push((i, blk));
290                    }
291                }
292            }
293        }
294
295        let file_self_method_owners = file_owner_sets.into_iter().map(|(k, v)| (k, v.len())).collect();
296        let mod_self_method_owners = mod_owner_sets.into_iter().map(|(k, v)| (k, v.len())).collect();
297        let factory_fns_by_return_short = build_factory_return_index(ws, &type_def_crates_by_name);
298
299        let mut proc_macro_coupled_methods = HashMap::new();
300        let mut proc_macro_files = Vec::new();
301        for (pm_crate, src_dir) in &cargo_targets.proc_macro_crates {
302            scan_proc_macro_dir(pm_crate, src_dir, &mut proc_macro_coupled_methods, &mut proc_macro_files);
303        }
304        for pm_file in &mut proc_macro_files {
305            for (i, reader) in ws.readers.iter().enumerate() {
306                if !ws.is_reader_external(i) && reader.crate_name() == pm_file.crate_name {
307                    if let Some(target_rel) = ws.target_file_for_reader(i, &pm_file.file_path) {
308                        if let Some(fid) = reader.find_file_id(target_rel.as_ref()) {
309                            pm_file.reader_idx = Some(i);
310                            pm_file.file_id = Some(fid);
311                            pm_file.file_path = reader.get_file(fid).to_string();
312                            break;
313                        }
314                    }
315                }
316            }
317        }
318
319        let mut unindexed_targets = Vec::new();
320        let mut seen_unindexed = HashSet::new();
321        for tgt in &cargo_targets.member_targets {
322            if tgt.src_path.to_str().is_some_and(|s| !ws.resolved_reader_file_ids(s).is_empty()) {
323                continue;
324            }
325            let mut candidate_paths = vec![tgt.src_path.clone()];
326            if tgt.kinds.iter().any(|k| matches!(k.as_str(), "example" | "test" | "bench")) {
327                collect_declared_submodules(&tgt.src_path, &mut candidate_paths);
328                if tgt.src_path.file_name().and_then(|s| s.to_str()) == Some("main.rs") {
329                    if let Some(dir) = tgt.src_path.parent() {
330                        if let Ok(entries) = std::fs::read_dir(dir) {
331                            for entry in entries.flatten() {
332                                let ep = entry.path();
333                                if ep.extension().and_then(|s| s.to_str()) == Some("rs") {
334                                    candidate_paths.push(ep);
335                                }
336                            }
337                        }
338                    }
339                }
340            }
341            for cand_path in candidate_paths {
342                let Some(path_str) = cand_path.to_str() else { continue };
343                if !ws.resolved_reader_file_ids(path_str).is_empty() || ws.is_external_path(&cand_path) {
344                    continue;
345                }
346                if seen_unindexed.insert(cand_path.clone()) {
347                    if let Some(parsed) = parse_unindexed_rust_file(cand_path, tgt.pkg_crate.clone(), tgt.dep_crates.clone()) {
348                        unindexed_targets.push(parsed);
349                    }
350                }
351            }
352        }
353        let mut unindexed_ident_map: HashMap<String, Vec<usize>> = HashMap::new();
354        for (u_idx, ut) in unindexed_targets.iter().enumerate() {
355            for ident in &ut.idents {
356                unindexed_ident_map.entry(ident.clone()).or_default().push(u_idx);
357            }
358        }
359
360        Self {
361            cargo_targets,
362            assoc_refs_by_name,
363            trait_ref_files_by_short,
364            dual_bound_short_names,
365            ws_trait_short_names,
366            type_def_crates_by_name,
367            proc_macro_coupled_methods,
368            proc_macro_files,
369            macro_blocks_by_crate,
370            file_self_method_owners,
371            mod_self_method_owners,
372            self_methods_by_name,
373            factory_fns_by_return_short,
374            unindexed_targets,
375            unindexed_ident_map,
376        }
377    }
378}
379
380impl WorkspaceIndex {
381    /// Returns the shared workspace rename cache for the current generation.
382    pub fn rename_cache(&self) -> Arc<RenameWorkspaceCache> {
383        RenameWorkspaceCache::get(self)
384    }
385}