use std::collections::BTreeMap;
use std::fmt;
use vvv_core::RelPath;
use serde::{Deserialize, Serialize};
use vvv_core::{Address, CaptureValue, LanguageId, Position, Role, Span, Symbol};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum Confidence {
Resolved,
Unresolved,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum Reason {
Declaring,
Imported,
Path,
Opened,
ReExport,
Oracle,
Unresolved,
ByName,
OtherDeclaration,
External,
OracleOther,
}
impl Reason {
pub fn confidence(self) -> Confidence {
match self {
Self::Declaring
| Self::Imported
| Self::Path
| Self::Opened
| Self::ReExport
| Self::Oracle => Confidence::Resolved,
Self::Unresolved | Self::ByName => Confidence::Unresolved,
Self::OtherDeclaration | Self::External | Self::OracleOther => Confidence::Other,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Occurrence {
#[serde(flatten)]
pub m: Match,
pub confidence: Confidence,
#[serde(default = "Reason::unresolved")]
pub reason: Reason,
}
impl Occurrence {
pub fn judged(m: Match, reason: Reason) -> Self {
Self {
m,
confidence: reason.confidence(),
reason,
}
}
}
impl Reason {
fn unresolved() -> Self {
Self::Unresolved
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Skipped {
pub language: LanguageId,
pub reason: String,
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct MatchId(String);
impl MatchId {
const LEN: usize = 12;
pub fn derive(path: &RelPath, span: Span, text: &str) -> Self {
let mut hasher = blake3::Hasher::new();
hasher.update(path.as_str().as_bytes());
hasher.update(&span.start.to_le_bytes());
hasher.update(&span.end.to_le_bytes());
hasher.update(text.as_bytes());
let hex = hasher.finalize().to_hex();
Self(hex[..Self::LEN].to_owned())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<String> for MatchId {
fn from(id: String) -> Self {
Self(id)
}
}
impl fmt::Display for MatchId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for MatchId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MatchId({})", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Match {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<crate::ContentId>,
pub id: MatchId,
pub path: RelPath,
pub language: LanguageId,
pub span: Span,
pub start: Position,
pub end: Position,
pub kind: String,
pub text: String,
#[serde(default)]
pub line: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub captures: BTreeMap<String, CaptureValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub symbol: Option<Symbol>,
#[serde(default)]
pub role: Role,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub address: Option<Address>,
}
impl Match {
pub(crate) fn same_source_match(&self, other: &Self) -> bool {
self.id == other.id
&& self.path == other.path
&& self.language == other.language
&& self.span == other.span
&& self.start == other.start
&& self.end == other.end
&& self.kind == other.kind
&& self.text == other.text
&& self.line == other.line
&& self.captures == other.captures
&& self.symbol == other.symbol
&& self.role == other.role
}
pub fn anchor(&self) -> Option<crate::SourceAnchor> {
Some(crate::SourceAnchor {
path: self.path.clone(),
content: self.content.clone()?,
span: self.symbol.as_ref().map_or(self.span, |s| s.name_span),
})
}
pub fn capture(&self, name: &str) -> Option<&CaptureValue> {
self.captures.get(name)
}
pub fn line_count(&self) -> u32 {
self.end.line - self.start.line + 1
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn match_id_is_stable_and_sensitive() {
let a = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
let b = MatchId::derive(&RelPath::from("a.rs"), Span::new(0, 3), "foo");
let c = MatchId::derive(&RelPath::from("b.rs"), Span::new(0, 3), "foo");
assert_eq!(a, b);
assert_ne!(a, c);
assert_eq!(a.as_str().len(), MatchId::LEN);
}
#[test]
fn reasons_are_declared_in_confidence_order() {
let all = [
Reason::Declaring,
Reason::Imported,
Reason::Path,
Reason::Opened,
Reason::ReExport,
Reason::Oracle,
Reason::Unresolved,
Reason::ByName,
Reason::OtherDeclaration,
Reason::External,
Reason::OracleOther,
];
let confidences: Vec<Confidence> = all.iter().map(|r| r.confidence()).collect();
let mut sorted = confidences.clone();
sorted.sort();
assert_eq!(confidences, sorted);
assert!(all.windows(2).all(|w| w[0] < w[1]));
}
}