Skip to main content

ridx_format/workspace/navigation/
references.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
11use super::reference_record::{matches_reference_target, points_at_definition, push_reference, ReferenceTarget};
12use super::*;
13impl WorkspaceIndex {
14    /// Finds all references to a symbol, optionally scoped to a target dependency unit.
15    pub fn find_references_for_unit<'a>(&'a self, target_path: &str, target_unit_key: Option<&str>) -> Vec<WorkspaceReference<'a>> {
16        self.find_references_for_unit_with_target(target_path, target_unit_key, None)
17    }
18
19    /// Finds all references to a symbol with optional explicit target definition metadata.
20    pub(crate) fn find_references_for_unit_with_target<'a>(
21        &'a self,
22        target_path: &str,
23        target_unit_key: Option<&str>,
24        explicit_def: Option<(&str, u32, DefKind, &'a str)>,
25    ) -> Vec<WorkspaceReference<'a>> {
26        let target_unit_key = target_unit_key.filter(|k| !k.is_empty());
27        let mut all_refs = Vec::new();
28        let mut seen_refs = std::collections::HashSet::new();
29        let raw_target_idx = if let Some(target_unit) = target_unit_key { self.unit_keys.iter().position(|u| u.as_deref() == Some(target_unit)) } else { None };
30        let mut target_crate = super::qualified_path::extract_root_crate(target_path);
31        if !self.has_crate(target_crate) && !matches!(target_crate, "core" | "alloc" | "std" | "proc_macro") {
32            let parent_path = target_path.rsplit_once("::").map(|(p, _)| p);
33            let mut resolved = false;
34            if let Some(t_idx) = raw_target_idx {
35                let r = &self.readers[t_idx];
36                if !target_path.contains("::") || r.find_definition_by_path(target_path).is_some() || parent_path.is_some_and(|p| r.find_definition_by_path(p).is_some()) {
37                    target_crate = r.crate_name();
38                    resolved = true;
39                }
40            }
41            if !resolved {
42                for r in &self.readers {
43                    if r.find_definition_by_path(target_path).is_some() {
44                        target_crate = r.crate_name();
45                        resolved = true;
46                        break;
47                    }
48                }
49            }
50            if !resolved {
51                for r in &self.readers {
52                    if parent_path.is_some_and(|p| r.find_definition_by_path(p).is_some_and(|d| DefKind::from(d.kind) == DefKind::Enum)) {
53                        target_crate = r.crate_name();
54                        break;
55                    }
56                }
57            }
58        }
59        let target_idx = if target_unit_key.is_some() {
60            raw_target_idx
61        } else {
62            let fast = self.readers_for_crate_fast(target_crate);
63            fast.iter()
64                .copied()
65                .find(|&idx| {
66                    let r = &self.readers[idx];
67                    let sub = target_path.strip_prefix(&format!("{target_crate}::")).unwrap_or(target_path);
68                    r.find_definition_by_path(target_path).is_some() || r.find_definition_by_path(sub).is_some()
69                })
70                .or_else(|| fast.first().copied())
71        };
72
73        if let Some(t_idx) = target_idx {
74            if (!target_path.starts_with('<')
75                && !matches!(target_crate, "core" | "alloc" | "std" | "proc_macro")
76                && (explicit_def.is_none_or(|(ef, _, _, _)| ef != "external") || !self.has_crate(target_crate)))
77                || self.readers[t_idx].crate_name() == target_crate
78            {
79                target_crate = self.readers[t_idx].crate_name();
80            }
81        }
82        let effective_unit_key = target_unit_key;
83
84        let resolve_full = |t_idx: usize, f: &str| -> String {
85            self.source_roots
86                .get(t_idx)
87                .and_then(|r| r.as_ref())
88                .or(self.workspace_root.as_ref())
89                .map(|root| crate::format::join_resolving_overlap(root, Path::new(f)).to_string_lossy().to_string())
90                .unwrap_or_else(|| f.to_string())
91        };
92
93        let target_def_coords = if let Some((ef, el, _, _)) = explicit_def.filter(|d| !d.0.is_empty() && d.1 > 0) {
94            let full = target_idx.map(|t| resolve_full(t, ef)).unwrap_or_else(|| ef.to_string());
95            Some((ef.to_string(), full, el))
96        } else if let Some(t_idx) = target_idx {
97            let r = &self.readers[t_idx];
98            let def_opt = r.find_definition_by_path(target_path).or_else(|| {
99                let rest = target_path.strip_prefix(&format!("{target_crate}::"))?;
100                r.find_definition_by_path(&format!("{}::{rest}", r.crate_name()))
101            });
102            def_opt.map(|def| {
103                let span = def.span();
104                let file = r.get_file(span.file_id());
105                (file.to_string(), resolve_full(t_idx, file), span.start_line())
106            })
107        } else {
108            None
109        };
110
111        let prefix = super::qualified_path::extract_root_crate(target_path);
112        let is_alias_for_target =
113            if let Some(target_unit) = effective_unit_key { self.reader_extern_units.iter().any(|m| m.get(prefix).is_some_and(|uk| uk == target_unit)) } else { false };
114
115        let local_path = if target_path.starts_with(&format!("{target_crate}::")) {
116            &target_path[target_crate.len() + 2..]
117        } else if !target_path.starts_with('<') && is_alias_for_target && target_path.contains("::") {
118            &target_path[prefix.len() + 2..]
119        } else {
120            target_path
121        };
122        let is_global_angle = local_path.starts_with('<') && {
123            let c = super::qualified_path::extract_root_crate(local_path);
124            c == target_crate || matches!(c, "core" | "alloc" | "std" | "proc_macro") || self.has_crate(c)
125        };
126        // A crate's root is spelled by its name alone (`tt` in `tt::Leaf`), in its own crate and in its consumers.
127        let is_crate_root = target_path == target_crate;
128        let global_path_buf = if is_global_angle || is_crate_root { local_path.to_string() } else { format!("{target_crate}::{local_path}") };
129        let global_path = global_path_buf.as_str();
130        let mut spellings = super::qualified_path::consumer_spellings(local_path, target_crate);
131        if target_path.starts_with(&format!("{target_crate}::")) {
132            let doubled = format!("{target_crate}::{global_path}");
133            if !spellings.contains(&doubled) {
134                spellings.push(doubled);
135            }
136            for sp in super::qualified_path::consumer_spellings(global_path, target_crate) {
137                if !spellings.contains(&sp) {
138                    spellings.push(sp);
139                }
140            }
141        }
142        for imp_sp in super::qualified_path::impl_consumer_spellings(local_path, target_crate) {
143            if !spellings.contains(&imp_sp) {
144                spellings.push(imp_sp);
145            }
146        }
147        for cand in super::std_map::std_path_candidates(global_path) {
148            if cand != global_path && cand != local_path && cand != target_path && !spellings.contains(&cand) {
149                spellings.push(cand);
150            }
151        }
152        if explicit_def.map(|d| d.2) == Some(DefKind::Macro) {
153            if let Some((_, macro_name)) = local_path.rsplit_once("::") {
154                let root_macro = format!("{target_crate}::{macro_name}");
155                if !spellings.contains(&root_macro) {
156                    spellings.push(root_macro);
157                }
158                if !spellings.contains(&macro_name.to_string()) {
159                    spellings.push(macro_name.to_string());
160                }
161            }
162        }
163        if let Some((ty, tr, tail)) = super::qualified_path::split_qualified_parts(target_path) {
164            let tr_crate = super::qualified_path::extract_root_crate(tr);
165            if ty.len() == 1 && ty.as_bytes()[0].is_ascii_uppercase() && matches!(tr_crate, "core" | "alloc" | "std") {
166                let trait_item = format!("{tr}{tail}");
167                for cand in super::std_map::std_path_candidates(&trait_item) {
168                    if !spellings.contains(&cand) {
169                        spellings.push(cand);
170                    }
171                }
172            }
173        }
174
175        let disambiguate_line = explicit_def.is_some()
176            && target_idx.is_some_and(|t| {
177                let r = &self.readers[t];
178                r.has_multiple_definitions_at_path(target_path) || r.has_multiple_definitions_at_path(local_path) || r.has_multiple_definitions_at_path(global_path)
179            });
180        let ref_target = ReferenceTarget {
181            kind: explicit_def.map(|d| d.2),
182            name: explicit_def.map(|d| d.3),
183            coords: target_def_coords.clone(),
184            disambiguate_line,
185            is_qualified_path: target_path.contains("::"),
186        };
187
188        // The target and the other builds of its crate and version (feature sets compile one
189        // source into several units): a consumer reaching any of them uses the item.
190        let target_builds: Vec<usize> = target_idx
191            .map(|t| {
192                let (name, version) = (self.readers[t].crate_name(), self.readers[t].crate_version());
193                (0..self.readers.len()).filter(|&s| s == t || (self.readers[s].crate_name() == name && self.readers[s].crate_version() == version)).collect()
194            })
195            .unwrap_or_default();
196
197        let mut match_memo = std::collections::HashMap::<(usize, &str), bool>::new();
198        let mut coord_cands = std::collections::HashMap::<&str, Vec<String>>::new();
199        let mut alias_spellings = std::collections::HashMap::<&str, Vec<String>>::new();
200        let mut alias_unit_memo = std::collections::HashMap::<(Option<&str>, &str), bool>::new();
201
202        for (i, reader) in self.readers.iter().enumerate() {
203            if self.is_reader_external(i) {
204                continue;
205            }
206            let reader_unit = self.unit_keys.get(i).and_then(|u| u.as_deref());
207            let reader_crate = reader.crate_name();
208
209            let is_exact_target_unit =
210                if let (Some(target_unit), Some(ru)) = (effective_unit_key, reader_unit) { ru == target_unit } else { target_idx == Some(i) || reader_crate == target_crate };
211
212            let is_sibling_unit = target_idx.map(|t| self.are_sibling_workspace_units(t, i)).unwrap_or(false);
213
214            let is_same_package = is_exact_target_unit || is_sibling_unit;
215
216            if !is_same_package {
217                let is_consumer_of_target = effective_unit_key
218                    .map(|tu| {
219                        let in_deps = self.reader_dependencies.get(i).map(|d| d.iter().any(|dep| dep == tu)).unwrap_or(false);
220                        let in_extern = self.reader_extern_units.get(i).map(|m| m.values().any(|uk| uk == tu)).unwrap_or(false);
221                        in_deps || in_extern
222                    })
223                    .unwrap_or(false);
224
225                if reader_crate == target_crate && !is_consumer_of_target {
226                    // Different package that collides on crate_name but is not a sibling unit.
227                    continue;
228                }
229                // The reader is an external/referring crate.
230                // If effective_unit_key is given:
231                if let Some(target_unit) = effective_unit_key {
232                    let has_deps = self.reader_dependencies.get(i).map(|d| !d.is_empty()).unwrap_or(false);
233                    let has_extern_units = self.reader_extern_units.get(i).map(|m| !m.is_empty()).unwrap_or(false);
234
235                    if has_deps || has_extern_units {
236                        let in_deps = self.reader_dependencies.get(i).map(|d| d.iter().any(|dep| dep == target_unit || dep == target_crate)).unwrap_or(false);
237                        let in_extern_units =
238                            self.reader_extern_units.get(i).map(|m| m.keys().any(|k| k == target_crate) || m.values().any(|uk| uk == target_unit)).unwrap_or(false);
239                        // A consumer may reach the target through a unit it depends on (an item
240                        // used through a re-export): the dependency graph is walked from it.
241                        if !in_deps && !in_extern_units && !target_builds.iter().any(|&t| self.is_reader_in_dep_graph(&[i], t)) {
242                            // Referring crate has dependency info but depends neither on
243                            // target_unit or target_crate nor, through another unit, on the
244                            // target. Exclude!
245                            continue;
246                        }
247                    } else {
248                        // Legacy reader without dependency info: exclude if multiple versions of target_crate exist in workspace
249                        let target_crate_versions = self.readers.iter().filter(|r| r.crate_name() == target_crate).count();
250                        if target_crate_versions > 1 && reader_crate == target_crate {
251                            continue;
252                        }
253                    }
254                }
255            }
256
257            // References with canonical target_path (querying both local and global path representations)
258            let source_root = self.source_roots.get(i).and_then(|r| r.as_deref()).or(self.workspace_root.as_deref());
259
260            let mut query_path_vec = Vec::new();
261            if local_path == global_path {
262                query_path_vec.push(target_path);
263            } else if is_same_package {
264                query_path_vec.push(local_path);
265                query_path_vec.push(global_path);
266                if target_path != local_path && target_path != global_path {
267                    query_path_vec.push(target_path);
268                }
269            } else {
270                query_path_vec.push(global_path);
271                if target_path != global_path && target_path != local_path {
272                    query_path_vec.push(target_path);
273                }
274            }
275            query_path_vec.extend(spellings.iter().map(String::as_str));
276            for &q_path in &query_path_vec {
277                let refs = reader.find_references(q_path);
278                for r in refs {
279                    let r_target_unit = reader.target_unit(r);
280                    if let Some(target_unit) = effective_unit_key {
281                        if !r_target_unit.is_empty() {
282                            // A build of the target's crate the index holds no shard for (a target with required
283                            // features compiles its dependencies again, with other features) is the same source
284                            // when the workspace has one version of that crate.
285                            let unindexed_build_of_target = self.unit_match.readers_for_unit(r_target_unit).is_none()
286                                && self.unit_match.crate_versions_count(target_crate) == 1
287                                && q_path.strip_prefix(target_crate).is_some_and(|rest| rest.starts_with("::"));
288                            if !unindexed_build_of_target && !self.matches_unit_memoized(&mut match_memo, i, r_target_unit, target_unit, target_crate) {
289                                continue;
290                            }
291                        } else if reader_crate == target_crate {
292                            if !is_same_package {
293                                continue;
294                            }
295                            if !is_sibling_unit {
296                                if let Some(ru) = reader_unit {
297                                    if ru != target_unit {
298                                        continue;
299                                    }
300                                }
301                            }
302                        } else if let Some(coords) = &target_def_coords {
303                            if !points_at_definition(reader, r, coords) {
304                                continue;
305                            }
306                        }
307                    }
308
309                    if !matches_reference_target(reader, r, &ref_target) {
310                        continue;
311                    }
312
313                    let owner = (reader_crate, reader_unit, source_root);
314                    push_reference(reader, r, owner, &mut seen_refs, &mut all_refs);
315                }
316            }
317
318            if let Some(ref coords) = target_def_coords {
319                if !target_path.starts_with('<') && !target_path.contains("<impl ") && local_path.contains("::") {
320                    if let Some((mod_prefix, item_name)) = local_path.rsplit_once("::") {
321                        let parent_mod = mod_prefix.rsplit_once("::").map(|(p, _)| p);
322                        for cname in [target_crate, reader_crate] {
323                            // The candidates depend only on the crate name: built once per name for all readers.
324                            let cands = coord_cands.entry(cname).or_insert_with(|| {
325                                [
326                                    Some(format!("{cname}::{item_name}")),
327                                    (cname != target_crate).then(|| format!("{cname}::{local_path}")),
328                                    parent_mod.map(|pm| format!("{cname}::{pm}::{item_name}")),
329                                    (cname == target_crate).then(|| parent_mod.map(|pm| format!("{pm}::{item_name}"))).flatten(),
330                                ]
331                                .into_iter()
332                                .flatten()
333                                .collect()
334                            });
335                            for cand in cands.iter() {
336                                for r in reader.find_references(cand) {
337                                    if r.target_line() != 0 && points_at_definition(reader, r, coords) && matches_reference_target(reader, r, &ref_target) {
338                                        push_reference(reader, r, (reader_crate, reader_unit, source_root), &mut seen_refs, &mut all_refs);
339                                    }
340                                }
341                            }
342                        }
343                    }
344                }
345            }
346
347            // Also check if reader refers to target_path via an extern alias (e.g. `a1::foo` instead of `a::foo`)
348            if let Some(extern_map) = self.reader_extern_units.get(i) {
349                for (alias, uk) in extern_map {
350                    if alias != target_crate {
351                        if let Some(target_unit) = target_unit_key {
352                            // A reader enters the match only through the unit of the target's crate it links, so the
353                            // answer is shared by every reader linking the same one.
354                            let linked = extern_map.get(target_crate).map(String::as_str);
355                            let ok = *alias_unit_memo.entry((linked, uk.as_str())).or_insert_with(|| self.matches_unit(i, uk.as_str(), target_unit, target_crate));
356                            if !ok {
357                                continue;
358                            }
359                        }
360                        // The spellings depend only on the alias: built once per alias for all readers.
361                        let aliased = alias_spellings.entry(alias.as_str()).or_insert_with(|| {
362                            let mut s = super::qualified_path::consumer_spellings(local_path, alias);
363                            s.push(format!("{alias}::{local_path}"));
364                            s
365                        });
366                        for r in aliased.iter().flat_map(|p| reader.find_references(p)) {
367                            let r_target_unit = reader.target_unit(r);
368                            if let Some(target_unit) = target_unit_key {
369                                if !r_target_unit.is_empty() {
370                                    if !self.matches_unit_memoized(&mut match_memo, i, r_target_unit, target_unit, target_crate) {
371                                        continue;
372                                    }
373                                } else if let Some(coords) = &target_def_coords {
374                                    if !points_at_definition(reader, r, coords) {
375                                        continue;
376                                    }
377                                }
378                            }
379                            if !matches_reference_target(reader, r, &ref_target) {
380                                continue;
381                            }
382
383                            let owner = (reader_crate, reader_unit, source_root);
384                            push_reference(reader, r, owner, &mut seen_refs, &mut all_refs);
385                        }
386                    }
387                }
388            }
389        }
390
391        all_refs
392    }
393}