1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
17#[serde(rename_all = "lowercase")]
18pub enum Confidence {
19 Resolved,
21 Unresolved,
23 Other,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum Reason {
32 Declaring,
34 Imported,
36 Path,
38 Opened,
40 ReExport,
43 Oracle,
46 Unresolved,
48 ByName,
51 OtherDeclaration,
53 External,
55 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct Skipped {
104 pub language: LanguageId,
105 pub reason: String,
106}
107
108#[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 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 #[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 #[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 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 #[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}