1use 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#[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 Resolved,
20 Unresolved,
22 Other,
24}
25
26#[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 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)]
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#[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#[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 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 #[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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub address: Option<Address>,
183}
184
185impl Match {
186 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 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 #[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}