whereexpr 0.1.1

A fast, expressive rule-based filtering engine for Rust that evaluates boolean expressions over any data structure
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use super::Attributes;
use super::CompiledCondition;
use super::Condition;
use super::ConditionAttribute;
use super::ConditionList;
use super::ConditionPredicate;
use super::Error;
use std::marker::PhantomData;

#[derive(Debug, PartialEq, Eq)]
pub(super) enum Composition {
    And,
    Or,
}

#[derive(Debug, PartialEq, Eq)]
pub(super) enum EvaluationNode {
    Condition(u16),
    Group {
        composition: Composition,
        negated: bool,
        children: Vec<EvaluationNode>,
    },
}

impl EvaluationNode {
    pub(super) fn evaluate<T: Attributes>(&self, obj: &T, expression: &Expression) -> Option<bool> {
        match self {
            EvaluationNode::Condition(index) => expression.conditions.get(*index).unwrap().evaluate(obj),
            EvaluationNode::Group {
                composition,
                negated,
                children,
            } => {
                let result = match composition {
                    Composition::And => {
                        let mut result = true;
                        for child in children {
                            match child.evaluate(obj, expression) {
                                Some(v) => {
                                    result &= v;
                                    if !result {
                                        break;
                                    }
                                }
                                None => return None,
                            }
                        }
                        result
                    }
                    Composition::Or => {
                        let mut result = false;
                        for child in children {
                            match child.evaluate(obj, expression) {
                                Some(v) => {
                                    result |= v;
                                    if result {
                                        break;
                                    }
                                }
                                None => return None,
                            }
                        }
                        result
                    }
                };
                if *negated {
                    Some(!result)
                } else {
                    Some(result)
                }
            }
        }
    }
}

/// A compiled, type-safe boolean expression that can be evaluated against objects
/// implementing [`Attributes`].
///
/// An `Expression` is built via [`ExpressionBuilder`] and holds a set of named conditions
/// combined by a boolean expression string (e.g. `"cond_a && cond_b || !cond_c"`).
/// It is tied at construction time to a specific type `T`, and will panic (or return
/// `None` with [`try_matches`](Expression::try_matches)) if evaluated against a different type.
pub struct Expression {
    root: EvaluationNode,
    #[cfg(feature = "enable_type_check")]
    type_id: u64,
    #[cfg(feature = "enable_type_check")]
    type_name: &'static str,
    pub(super) conditions: ConditionList,
}

impl Expression {
    /// Evaluates the expression against the given object and returns `true` if it matches.
    ///
    /// # Panics
    ///
    /// Panics if `T` does not match the type the expression was built for. Use
    /// [`try_matches`](Expression::try_matches) for a panic-free alternative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder};
    ///
    /// struct Person { name: String, age: u32 }
    ///
    /// impl Person {
    ///     const NAME: AttributeIndex = AttributeIndex::new(0);
    ///     const AGE:  AttributeIndex = AttributeIndex::new(1);
    /// }
    ///
    /// impl Attributes for Person {
    ///     const TYPE_ID: u64 = 0x517652f2; // unique ID for Person type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Person";
    ///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
    ///         match idx {
    ///             Self::NAME => Some(Value::String(&self.name)),
    ///             Self::AGE  => Some(Value::U32(self.age)),
    ///             _          => None,
    ///         }
    ///     }
    ///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
    ///         match idx {
    ///             Self::NAME => Some(ValueKind::String),
    ///             Self::AGE  => Some(ValueKind::U32),
    ///             _          => None,
    ///         }
    ///     }
    ///     fn index(name: &str) -> Option<AttributeIndex> {
    ///         match name {
    ///             "name" => Some(Self::NAME),
    ///             "age"  => Some(Self::AGE),
    ///             _      => None,
    ///         }
    ///     }
    /// }
    ///
    /// let expr = ExpressionBuilder::<Person>::new()
    ///     .add("is_alice", Condition::from_str("name is Alice"))
    ///     .add("is_adult", Condition::from_str("age >= 18"))
    ///     .build("is_alice && is_adult")
    ///     .unwrap();
    ///
    /// let alice = Person { name: "Alice".into(), age: 30 };
    /// let bob   = Person { name: "Bob".into(),   age: 25 };
    ///
    /// assert!(expr.matches(&alice));
    /// assert!(!expr.matches(&bob));
    /// ```
    #[inline(always)]
    pub fn matches<T: Attributes>(&self, obj: &T) -> bool {
        #[cfg(feature = "enable_type_check")]
        if T::TYPE_ID != self.type_id {
            panic!(
                "object type mismatch (this expression is for type '{}', but the object you are trying to match is of type '{}')",
                self.type_name,
                T::TYPE_NAME
            );
        }
        self.root.evaluate(obj, self).expect("evaluation failed !")
    }

    /// Evaluates the expression against the given object, returning `Some(true/false)` on
    /// success or `None` if the type does not match the one the expression was built for.
    ///
    /// This is the non-panicking counterpart of [`matches`](Expression::matches). It is
    /// useful when working with heterogeneous collections where the concrete type may not
    /// be known ahead of time.
    ///
    /// # Return value
    ///
    /// - `Some(true)`  – the object satisfies the expression.
    /// - `Some(false)` – the object does not satisfy the expression.
    /// - `None`        – `T` is not the type this expression was compiled for.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder};
    ///
    /// struct Score { value: u32 }
    ///
    /// impl Score {
    ///     const VALUE: AttributeIndex = AttributeIndex::new(0);
    /// }
    ///
    /// impl Attributes for Score {
    ///     const TYPE_ID: u64 = 0x517652f2; // unique ID for Score type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Score";
    ///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
    ///         match idx {
    ///             Self::VALUE => Some(Value::U32(self.value)),
    ///             _           => None,
    ///         }
    ///     }
    ///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
    ///         match idx { Self::VALUE => Some(ValueKind::U32), _ => None }
    ///     }
    ///     fn index(name: &str) -> Option<AttributeIndex> {
    ///         match name { "value" => Some(Self::VALUE), _ => None }
    ///     }
    /// }
    ///
    /// let expr = ExpressionBuilder::<Score>::new()
    ///     .add("high", Condition::from_str("value > 90"))
    ///     .build("high")
    ///     .unwrap();
    ///
    /// let s = Score { value: 95 };
    /// assert_eq!(expr.try_matches(&s), Some(true));
    ///
    /// let low = Score { value: 40 };
    /// assert_eq!(expr.try_matches(&low), Some(false));
    /// ```
    #[inline(always)]
    pub fn try_matches<T: Attributes>(&self, obj: &T) -> Option<bool> {
        #[cfg(feature = "enable_type_check")]
        if T::TYPE_ID != self.type_id {
            return None;
        }
        self.root.evaluate(obj, self)
    }
}

/// A builder for constructing a type-safe [`Expression`].
///
/// Use [`ExpressionBuilder::new`] to create a builder, register one or more named
/// [`Condition`]s with [`add`](ExpressionBuilder::add), and then call
/// [`build`](ExpressionBuilder::build) with a boolean expression string that
/// combines those condition names.
///
/// # Boolean expression syntax
///
/// The expression string passed to `build` supports:
/// - `&&` / `AND` — logical AND
/// - `||` / `OR`  — logical OR
/// - `!`  / `NOT` — logical negation
/// - `(` `)` — grouping
///
/// Condition names referenced in the expression must exactly match the names
/// provided to [`add`](ExpressionBuilder::add).
///
/// # Example
///
/// ```rust
/// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder};
///
/// struct Person { name: String, age: u32 }
///
/// impl Person {
///     const NAME: AttributeIndex = AttributeIndex::new(0);
///     const AGE:  AttributeIndex = AttributeIndex::new(1);
/// }
///
/// impl Attributes for Person {
///     const TYPE_ID: u64 = 0xffff1201; // unique ID for Person type (a hash or other unique identifier)
///     const TYPE_NAME: &'static str = "Person";
///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
///         match idx {
///             Self::NAME => Some(Value::String(&self.name)),
///             Self::AGE  => Some(Value::U32(self.age)),
///             _          => None,
///         }
///     }
///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
///         match idx {
///             Self::NAME => Some(ValueKind::String),
///             Self::AGE  => Some(ValueKind::U32),
///             _          => None,
///         }
///     }
///     fn index(name: &str) -> Option<AttributeIndex> {
///         match name {
///             "name" => Some(Self::NAME),
///             "age"  => Some(Self::AGE),
///             _      => None,
///         }
///     }
/// }
///
/// let expr = ExpressionBuilder::<Person>::new()
///     .add("is_alice", Condition::from_str("name is Alice"))
///     .add("is_adult", Condition::from_str("age >= 18"))
///     .build("is_alice && is_adult")
///     .unwrap();
/// ```
pub struct ExpressionBuilder<T: Attributes> {
    conditions: Vec<(String, Condition)>,
    _phantom: PhantomData<T>,
}

impl<T: Attributes> ExpressionBuilder<T> {
    /// Creates a new, empty `ExpressionBuilder` for the type `T`.
    ///
    /// At least one condition must be added with [`add`](ExpressionBuilder::add) before
    /// calling [`build`](ExpressionBuilder::build), otherwise `build` will return
    /// [`Error::EmptyConditionList`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, ExpressionBuilder};
    ///
    /// struct Item { price: f64 }
    ///
    /// impl Attributes for Item {
    ///     const TYPE_ID: u64 = 0x1123F78; // unique ID for Item type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Item";
    ///     fn get(&self, _: AttributeIndex) -> Option<Value<'_>> { Some(Value::F64(self.price)) }
    ///     fn kind(_: AttributeIndex) -> Option<ValueKind> { Some(ValueKind::F64) }
    ///     fn index(_: &str) -> Option<AttributeIndex> { Some(AttributeIndex::new(0)) }
    /// }
    ///
    /// let builder = ExpressionBuilder::<Item>::new();
    /// ```
    pub fn new() -> Self {
        Self {
            conditions: Vec::with_capacity(4),
            _phantom: PhantomData,
        }
    }

    /// Registers a named condition with this builder.
    ///
    /// The `name` is used to reference the condition in the boolean expression string
    /// passed to [`build`](ExpressionBuilder::build). Names must:
    /// - Be non-empty.
    /// - Start with an ASCII letter (`a-z`, `A-Z`).
    /// - Contain only ASCII letters, digits, `-`, or `_` after the first character.
    ///
    /// If these rules are violated, `build` will return [`Error::InvalidConditionName`].
    /// Registering the same name twice causes `build` to return
    /// [`Error::DuplicateConditionName`].
    ///
    /// This method consumes and returns `self`, enabling a fluent builder chain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder};
    ///
    /// struct Product { category: String, price: f64 }
    ///
    /// impl Product {
    ///     const CATEGORY: AttributeIndex = AttributeIndex::new(0);
    ///     const PRICE:    AttributeIndex = AttributeIndex::new(1);
    /// }
    ///
    /// impl Attributes for Product {
    ///     const TYPE_ID: u64 = 0x12345678; // unique ID for Product type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Product";
    ///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
    ///         match idx {
    ///             Self::CATEGORY => Some(Value::String(&self.category)),
    ///             Self::PRICE    => Some(Value::F64(self.price)),
    ///             _              => None,
    ///         }
    ///     }
    ///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
    ///         match idx {
    ///             Self::CATEGORY => Some(ValueKind::String),
    ///             Self::PRICE    => Some(ValueKind::F64),
    ///             _              => None,
    ///         }
    ///     }
    ///     fn index(name: &str) -> Option<AttributeIndex> {
    ///         match name {
    ///             "category" => Some(Self::CATEGORY),
    ///             "price"    => Some(Self::PRICE),
    ///             _          => None,
    ///         }
    ///     }
    /// }
    ///
    /// let expr = ExpressionBuilder::<Product>::new()
    ///     .add("is_book",      Condition::from_str("category is book"))
    ///     .add("is_expensive", Condition::from_str("price > 50"))
    ///     .build("is_book && is_expensive")
    ///     .unwrap();
    /// ```
    pub fn add(mut self, name: &str, condition: Condition) -> Self {
        self.conditions.push((name.to_string(), condition));
        self
    }

    /// Compiles all registered conditions and the boolean expression string into a
    /// reusable [`Expression`].
    ///
    /// # Parameters
    ///
    /// - `expr` – A boolean expression string combining the named conditions registered
    ///   via [`add`](ExpressionBuilder::add). Supported operators: `&&`/`AND`,
    ///   `||`/`OR`, `!`/`NOT`, and parentheses for grouping.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if any of the following occur:
    ///
    /// | Error variant | Cause |
    /// |---|---|
    /// | [`Error::EmptyConditionList`] | No conditions were added before calling `build`. |
    /// | [`Error::InvalidConditionName`] | A condition name violates naming rules. |
    /// | [`Error::DuplicateConditionName`] | The same name was registered more than once. |
    /// | [`Error::UnknownAttribute`] | A condition references an attribute name not exposed by `T`. |
    /// | [`Error::UnknownConditionName`] | The expression string references a name not registered via `add`. |
    /// | parse errors | The expression string or a condition string is malformed. |
    ///
    /// # Examples
    ///
    /// Basic usage with `Condition::from_str` (attribute resolved from the string):
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder};
    ///
    /// struct Person { name: String, age: u32 }
    ///
    /// impl Person {
    ///     const NAME: AttributeIndex = AttributeIndex::new(0);
    ///     const AGE:  AttributeIndex = AttributeIndex::new(1);
    /// }
    ///
    /// impl Attributes for Person {
    ///     const TYPE_ID: u64 = 0xC2DF0123; // unique ID for Person type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Person";
    ///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
    ///         match idx {
    ///             Self::NAME => Some(Value::String(&self.name)),
    ///             Self::AGE  => Some(Value::U32(self.age)),
    ///             _          => None,
    ///         }
    ///     }
    ///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
    ///         match idx {
    ///             Self::NAME => Some(ValueKind::String),
    ///             Self::AGE  => Some(ValueKind::U32),
    ///             _          => None,
    ///         }
    ///     }
    ///     fn index(name: &str) -> Option<AttributeIndex> {
    ///         match name {
    ///             "name" => Some(Self::NAME),
    ///             "age"  => Some(Self::AGE),
    ///             _      => None,
    ///         }
    ///     }
    /// }
    ///
    /// // Matches people named "John" or "Jane" who are older than 25
    /// let expr = ExpressionBuilder::<Person>::new()
    ///     .add("named", Condition::from_str("name is-one-of [John, Jane]"))
    ///     .add("older", Condition::from_str("age > 25"))
    ///     .build("named && older")
    ///     .unwrap();
    ///
    /// let john = Person { name: "John".into(), age: 30 };
    /// assert!(expr.matches(&john));
    ///
    /// // With negation and grouping
    /// let expr2 = ExpressionBuilder::<Person>::new()
    ///     .add("is_john",  Condition::from_str("name is John"))
    ///     .add("is_young", Condition::from_str("age < 18"))
    ///     .build("is_john && !is_young")
    ///     .unwrap();
    ///
    /// assert!(expr2.matches(&john));
    /// ```
    ///
    /// Handling build errors:
    ///
    /// ```rust
    /// use whereexpr::{Attributes, AttributeIndex, Value, ValueKind, Condition, ExpressionBuilder, Error};
    ///
    /// struct Item { name: String }
    ///
    /// impl Item {
    ///     const NAME: AttributeIndex = AttributeIndex::new(0);
    /// }
    ///
    /// impl Attributes for Item {
    ///     const TYPE_ID: u64 = 0x517652f2; // unique ID for Item type (a hash or other unique identifier)
    ///     const TYPE_NAME: &'static str = "Item";
    ///     fn get(&self, idx: AttributeIndex) -> Option<Value<'_>> {
    ///         match idx { Self::NAME => Some(Value::String(&self.name)), _ => None }
    ///     }
    ///     fn kind(idx: AttributeIndex) -> Option<ValueKind> {
    ///         match idx { Self::NAME => Some(ValueKind::String), _ => None }
    ///     }
    ///     fn index(name: &str) -> Option<AttributeIndex> {
    ///         match name { "name" => Some(Self::NAME), _ => None }
    ///     }
    /// }
    ///
    /// // Referencing an unknown condition name in the expression string
    /// let result = ExpressionBuilder::<Item>::new()
    ///     .add("named", Condition::from_str("name is Widget"))
    ///     .build("named && typo_name");
    ///
    /// assert!(matches!(result, Err(Error::UnknownConditionName(..))));
    /// ```
    pub fn build(self, expr: &str) -> Result<Expression, Error> {
        // build the conditions list
        if self.conditions.is_empty() {
            return Err(Error::EmptyConditionList);
        }
        let mut clist = ConditionList::with_capacity(self.conditions.len());
        for (name, condition) in self.conditions {
            if !Self::is_valid_name(&name) {
                return Err(Error::InvalidConditionName(name));
            }
            let attr_index = match condition.attribute {
                ConditionAttribute::Name(attr_name) => T::index(&attr_name).ok_or(Error::UnknownAttribute(attr_name, name.clone()))?,
                ConditionAttribute::Index(index) => index,
            };
            let (attr_index, predicate) = match condition.predicate {
                ConditionPredicate::Resolved(p) => (attr_index, p),
                ConditionPredicate::Error(e) => return Err(e),
                ConditionPredicate::Raw(expr) => Condition::parse::<T>(&expr, &name)?,
            };
            let compiled_condition = CompiledCondition::new(attr_index, predicate);
            if !clist.add(&name, compiled_condition) {
                return Err(Error::DuplicateConditionName(name));
            }
        }
        let evaluation_node = crate::expr_parser::parse(expr, &clist)?;
        Ok(Expression {
            #[cfg(feature = "enable_type_check")]
            type_id: T::TYPE_ID,
            #[cfg(feature = "enable_type_check")]
            type_name: T::TYPE_NAME,
            root: evaluation_node,
            conditions: clist,
        })
    }

    fn is_valid_name(name: &str) -> bool {
        if name.is_empty() {
            return false;
        }
        let mut first = true;
        for c in name.chars() {
            if first {
                if !c.is_ascii_alphabetic() {
                    return false;
                }
                first = false;
            } else if !c.is_ascii_alphanumeric() && c != '_' && c != '-' {
                return false;
            }
        }
        true
    }
}