1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use std::ops;

use serde::{Deserialize, Serialize};

use snafu::{ensure, Snafu};

use crate::{parser, Resolver, Span};

/// The error type returned by the query parser.
#[derive(Debug, Snafu)]
pub enum Error {
    #[snafu(display("parse error"))]
    ParseError { message: String },
}

/// A parsed (or manually constructed) query expression.
///
/// An expression can be arbitrarily nested.
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum Expression {
    /// Tag expression.
    ///
    /// Evaluates to resolver items where the tag is present.
    Tag { tag: String },
    /// Key/Value expression.
    ///
    /// Evaluates to resolver items where the given key/value pair is present.
    KeyValue { key: String, value: String },
    /// HasKey expression.
    ///
    /// Evaluates to resolver items where the given key is present (in any key/value pair).
    HasKey { key: String },
    /// Parent expression.
    ///
    /// Evaluates to resolver items having the provided value as a parent.
    Parent { parent: String },
    /// And expression.
    ///
    /// Evaluates to the intersection of its two sub-expressions.
    And {
        and: (Box<Expression>, Box<Expression>),
    },
    /// Or expression.
    /// Evaluates to the union of its two sub-expressions.
    Or {
        or: (Box<Expression>, Box<Expression>),
    },
    /// Not expression.
    /// Evaluates to the negation of its sub-expression.
    Not { not: Box<Expression> },
    /// Empty expression.
    /// Evaluates to all items resolvable by the resolver.
    Empty,
}

impl Expression {
    /// Parse an expression from a string.
    ///
    /// Returns an error if the provided string could not be parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use rapidquery::Expression;
    ///
    /// let expression = "a && b";
    /// match Expression::parse(expression) {
    ///     Ok(expr) => println!("Got expression: {:?}", expr),
    ///     Err(e) => panic!("failed to parse")
    /// }
    /// ```
    pub fn parse<S: AsRef<str>>(str_expr: S) -> Result<Self, Error> {
        let (rest, expr) =
            parser::expression(str_expr.as_ref()).map_err(|e| Error::ParseError {
                message: e.to_string(),
            })?;

        ensure!(
            rest.is_empty(),
            ParseError {
                message: "incomplete parse".to_string()
            }
        );

        Ok(expr)
    }

    /// Evaluate an expression using a resolver.
    ///
    /// The resolver is tasked with resolving the sets corresponding to the various sub-expressions kinds (tags, key/value pairs, etc.).
    /// From there, the evaluator will recursively compute the query, calling the resolver when appropriate.
    ///
    /// # Examples
    /// ```no_run
    /// use rapidquery::{Expression, Resolver};
    ///
    /// let resolver: Box<dyn Resolver<bool, Error = std::io::Error>> = {
    ///     unimplemented!()
    /// };
    ///
    /// let expr = Expression::Empty;;
    ///
    /// let evaluation: bool = expr.evaluate(&resolver)?;
    /// # Ok::<(), std::io::Error>(())
    /// ```
    pub fn evaluate<R, V, E>(&self, resolver: &R) -> Result<V, E>
    where
        V: ops::BitAndAssign + ops::BitOrAssign + ops::Not<Output = V> + Span + std::fmt::Display,
        R: Resolver<V, Error = E>,
    {
        match self {
            Expression::Empty => resolver.resolve_empty(),
            Expression::Tag { tag } => resolver.resolve_tag(&tag),
            Expression::KeyValue { key, value } => resolver.resolve_key_value(&key, &value),
            Expression::HasKey { key } => resolver.resolve_key(&key),
            Expression::Parent { parent } => resolver.resolve_children(&parent),
            Expression::Not { not } => {
                let mut all_bv = resolver.resolve_empty()?;
                all_bv &= not.evaluate(resolver)?;
                let mut negated = !all_bv;
                negated &= resolver.resolve_empty()?;
                Ok(negated)
            }
            Expression::And { and } => {
                let (lhs, rhs) = and;
                let lhs_bv = lhs.evaluate(resolver)?;
                let rhs_bv = rhs.evaluate(resolver)?;
                let (mut biggest, smallest) = if lhs_bv.span() > rhs_bv.span() {
                    (lhs_bv, rhs_bv)
                } else {
                    (rhs_bv, lhs_bv)
                };

                biggest &= smallest;
                Ok(biggest)
            }
            Expression::Or { or } => {
                let (lhs, rhs) = or;
                let lhs_bv = lhs.evaluate(resolver)?;
                let rhs_bv = rhs.evaluate(resolver)?;
                let (mut biggest, smallest) = if lhs_bv.span() > rhs_bv.span() {
                    (lhs_bv, rhs_bv)
                } else {
                    (rhs_bv, lhs_bv)
                };
                biggest |= smallest;
                Ok(biggest)
            }
        }
    }
}

impl Default for Expression {
    fn default() -> Self {
        Self::Empty
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, convert::Infallible};

    use super::*;

    #[derive(Default)]
    struct MockResolver {
        tags: Vec<String>,
        kv: HashMap<String, String>,
        keys: Vec<String>,
        parents: Vec<String>,
    }

    impl MockResolver {
        pub fn with_tag<S: Into<String>>(mut self, tag: S) -> Self {
            self.tags.push(tag.into());
            self
        }

        pub fn with_key_value<K: Into<String>, V: Into<String>>(mut self, k: K, v: V) -> Self {
            let key: String = k.into();
            self.keys.push(key.clone());
            self.kv.insert(key, v.into());
            self
        }

        pub fn with_parent<S: Into<String>>(mut self, parent: S) -> Self {
            self.parents.push(parent.into());
            self
        }
    }

    impl Resolver<bool> for MockResolver {
        type Error = Infallible;

        fn resolve_children(&self, parent_id: &str) -> Result<bool, Self::Error> {
            Ok(self.parents.contains(&String::from(parent_id)))
        }

        fn resolve_empty(&self) -> Result<bool, Self::Error> {
            Ok(true)
        }

        fn resolve_key(&self, key: &str) -> Result<bool, Self::Error> {
            Ok(self.keys.contains(&String::from(key)))
        }

        fn resolve_key_value(&self, key: &str, value: &str) -> Result<bool, Self::Error> {
            Ok(self.kv.get(&String::from(key)) == Some(&String::from(value)))
        }

        fn resolve_tag(&self, tag: &str) -> Result<bool, Self::Error> {
            Ok(self.tags.contains(&String::from(tag)))
        }
    }

    #[test]
    fn eval_empty_query() {
        assert!(Expression::Empty
            .evaluate(&MockResolver::default())
            .unwrap())
    }

    #[test]
    fn eval_tag_query() {
        assert!(Expression::Tag {
            tag: "hello".into()
        }
        .evaluate(&MockResolver::default().with_tag("hello"))
        .unwrap());
    }

    #[test]
    fn eval_tag_nomatch() {
        assert!(!Expression::Tag {
            tag: "yayeet".into()
        }
        .evaluate(&MockResolver::default().with_tag("Hello"))
        .unwrap())
    }

    #[test]
    fn eval_kv_query() {
        assert!(Expression::KeyValue {
            key: "key".into(),
            value: "val".into()
        }
        .evaluate(&MockResolver::default().with_key_value("key", "val"))
        .unwrap())
    }

    #[test]
    fn eval_kv_nomatch() {
        assert!(!Expression::KeyValue {
            key: "key".into(),
            value: "val".into()
        }
        .evaluate(&MockResolver::default().with_key_value("key", "yayeet"))
        .unwrap())
    }

    #[test]
    fn eval_and() {
        assert!(Expression::parse("a && b")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("a").with_tag("b"))
            .unwrap())
    }

    #[test]
    fn eval_and_nomatch() {
        assert!(!Expression::parse("a && b")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("a").with_tag("c"))
            .unwrap())
    }

    #[test]
    fn eval_or() {
        assert!(Expression::parse("a || b")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("b"))
            .unwrap())
    }

    #[test]
    fn eval_or_nomatch() {
        assert!(!Expression::parse("a || b")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("c"))
            .unwrap())
    }

    #[test]
    fn eval_not() {
        assert!(Expression::parse("!a")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("b"))
            .unwrap())
    }

    #[test]
    fn eval_not_nomatch() {
        assert!(!Expression::parse("!a")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("a"))
            .unwrap())
    }

    #[test]
    fn eval_parent() {
        assert!(
            Expression::Parent { parent: "p".into() } // There's no query syntax for parent queries _yet_.
                .evaluate(&MockResolver::default().with_parent("p"))
                .unwrap()
        )
    }

    #[test]
    fn eval_parent_nomatch() {
        assert!(!Expression::Parent { parent: "p".into() }
            .evaluate(&MockResolver::default().with_parent("3"))
            .unwrap())
    }

    #[test]
    fn eval_and_or_nested() {
        assert!(Expression::parse("(a || b) && c")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("a").with_tag("c"))
            .unwrap())
    }

    #[test]
    fn eval_not_nested() {
        assert!(Expression::parse("!(a && b) && !(!c)")
            .unwrap()
            .evaluate(&MockResolver::default().with_tag("a").with_tag("c"))
            .unwrap())
    }
}