1use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11use crate::symbol::Symbol;
12use crate::text::Span;
13
14#[derive(Debug, Clone, thiserror::Error)]
15pub enum SearchError {
16 #[error(transparent)]
17 Facts(#[from] crate::FactsError),
18 #[error(transparent)]
19 Span(#[from] crate::SpanError),
20 #[error("invalid pattern: {0}")]
21 Pattern(String),
22 #[error("invalid node kind: {0}")]
23 Kind(String),
24 #[error("{0}")]
25 Other(String),
26}
27
28#[derive(
32 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
33)]
34#[serde(rename_all = "lowercase")]
35#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
36pub enum Role {
37 Declaration,
38 Import,
39 #[default]
40 Use,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46pub struct Capture {
47 pub span: Span,
48 pub text: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54#[serde(untagged)]
55pub enum CaptureValue {
56 Single(Capture),
57 Multiple(Vec<Capture>),
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
63pub struct RawMatch {
64 pub span: Span,
65 pub kind: String,
67 pub text: String,
68 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
69 pub captures: BTreeMap<String, CaptureValue>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub symbol: Option<Symbol>,
73 #[serde(default)]
74 pub role: Role,
75}
76
77impl RawMatch {
78 pub fn validate_in(&self, source: &str) -> Result<(), crate::SpanError> {
80 self.span.validate_in(source)?;
81 if let Some(symbol) = &self.symbol {
82 symbol.validate_in(source)?;
83 }
84 for value in self.captures.values() {
85 match value {
86 CaptureValue::Single(capture) => capture.span.validate_in(source)?,
87 CaptureValue::Multiple(captures) => {
88 for capture in captures {
89 capture.span.validate_in(source)?;
90 }
91 }
92 }
93 }
94 Ok(())
95 }
96 pub fn plain(span: Span, kind: impl Into<String>, text: impl Into<String>) -> Self {
98 Self {
99 span,
100 kind: kind.into(),
101 text: text.into(),
102 captures: BTreeMap::new(),
103 symbol: None,
104 role: Role::Use,
105 }
106 }
107}