Skip to main content

ridx_format/reader/
name_reference.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//! Which stored references count as uses of a name: the single filter the reader's lookups
12//! (`find_innermost_ref_at_file_id`, `find_references`) apply to the reference table, and the
13//! span test behind the precedence of a definition at the cursor over a reference enclosing it.
14
15use super::IndexReader;
16use crate::format::*;
17
18impl<B: AsRef<[u8]>> IndexReader<B> {
19    /// Whether a macro expansion wrote a reference to `target_path` whose target sits on 1-based `def_line` (0
20    /// matches any). Unlike `find_references` this counts the references that are no use of the name, such as a
21    /// proc macro's generated call carrying its call site's span: rename safety needs to know the call exists.
22    pub fn has_macro_expansion_reference(&self, target_path: &str, def_line: u32) -> bool {
23        let hash = fnv1a_64(target_path.as_bytes());
24        let (ref_hashes, refs) = (self.refs_by_target(), self.references());
25        let Ok(mut i) = ref_hashes.binary_search_by_key(&hash, |e| e.hash()) else { return false };
26        while i > 0 && ref_hashes[i - 1].hash() == hash {
27            i -= 1;
28        }
29        ref_hashes[i..]
30            .iter()
31            .take_while(|e| e.hash() == hash)
32            .map(|e| &refs[e.index() as usize])
33            .any(|r| r.is_macro_expansion() && self.get_str(r.target_path_offset()) == target_path && (def_line == 0 || r.target_line() == 0 || r.target_line() == def_line))
34    }
35
36    /// The definition `def_id` among the definitions stored under `path`, if any.
37    fn find_definition_by_id_under_path(&self, def_id: u32, path: &str) -> Option<&DefEntry> {
38        let hash = fnv1a_64(path.as_bytes());
39        let defs_hash = self.defs_by_hash();
40        let defs = self.definitions();
41        let mut i = defs_hash.binary_search_by_key(&hash, |e| e.hash()).ok()?;
42        while i > 0 && defs_hash[i - 1].hash() == hash {
43            i -= 1;
44        }
45        while i < defs_hash.len() && defs_hash[i].hash() == hash {
46            let def = &defs[defs_hash[i].index() as usize];
47            if def.def_id() == def_id {
48                return Some(def);
49            }
50            i += 1;
51        }
52        None
53    }
54
55    /// True when `r` is a use of its target's name. A reference whose span properly encloses the
56    /// span of its own target's definition is not one: it is the span of the item or file that
57    /// defines the target. The driver writes two such references per `#[test]` function: a plain
58    /// `Fn` reference spanning the whole function (the call the test harness generates) and a
59    /// macro `Const` reference to the generated test constant spanning the whole file or module
60    /// (the constant's definition sits on the `#[test]` attribute, so the span begins where the
61    /// definition begins and reaches far past it); derive expansions add references spanning a
62    /// whole variant or field. A definition whose end lies before its start (an index without end
63    /// spans) is never enclosed. The reader's lookups (`find_innermost_ref_at_file_id`,
64    /// `find_references`) skip references that fail this test; `IndexReader::references` still
65    /// returns every record.
66    pub fn is_name_reference(&self, r: &RefEntry) -> bool {
67        let path = self.get_str(r.target_path_offset());
68        let kind = DefKind::from(r.kind);
69        let name = path.rsplit("::").next().unwrap_or(path);
70        if kind == DefKind::Local && name.starts_with("__") {
71            return false;
72        }
73        // A method or a field is never renamed by an import, so its use spells its name. A derive's generated call
74        // given the span of the field it was made for (`remove_many` on `name: Vec<String>`) does not.
75        if matches!(kind, DefKind::AssocFn | DefKind::Field) {
76            let span = r.span();
77            let width = span.end_col().saturating_sub(span.start_col()) as usize;
78            let len = name.strip_prefix("r#").unwrap_or(name).chars().count();
79            if span.start_line() == span.end_line() && span.end_col() > span.start_col() && width != len && width != len + 2 && !name.starts_with('<') {
80                return false;
81            }
82        }
83        if r.target_def_id() == u32::MAX {
84            return true;
85        }
86        let Some(def) = self.find_definition_by_id_under_path(r.target_def_id(), path) else {
87            return true;
88        };
89        let (span, def_span) = (r.span(), def.span());
90        let def_end_valid = (def_span.end_line(), def_span.end_col()) >= (def_span.start_line(), def_span.start_col());
91        !(def_end_valid && span_strictly_inside(&def_span, &span))
92    }
93
94    /// True when the span of `r` can contain a definition's name span: a span over more than one
95    /// line, or a single-line span wider than its target's name. A reference as wide as the name
96    /// it uses contains no definition, so `find_definition_at` answers it without looking for one;
97    /// a span whose end lies before its start contains nothing.
98    pub fn may_enclose_definition(&self, r: &RefEntry) -> bool {
99        let span = r.span();
100        let (start, end) = ((span.start_line(), span.start_col()), (span.end_line(), span.end_col()));
101        if end < start {
102            return false;
103        }
104        if span.end_line() != span.start_line() {
105            return true;
106        }
107        let target_path = self.get_str(r.target_path_offset());
108        let name = target_path.rsplit("::").next().unwrap_or(target_path);
109        (span.end_col() - span.start_col()) as usize > name.chars().count()
110    }
111
112    /// The distinct reference target paths that name an implementation's item (`<T as Trait>::item`,
113    /// `m::<impl Trait for T>::item`), as string offsets grouped by the item's name. One pass over the target table.
114    pub fn qualified_item_targets(&self) -> std::collections::HashMap<Box<str>, Vec<u32>> {
115        let (by_target, refs) = (self.refs_by_target(), self.references());
116        let mut out: std::collections::HashMap<Box<str>, Vec<u32>> = std::collections::HashMap::new();
117        let mut last = u32::MAX;
118        for e in by_target {
119            let off = refs[e.index() as usize].target_path_offset();
120            if off == last {
121                continue;
122            }
123            last = off;
124            let path = self.get_str(off);
125            if !path.starts_with('<') && !path.contains("::<impl ") {
126                continue;
127            }
128            if let Some((head, item)) = path.rsplit_once("::") {
129                // The table is sorted by the target's hash, so the references to one target are adjacent.
130                if head.ends_with('>') && !item.is_empty() {
131                    out.entry(item.into()).or_default().push(off);
132                }
133            }
134        }
135        out
136    }
137}
138
139/// True when `inner` lies within `outer` in the same file and the two spans differ.
140pub(crate) fn span_strictly_inside(inner: &Span, outer: &Span) -> bool {
141    let (inner_start, inner_end) = ((inner.start_line(), inner.start_col()), (inner.end_line(), inner.end_col()));
142    let (outer_start, outer_end) = ((outer.start_line(), outer.start_col()), (outer.end_line(), outer.end_col()));
143    inner.file_id() == outer.file_id() && outer_start <= inner_start && inner_end <= outer_end && (inner_start, inner_end) != (outer_start, outer_end)
144}
145
146#[cfg(test)]
147mod tests {
148    use super::super::cursor_precedence_tests::write_fixture;
149    use super::super::IndexReader;
150
151    #[test]
152    fn only_a_span_wider_than_its_target_name_may_enclose_a_definition() {
153        let dir = std::env::temp_dir().join(format!("ridx_may_enclose_{}", std::process::id()));
154        let _ = std::fs::create_dir_all(&dir);
155        let reader = IndexReader::open(write_fixture(&dir)).unwrap();
156        // 7:5-7:8 is as wide as `Arc`; 8:5-8:30 is wider; 1:1-30:2 spans thirty lines.
157        let name_wide = reader.find_innermost_ref_at("src/lib.rs", 7, 6).unwrap();
158        let wider = reader.find_innermost_ref_at("src/lib.rs", 8, 6).unwrap();
159        let invocation = reader.find_innermost_ref_at("src/lib.rs", 20, 1).unwrap();
160        assert_eq!((reader.may_enclose_definition(name_wide), reader.may_enclose_definition(wider), reader.may_enclose_definition(invocation),), (false, true, true));
161        let _ = std::fs::remove_dir_all(dir);
162    }
163}