Skip to main content

vvv_engine/protocol/
search.rs

1//! What a search answers with: a [`vvv_core::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, Role, Span, Symbol};
12
13/// How sure a rename is that an occurrence refers to its target declaration.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16#[serde(rename_all = "lowercase")]
17pub enum Confidence {
18    /// Declared, imported, or reached by a path that resolves to the target.
19    Resolved,
20    /// A bare token with no evidence either way.
21    Unresolved,
22    /// Resolves to a different declaration of the same name.
23    Other,
24}
25
26/// What the file's imports and paths said about an occurrence: the ground
27/// for its [`Confidence`]. Views tag `?` and `✗` sections with it.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
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)]
76#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
77pub struct Occurrence {
78    #[serde(flatten)]
79    pub m: Match,
80    pub confidence: Confidence,
81    #[serde(default = "Reason::unresolved")]
82    pub reason: Reason,
83}
84
85impl Occurrence {
86    pub fn judged(m: Match, reason: Reason) -> Self {
87        Self {
88            m,
89            confidence: reason.confidence(),
90            reason,
91        }
92    }
93}
94
95impl Reason {
96    fn unresolved() -> Self {
97        Self::Unresolved
98    }
99}
100/// A language a search left out, and why: its grammar could not compile the
101/// query (a Rust pattern on a TypeScript tree). Never fatal; the other
102/// languages' matches are complete. Data only; the display layer words it.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105pub struct Skipped {
106    pub language: LanguageId,
107    pub reason: String,
108}
109
110/// Content-derived identifier: the same file, range and text yield the same id
111/// across runs, so a selection made from one `search` can drive a later command.
112#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
114#[serde(transparent)]
115pub struct MatchId(String);
116
117impl MatchId {
118    const LEN: usize = 12;
119
120    /// The file, the span and the text, in one workspace spelling: an id is
121    /// the same on every platform, so a selection made in one process holds
122    /// in the next.
123    pub fn derive(path: &RelPath, span: Span, text: &str) -> Self {
124        let mut hasher = blake3::Hasher::new();
125        hasher.update(path.as_str().as_bytes());
126        hasher.update(&span.start.to_le_bytes());
127        hasher.update(&span.end.to_le_bytes());
128        hasher.update(text.as_bytes());
129        let hex = hasher.finalize().to_hex();
130        Self(hex[..Self::LEN].to_owned())
131    }
132
133    pub fn as_str(&self) -> &str {
134        &self.0
135    }
136}
137
138impl From<String> for MatchId {
139    fn from(id: String) -> Self {
140        Self(id)
141    }
142}
143
144impl fmt::Display for MatchId {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.write_str(&self.0)
147    }
148}
149
150impl fmt::Debug for MatchId {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "MatchId({})", self.0)
153    }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
157#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
158pub struct Match {
159    /// Complete source version; absent only in older serialized matches.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub content: Option<crate::ContentId>,
162    pub id: MatchId,
163    pub path: RelPath,
164    pub language: LanguageId,
165    pub span: Span,
166    pub start: Position,
167    pub end: Position,
168    pub kind: String,
169    pub text: String,
170    /// The source line on which the match starts, for display in context.
171    #[serde(default)]
172    pub line: String,
173    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
174    pub captures: BTreeMap<String, CaptureValue>,
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub symbol: Option<Symbol>,
177    #[serde(default)]
178    pub role: Role,
179    /// For a declaration in an addressable file: its module address, the
180    /// value `outline` gives it. Filled by the engine, which has the project.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub address: Option<Address>,
183}
184
185impl Match {
186    /// Compare source-derived search data, excluding the resolved address
187    /// that the graph may attach after searching.
188    pub(crate) fn same_source_match(&self, other: &Self) -> bool {
189        self.id == other.id
190            && self.path == other.path
191            && self.language == other.language
192            && self.span == other.span
193            && self.start == other.start
194            && self.end == other.end
195            && self.kind == other.kind
196            && self.text == other.text
197            && self.line == other.line
198            && self.captures == other.captures
199            && self.symbol == other.symbol
200            && self.role == other.role
201    }
202
203    pub fn anchor(&self) -> Option<crate::SourceAnchor> {
204        Some(crate::SourceAnchor {
205            path: self.path.clone(),
206            content: self.content.clone()?,
207            span: self.symbol.as_ref().map_or(self.span, |s| s.name_span),
208        })
209    }
210
211    pub fn capture(&self, name: &str) -> Option<&CaptureValue> {
212        self.captures.get(name)
213    }
214
215    /// Number of lines the match spans.
216    pub fn line_count(&self) -> u32 {
217        self.end.line - self.start.line + 1
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn match_id_is_stable_and_sensitive() {
227        let a = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
228        let b = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
229        let c = MatchId::derive(&RelPath::from("b.rs"), Span::new(0, 3), "foo");
230        assert_eq!(a, b);
231        assert_ne!(a, c);
232        assert_eq!(a.as_str().len(), MatchId::LEN);
233    }
234
235    /// Occurrences sort by reason, and a preview lists `✓`, then `?`, then
236    /// `✗`: the reasons must be declared in that order.
237    #[test]
238    fn reasons_are_declared_in_confidence_order() {
239        let all = [
240            Reason::Declaring,
241            Reason::Imported,
242            Reason::Path,
243            Reason::Opened,
244            Reason::ReExport,
245            Reason::Oracle,
246            Reason::Unresolved,
247            Reason::ByName,
248            Reason::OtherDeclaration,
249            Reason::External,
250            Reason::OracleOther,
251        ];
252        let confidences: Vec<Confidence> = all.iter().map(|r| r.confidence()).collect();
253        let mut sorted = confidences.clone();
254        sorted.sort();
255        assert_eq!(confidences, sorted);
256        assert!(all.windows(2).all(|w| w[0] < w[1]));
257    }
258}