Skip to main content

vvv_engine/protocol/
search.rs

1//! What a search answers with: a [`RawMatch`] tied to its file as a
2//! [`Match`] with a stable [`MatchId`], and, for a rename, each occurrence
3//! judged against the declaration meant.
4
5use std::collections::BTreeMap;
6use std::fmt;
7
8use vvv_core::RelPath;
9
10use serde::{Deserialize, Serialize};
11use vvv_core::{Address, CaptureValue, LanguageId, Position, RawMatch, Role, Span, Symbol};
12
13use crate::SourceFile;
14
15/// How sure a rename is that an occurrence refers to its target declaration.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum Confidence {
19    /// Declared, imported, or reached by a path that resolves to the target.
20    Resolved,
21    /// A bare token with no evidence either way.
22    Unresolved,
23    /// Resolves to a different declaration of the same name.
24    Other,
25}
26
27/// What the file's imports and paths said about an occurrence: the ground
28/// for its [`Confidence`]. Views tag `?` and `✗` sections with it.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum Reason {
32    /// Written in the module that declares the target.
33    Declaring,
34    /// An import resolving to the target brings the name in.
35    Imported,
36    /// The tail of a qualified path resolving to the target.
37    Path,
38    /// A glob (or whole-file) import opens the declaring module.
39    Opened,
40    /// Reached through a re-export (`use vvv_core::Span` for
41    /// `vvv_core::text::span::Span`) that vvv followed to the declaration.
42    ReExport,
43    /// Syntax could not place it; an oracle — a build, a language server —
44    /// said it is the declaration.
45    Oracle,
46    /// A bare name nothing imports, or a path whose head cannot be placed.
47    Unresolved,
48    /// No declaration to judge against: a method or field, reached through
49    /// a type; the token merely spells the name.
50    ByName,
51    /// Resolves to another declaration of the same name in the workspace.
52    OtherDeclaration,
53    /// Resolves into a package outside the workspace.
54    External,
55    /// Syntax could not place it; an oracle said it is another declaration.
56    OracleOther,
57}
58
59impl Reason {
60    pub fn confidence(self) -> Confidence {
61        match self {
62            Self::Declaring
63            | Self::Imported
64            | Self::Path
65            | Self::Opened
66            | Self::ReExport
67            | Self::Oracle => Confidence::Resolved,
68            Self::Unresolved | Self::ByName => Confidence::Unresolved,
69            Self::OtherDeclaration | Self::External | Self::OracleOther => Confidence::Other,
70        }
71    }
72}
73
74/// A token spelling the renamed name, with what the imports could tell.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Occurrence {
77    #[serde(flatten)]
78    pub m: Match,
79    pub confidence: Confidence,
80    #[serde(default = "Reason::unresolved")]
81    pub reason: Reason,
82}
83
84impl Occurrence {
85    pub fn judged(m: Match, reason: Reason) -> Self {
86        Self {
87            m,
88            confidence: reason.confidence(),
89            reason,
90        }
91    }
92}
93
94impl Reason {
95    fn unresolved() -> Self {
96        Self::Unresolved
97    }
98}
99/// A language a search left out, and why: its grammar could not compile the
100/// query (a Rust pattern on a TypeScript tree). Never fatal; the other
101/// languages' matches are complete. Data only; the display layer words it.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct Skipped {
104    pub language: LanguageId,
105    pub reason: String,
106}
107
108/// Content-derived identifier: the same file, range and text yield the same id
109/// across runs, so a selection made from one `search` can drive a later command.
110#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct MatchId(String);
113
114impl MatchId {
115    const LEN: usize = 12;
116
117    /// The file, the span and the text, in one workspace spelling: an id is
118    /// the same on every platform, so a selection made in one process holds
119    /// in the next.
120    pub fn derive(path: &RelPath, span: Span, text: &str) -> Self {
121        let mut hasher = blake3::Hasher::new();
122        hasher.update(path.as_str().as_bytes());
123        hasher.update(&span.start.to_le_bytes());
124        hasher.update(&span.end.to_le_bytes());
125        hasher.update(text.as_bytes());
126        let hex = hasher.finalize().to_hex();
127        Self(hex[..Self::LEN].to_owned())
128    }
129
130    pub fn as_str(&self) -> &str {
131        &self.0
132    }
133}
134
135impl From<String> for MatchId {
136    fn from(id: String) -> Self {
137        Self(id)
138    }
139}
140
141impl fmt::Display for MatchId {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(&self.0)
144    }
145}
146
147impl fmt::Debug for MatchId {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        write!(f, "MatchId({})", self.0)
150    }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct Match {
155    pub id: MatchId,
156    pub path: RelPath,
157    pub language: LanguageId,
158    pub span: Span,
159    pub start: Position,
160    pub end: Position,
161    pub kind: String,
162    pub text: String,
163    /// The source line on which the match starts, for display in context.
164    #[serde(default)]
165    pub line: String,
166    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
167    pub captures: BTreeMap<String, CaptureValue>,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub symbol: Option<Symbol>,
170    #[serde(default)]
171    pub role: Role,
172    /// For a declaration in an addressable file: its module address, the
173    /// value `outline` gives it. Filled by the engine, which has the project.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub address: Option<Address>,
176}
177
178impl Match {
179    pub fn locate(raw: RawMatch, file: &SourceFile, language: LanguageId) -> Self {
180        let source = file.source();
181        let start = source.position(raw.span.start);
182        let path = RelPath::from(file.path());
183        Self {
184            id: MatchId::derive(&path, raw.span, &raw.text),
185            path,
186            language,
187            span: raw.span,
188            start,
189            end: source.position(raw.span.end),
190            line: source
191                .line(start.line as usize)
192                .unwrap_or_default()
193                .to_owned(),
194            kind: raw.kind,
195            text: raw.text,
196            captures: raw.captures,
197            symbol: raw.symbol,
198            role: raw.role,
199            address: None,
200        }
201    }
202
203    pub fn capture(&self, name: &str) -> Option<&CaptureValue> {
204        self.captures.get(name)
205    }
206
207    /// Number of lines the match spans.
208    pub fn line_count(&self) -> u32 {
209        self.end.line - self.start.line + 1
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn match_id_is_stable_and_sensitive() {
219        let a = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
220        let b = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
221        let c = MatchId::derive(&RelPath::from("b.rs"), Span::new(0, 3), "foo");
222        assert_eq!(a, b);
223        assert_ne!(a, c);
224        assert_eq!(a.as_str().len(), MatchId::LEN);
225    }
226
227    /// Occurrences sort by reason, and a preview lists `✓`, then `?`, then
228    /// `✗`: the reasons must be declared in that order.
229    #[test]
230    fn reasons_are_declared_in_confidence_order() {
231        let all = [
232            Reason::Declaring,
233            Reason::Imported,
234            Reason::Path,
235            Reason::Opened,
236            Reason::ReExport,
237            Reason::Oracle,
238            Reason::Unresolved,
239            Reason::ByName,
240            Reason::OtherDeclaration,
241            Reason::External,
242            Reason::OracleOther,
243        ];
244        let confidences: Vec<Confidence> = all.iter().map(|r| r.confidence()).collect();
245        let mut sorted = confidences.clone();
246        sorted.sort();
247        assert_eq!(confidences, sorted);
248        assert!(all.windows(2).all(|w| w[0] < w[1]));
249    }
250}