ridx_format/reader/definition_at.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//! The definition at a cursor: the innermost name reference there, the definition at the cursor
12//! when its span lies inside that reference's span, or the smallest definition containing the
13//! cursor when no reference does.
14
15use super::name_reference::span_strictly_inside;
16use super::{IndexReader, ResolvedDefinition};
17use crate::format::*;
18
19/// True when a definition's name is a synthetic compiler placeholder rather than a user-written
20/// source identifier (`""` crate root, `"{use#N}"`, `"{impl#N}"`, `"{closure#N}"`, or a numeric
21/// tuple-struct field `"0"`, `"1"`, ... whose span covers the field's type).
22pub(crate) fn is_synthetic_def_name(kind: DefKind, name: &str) -> bool {
23 kind == DefKind::Impl
24 || name.is_empty()
25 || name.starts_with('{')
26 || (kind == DefKind::Field && name.bytes().all(|b| b.is_ascii_digit()))
27 || (kind == DefKind::Local && name.starts_with("__"))
28}
29
30impl<B: AsRef<[u8]>> IndexReader<B> {
31 /// Go to definition at a given cursor position `(file, line, col)`.
32 ///
33 /// The innermost name reference at the cursor answers, unless a definition at the cursor lies
34 /// inside that reference's span: a reference spanning a macro invocation or a generated call
35 /// encloses every item written inside it, and on such an item's name the item is the answer.
36 /// Equal spans (a self-reference) keep the reference. A reference as wide as its target's name
37 /// cannot enclose a definition, so no definition is looked for behind it. Without a reference
38 /// the smallest named definition containing the cursor answers; the nameless crate-root module
39 /// the driver records with the span of the whole file never does, so a position on no name
40 /// has no definition.
41 pub fn find_definition_at(&self, file: &str, line: u32, col: u32) -> Option<ResolvedDefinition<'_>> {
42 let file_id = self.find_file_id(file)?;
43 let inner = self.find_innermost_ref_at_file_id(file_id, line, col);
44 if let Some(r) = inner {
45 if !self.may_enclose_definition(r) {
46 return Some(self.resolve_ref_definition(r));
47 }
48 }
49
50 let mut best_def: Option<(&DefEntry, u64)> = None;
51 for def in self.definitions() {
52 let def_span = def.span();
53 // Span checks first: they are integer comparisons on every definition; the name is
54 // read only for a definition that contains the cursor.
55 if def_span.contains(file_id, line, col)
56 && inner.is_none_or(|r| span_strictly_inside(&def_span, &r.span()))
57 && !is_synthetic_def_name(DefKind::from(def.kind), self.get_str(def.name_offset()))
58 {
59 let size = def_span.approximate_size();
60 if best_def.is_none_or(|(_, best_size)| size < best_size) {
61 best_def = Some((def, size));
62 }
63 }
64 }
65 if let Some((def, _)) = best_def {
66 return Some(self.def_to_resolved(def));
67 }
68 inner.map(|r| self.resolve_ref_definition(r))
69 }
70
71 /// Finds the innermost `RefEntry` at `(file, line, col)` via binary search on span-sorted references.
72 pub fn find_innermost_ref_at(&self, file: &str, line: u32, col: u32) -> Option<&RefEntry> {
73 let file_id = self.find_file_id(file)?;
74 self.find_innermost_ref_at_file_id(file_id, line, col)
75 }
76
77 /// Finds the innermost `RefEntry` at `(file_id, line, col)` via binary search on span-sorted references.
78 /// References that are not uses of a name (`is_name_reference`) are skipped.
79 pub fn find_innermost_ref_at_file_id(&self, file_id: u32, line: u32, col: u32) -> Option<&RefEntry> {
80 let refs = self.references();
81 let key = (file_id, line, col);
82 let hi = refs.partition_point(|r| {
83 let s = r.span();
84 (s.file_id(), s.start_line(), s.start_col()) <= key
85 });
86
87 let mut best: Option<(&RefEntry, u64)> = None;
88 for r in refs[..hi].iter().rev() {
89 let span = r.span();
90 if span.file_id() != file_id {
91 break;
92 }
93 if let Some((_, best_size)) = best {
94 let min_size = if line > span.start_line() { (line - span.start_line()) as u64 * 80 } else { (col.saturating_sub(span.start_col()) as u64).min(80) };
95 if min_size > best_size {
96 break;
97 }
98 }
99 if !span.contains(file_id, line, col) {
100 continue;
101 }
102 if !self.is_name_reference(r) {
103 continue;
104 }
105 let size = span.approximate_size();
106 // A shorthand (`Point { x }`) names the local and the field on one span: the local comes first, as
107 // rust-analyzer's first definition of a field shorthand.
108 let yields_to_local = |b: &RefEntry| DefKind::from(b.kind) == DefKind::Local && DefKind::from(r.kind) == DefKind::Field;
109 if best.is_none_or(|(b, best_size)| size < best_size || (size == best_size && !yields_to_local(b))) {
110 best = Some((r, size));
111 }
112 }
113 best.map(|(r, _)| r)
114 }
115}