Skip to main content

vvv_core/query/
mod.rs

1//! What the user is looking for. Declarative and serializable so the CLI, a
2//! TUI form, and a JSON request all build the same value.
3//!
4//! `pattern` and `kind` select nodes structurally; `symbol` and `name`
5//! select declarations. When both sides are given a match must satisfy both.
6
7use serde::{Deserialize, Serialize};
8
9use crate::lang::LanguageId;
10use crate::symbol::SymbolKind;
11
12#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
14pub struct Query {
15    /// ast-grep style pattern with meta-variables, e.g. `fn $NAME($$$ARGS) { $$$ }`.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pattern: Option<String>,
18    /// Tree-sitter node kind, e.g. `function_item`.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    kind: Option<String>,
21    /// Only declarations of this kind.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    symbol: Option<SymbolKind>,
24    /// Only declarations with exactly this name.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    name: Option<String>,
27    /// Restrict to one language; otherwise every registered language is searched.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    language: Option<LanguageId>,
30}
31
32#[derive(Debug, thiserror::Error, PartialEq, Eq)]
33pub enum QueryError {
34    #[error("a query needs at least one of: pattern, kind, symbol, name")]
35    Empty,
36}
37
38impl Query {
39    pub fn builder() -> QueryBuilder {
40        QueryBuilder::default()
41    }
42
43    /// A query has to ask something: one read from JSON may not.
44    pub fn check(&self) -> Result<(), QueryError> {
45        if self.is_structural() || self.is_symbolic() {
46            Ok(())
47        } else {
48            Err(QueryError::Empty)
49        }
50    }
51
52    pub fn pattern(pattern: impl Into<String>) -> Self {
53        Self {
54            pattern: Some(pattern.into()),
55            ..Self::default()
56        }
57    }
58
59    pub fn of_kind(kind: impl Into<String>) -> Self {
60        Self {
61            kind: Some(kind.into()),
62            ..Self::default()
63        }
64    }
65
66    pub fn of_symbol(symbol: SymbolKind) -> Self {
67        Self {
68            symbol: Some(symbol),
69            ..Self::default()
70        }
71    }
72
73    pub fn named(name: impl Into<String>) -> Self {
74        Self {
75            name: Some(name.into()),
76            ..Self::default()
77        }
78    }
79
80    pub fn with_kind(mut self, kind: impl Into<String>) -> Self {
81        self.kind = Some(kind.into());
82        self
83    }
84
85    pub fn with_symbol(mut self, symbol: SymbolKind) -> Self {
86        self.symbol = Some(symbol);
87        self
88    }
89
90    pub fn with_name(mut self, name: impl Into<String>) -> Self {
91        self.name = Some(name.into());
92        self
93    }
94
95    pub fn in_language(mut self, language: impl Into<LanguageId>) -> Self {
96        self.language = Some(language.into());
97        self
98    }
99
100    pub fn pattern_str(&self) -> Option<&str> {
101        self.pattern.as_deref()
102    }
103
104    pub fn kind_str(&self) -> Option<&str> {
105        self.kind.as_deref()
106    }
107
108    pub fn symbol(&self) -> Option<SymbolKind> {
109        self.symbol
110    }
111
112    pub fn name(&self) -> Option<&str> {
113        self.name.as_deref()
114    }
115
116    pub fn language(&self) -> Option<&LanguageId> {
117        self.language.as_ref()
118    }
119
120    /// True when the query selects nodes structurally (pattern or kind).
121    pub fn is_structural(&self) -> bool {
122        self.pattern.is_some() || self.kind.is_some()
123    }
124
125    /// True when the query filters on declarations (symbol or name).
126    pub fn is_symbolic(&self) -> bool {
127        self.symbol.is_some() || self.name.is_some()
128    }
129
130    /// Words every match must contain as whole tokens: the identifier- and
131    /// number-like runs of the pattern that are not meta-variables, and the
132    /// symbol name. A file whose text lacks any of them cannot match, so a
133    /// search may skip it without parsing. Empty for a kind-only query.
134    pub fn literals(&self) -> Vec<&str> {
135        let mut words: Vec<&str> = self
136            .pattern
137            .as_deref()
138            .map(Self::pattern_words)
139            .unwrap_or_default();
140        words.extend(self.name.as_deref());
141        words.sort_unstable();
142        words.dedup();
143        words
144    }
145
146    /// Token-like runs of `pattern`, skipping any introduced by `$`.
147    fn pattern_words(pattern: &str) -> Vec<&str> {
148        let is_word = |c: char| c.is_alphanumeric() || c == '_';
149        let mut words = Vec::new();
150        let mut rest = pattern;
151        while let Some(start) = rest.find(is_word) {
152            let meta = rest[..start].ends_with('$');
153            let tail = &rest[start..];
154            let end = tail.find(|c| !is_word(c)).unwrap_or(tail.len());
155            if !meta {
156                words.push(&tail[..end]);
157            }
158            rest = &tail[end..];
159        }
160        words
161    }
162}
163
164/// Assemble a [`Query`] from optional parts (typically CLI flags).
165#[derive(Debug, Default)]
166pub struct QueryBuilder {
167    query: Query,
168}
169
170impl QueryBuilder {
171    pub fn pattern(mut self, pattern: Option<impl Into<String>>) -> Self {
172        self.query.pattern = pattern.map(Into::into);
173        self
174    }
175
176    pub fn kind(mut self, kind: Option<impl Into<String>>) -> Self {
177        self.query.kind = kind.map(Into::into);
178        self
179    }
180
181    pub fn symbol(mut self, symbol: Option<SymbolKind>) -> Self {
182        self.query.symbol = symbol;
183        self
184    }
185
186    pub fn name(mut self, name: Option<impl Into<String>>) -> Self {
187        self.query.name = name.map(Into::into);
188        self
189    }
190
191    pub fn language(mut self, language: Option<impl Into<LanguageId>>) -> Self {
192        self.query.language = language.map(Into::into);
193        self
194    }
195
196    pub fn build(self) -> Result<Query, QueryError> {
197        self.query.check()?;
198        Ok(self.query)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn literals_are_pattern_words_minus_meta_variables() {
208        let q = Query::pattern("$A.foo($$$ARGS, bar_2, $_)");
209        assert_eq!(q.literals(), vec!["bar_2", "foo"]);
210    }
211
212    #[test]
213    fn literals_include_the_name_and_skip_kinds() {
214        assert_eq!(Query::of_kind("mod_item").literals(), Vec::<&str>::new());
215        assert_eq!(
216            Query::of_kind("fn").with_name("run").literals(),
217            vec!["run"]
218        );
219        assert_eq!(
220            Query::pattern("run").with_name("run").literals(),
221            vec!["run"]
222        );
223    }
224
225    #[test]
226    fn literals_keep_number_tokens_whole() {
227        assert_eq!(Query::pattern("$X + 0x1f").literals(), vec!["0x1f"]);
228    }
229
230    #[test]
231    fn literals_keep_keywords_and_unicode() {
232        assert_eq!(
233            Query::pattern("fn $F() { héllo }").literals(),
234            vec!["fn", "héllo"]
235        );
236    }
237}