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