use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::symbol::Symbol;
use crate::text::Span;
#[derive(Debug, Clone, thiserror::Error)]
pub enum SearchError {
#[error(transparent)]
Facts(#[from] crate::FactsError),
#[error(transparent)]
Span(#[from] crate::SpanError),
#[error("invalid pattern: {0}")]
Pattern(String),
#[error("invalid node kind: {0}")]
Kind(String),
#[error("{0}")]
Other(String),
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Role {
Declaration,
Import,
#[default]
Use,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Capture {
pub span: Span,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(untagged)]
pub enum CaptureValue {
Single(Capture),
Multiple(Vec<Capture>),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RawMatch {
pub span: Span,
pub kind: String,
pub text: 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,
}
impl RawMatch {
pub fn validate_in(&self, source: &str) -> Result<(), crate::SpanError> {
self.span.validate_in(source)?;
if let Some(symbol) = &self.symbol {
symbol.validate_in(source)?;
}
for value in self.captures.values() {
match value {
CaptureValue::Single(capture) => capture.span.validate_in(source)?,
CaptureValue::Multiple(captures) => {
for capture in captures {
capture.span.validate_in(source)?;
}
}
}
}
Ok(())
}
pub fn plain(span: Span, kind: impl Into<String>, text: impl Into<String>) -> Self {
Self {
span,
kind: kind.into(),
text: text.into(),
captures: BTreeMap::new(),
symbol: None,
role: Role::Use,
}
}
}