ooroo 0.2.0

A fast, compiled rule engine with a text-based DSL
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
use std::fmt;
use std::ops::Not;

use super::Value;

/// Comparison operators supported in rule expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    /// Equal (`==`).
    Eq,
    /// Not equal (`!=`).
    Neq,
    /// Greater than (`>`).
    Gt,
    /// Greater than or equal (`>=`).
    Gte,
    /// Less than (`<`).
    Lt,
    /// Less than or equal (`<=`).
    Lte,
}

/// User-facing expression AST. Field paths and rule names are strings.
/// Transformed into a compiled representation during compilation.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// A field comparison (e.g., `user.age >= 18`).
    Compare {
        /// Dot-separated field path.
        field: String,
        /// The comparison operator.
        op: CompareOp,
        /// The value to compare against.
        value: Value,
    },
    /// Logical AND of two expressions.
    And(Box<Expr>, Box<Expr>),
    /// Logical OR of two expressions.
    Or(Box<Expr>, Box<Expr>),
    /// Logical NOT of an expression.
    Not(Box<Expr>),
    /// A reference to another rule by name.
    RuleRef(String),
    /// Membership test: field value must be in the given list.
    In {
        /// Dot-separated field path.
        field: String,
        /// Candidate values.
        values: Vec<Value>,
    },
    /// Negated membership test: field value must not be in the given list.
    NotIn {
        /// Dot-separated field path.
        field: String,
        /// Candidate values.
        values: Vec<Value>,
    },
    /// Range test: field value must be between low and high (inclusive).
    Between {
        /// Dot-separated field path.
        field: String,
        /// Lower bound (inclusive).
        low: Value,
        /// Upper bound (inclusive).
        high: Value,
    },
    /// SQL LIKE pattern match (`%` = any sequence, `_` = one character).
    Like {
        /// Dot-separated field path.
        field: String,
        /// The LIKE pattern.
        pattern: String,
    },
    /// Negated SQL LIKE pattern match.
    NotLike {
        /// Dot-separated field path.
        field: String,
        /// The LIKE pattern.
        pattern: String,
    },
    /// True when the field is absent or has no value.
    IsNull(String),
    /// True when the field is present and has a value.
    IsNotNull(String),
}

/// Compiled expression with all string lookups resolved to integer indices.
/// Field paths are resolved via the [`FieldRegistry`](super::FieldRegistry) and rule
/// references are resolved to their topological sort index.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum CompiledExpr {
    Compare {
        field_index: usize,
        op: CompareOp,
        value: Value,
    },
    And(Box<CompiledExpr>, Box<CompiledExpr>),
    Or(Box<CompiledExpr>, Box<CompiledExpr>),
    Not(Box<CompiledExpr>),
    RuleRef(usize),
    In {
        field_index: usize,
        values: Vec<Value>,
    },
    NotIn {
        field_index: usize,
        values: Vec<Value>,
    },
    Between {
        field_index: usize,
        low: Value,
        high: Value,
    },
    Like {
        field_index: usize,
        pattern: String,
    },
    NotLike {
        field_index: usize,
        pattern: String,
    },
    IsNull(usize),
    IsNotNull(usize),
}

impl fmt::Display for CompareOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CompareOp::Eq => write!(f, "=="),
            CompareOp::Neq => write!(f, "!="),
            CompareOp::Gt => write!(f, ">"),
            CompareOp::Gte => write!(f, ">="),
            CompareOp::Lt => write!(f, "<"),
            CompareOp::Lte => write!(f, "<="),
        }
    }
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expr::Compare { field, op, value } => write!(f, "({field} {op} {value})"),
            Expr::And(a, b) => write!(f, "({a} AND {b})"),
            Expr::Or(a, b) => write!(f, "({a} OR {b})"),
            Expr::Not(inner) => write!(f, "(NOT {inner})"),
            Expr::RuleRef(name) => write!(f, "{name}"),
            Expr::In { field, values } => {
                let vals: Vec<String> = values.iter().map(ToString::to_string).collect();
                write!(f, "({field} IN [{}])", vals.join(", "))
            }
            Expr::NotIn { field, values } => {
                let vals: Vec<String> = values.iter().map(ToString::to_string).collect();
                write!(f, "({field} NOT IN [{}])", vals.join(", "))
            }
            Expr::Between { field, low, high } => {
                write!(f, "({field} BETWEEN {low} AND {high})")
            }
            Expr::Like { field, pattern } => write!(f, "({field} LIKE \"{pattern}\")"),
            Expr::NotLike { field, pattern } => write!(f, "({field} NOT LIKE \"{pattern}\")"),
            Expr::IsNull(field) => write!(f, "({field} IS NULL)"),
            Expr::IsNotNull(field) => write!(f, "({field} IS NOT NULL)"),
        }
    }
}

impl Expr {
    /// Combine two expressions with logical AND.
    #[must_use]
    pub fn and(self, other: Expr) -> Expr {
        Expr::And(Box::new(self), Box::new(other))
    }

    /// Combine two expressions with logical OR.
    #[must_use]
    pub fn or(self, other: Expr) -> Expr {
        Expr::Or(Box::new(self), Box::new(other))
    }
}

impl Not for Expr {
    type Output = Expr;

    fn not(self) -> Expr {
        Expr::Not(Box::new(self))
    }
}

/// Intermediate builder for field comparison expressions.
/// Created by [`field()`]; requires a comparison method to produce a valid [`Expr`].
#[derive(Debug, Clone)]
pub struct FieldExpr {
    path: String,
}

impl FieldExpr {
    /// Build an equality comparison (`==`).
    #[must_use]
    pub fn eq(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Eq,
            value: value.into(),
        }
    }

    /// Build a not-equal comparison (`!=`).
    #[must_use]
    pub fn neq(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Neq,
            value: value.into(),
        }
    }

    /// Build a greater-than comparison (`>`).
    #[must_use]
    pub fn gt(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Gt,
            value: value.into(),
        }
    }

    /// Build a greater-than-or-equal comparison (`>=`).
    #[must_use]
    pub fn gte(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Gte,
            value: value.into(),
        }
    }

    /// Build a less-than comparison (`<`).
    #[must_use]
    pub fn lt(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Lt,
            value: value.into(),
        }
    }

    /// Build a less-than-or-equal comparison (`<=`).
    #[must_use]
    pub fn lte(self, value: impl Into<Value>) -> Expr {
        Expr::Compare {
            field: self.path,
            op: CompareOp::Lte,
            value: value.into(),
        }
    }

    /// Build an `IN` membership test.
    #[must_use]
    pub fn is_in<I, V>(self, values: I) -> Expr
    where
        I: IntoIterator<Item = V>,
        V: Into<Value>,
    {
        Expr::In {
            field: self.path,
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// Build a `NOT IN` membership test.
    #[must_use]
    pub fn not_in<I, V>(self, values: I) -> Expr
    where
        I: IntoIterator<Item = V>,
        V: Into<Value>,
    {
        Expr::NotIn {
            field: self.path,
            values: values.into_iter().map(Into::into).collect(),
        }
    }

    /// Build a `BETWEEN` range test (inclusive on both ends).
    #[must_use]
    pub fn between(self, low: impl Into<Value>, high: impl Into<Value>) -> Expr {
        Expr::Between {
            field: self.path,
            low: low.into(),
            high: high.into(),
        }
    }

    /// Build a `LIKE` pattern match.
    #[must_use]
    pub fn like(self, pattern: impl Into<String>) -> Expr {
        Expr::Like {
            field: self.path,
            pattern: pattern.into(),
        }
    }

    /// Build a `NOT LIKE` pattern match.
    #[must_use]
    pub fn not_like(self, pattern: impl Into<String>) -> Expr {
        Expr::NotLike {
            field: self.path,
            pattern: pattern.into(),
        }
    }

    /// Build an `IS NULL` test (true when field is absent).
    #[must_use]
    pub fn is_null(self) -> Expr {
        Expr::IsNull(self.path)
    }

    /// Build an `IS NOT NULL` test (true when field is present).
    #[must_use]
    pub fn is_not_null(self) -> Expr {
        Expr::IsNotNull(self.path)
    }
}

/// Create a [`FieldExpr`] for building field comparison expressions.
#[must_use]
pub fn field(path: &str) -> FieldExpr {
    FieldExpr {
        path: path.to_owned(),
    }
}

/// Create an [`Expr`] that references another rule by name.
#[must_use]
pub fn rule_ref(name: &str) -> Expr {
    Expr::RuleRef(name.to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Value;

    #[test]
    fn field_eq_i64() {
        let expr = field("user.age").eq(18_i64);
        assert_eq!(
            expr,
            Expr::Compare {
                field: "user.age".to_owned(),
                op: CompareOp::Eq,
                value: Value::Int(18),
            }
        );
    }

    #[test]
    fn field_gte_with_into() {
        let expr = field("score").gte(90_i64);
        assert_eq!(
            expr,
            Expr::Compare {
                field: "score".to_owned(),
                op: CompareOp::Gte,
                value: Value::Int(90),
            }
        );
    }

    #[test]
    fn field_eq_str() {
        let expr = field("status").eq("active");
        assert_eq!(
            expr,
            Expr::Compare {
                field: "status".to_owned(),
                op: CompareOp::Eq,
                value: Value::String("active".to_owned()),
            }
        );
    }

    #[test]
    fn rule_ref_creates_expr() {
        let expr = rule_ref("some_rule");
        assert_eq!(expr, Expr::RuleRef("some_rule".to_owned()));
    }

    #[test]
    fn and_chaining() {
        let expr = rule_ref("a").and(rule_ref("b"));
        assert_eq!(
            expr,
            Expr::And(
                Box::new(Expr::RuleRef("a".to_owned())),
                Box::new(Expr::RuleRef("b".to_owned())),
            )
        );
    }

    #[test]
    fn or_chaining() {
        let expr = field("x").eq(1_i64).or(field("y").eq(2_i64));
        match expr {
            Expr::Or(_, _) => {}
            other => panic!("expected Or, got {other:?}"),
        }
    }

    #[test]
    fn not_expr() {
        let expr = !field("banned").eq(true);
        match expr {
            Expr::Not(_) => {}
            other => panic!("expected Not, got {other:?}"),
        }
    }

    #[test]
    fn complex_expression_tree() {
        let expr = rule_ref("eligible_age")
            .and(rule_ref("active_account"))
            .and(rule_ref("not_restricted"));

        // Left-associative: And(And(eligible_age, active_account), not_restricted)
        match &expr {
            Expr::And(left, right) => {
                assert_eq!(**right, Expr::RuleRef("not_restricted".to_owned()));
                match left.as_ref() {
                    Expr::And(ll, lr) => {
                        assert_eq!(**ll, Expr::RuleRef("eligible_age".to_owned()));
                        assert_eq!(**lr, Expr::RuleRef("active_account".to_owned()));
                    }
                    other => panic!("expected inner And, got {other:?}"),
                }
            }
            other => panic!("expected outer And, got {other:?}"),
        }
    }

    #[test]
    fn field_is_in() {
        let expr = field("country").is_in(["US", "CA", "GB"]);
        assert_eq!(
            expr,
            Expr::In {
                field: "country".to_owned(),
                values: vec![
                    Value::String("US".to_owned()),
                    Value::String("CA".to_owned()),
                    Value::String("GB".to_owned()),
                ],
            }
        );
    }

    #[test]
    fn field_not_in() {
        let expr = field("status").not_in(["banned", "suspended"]);
        assert_eq!(
            expr,
            Expr::NotIn {
                field: "status".to_owned(),
                values: vec![
                    Value::String("banned".to_owned()),
                    Value::String("suspended".to_owned()),
                ],
            }
        );
    }

    #[test]
    fn field_between() {
        let expr = field("age").between(18_i64, 65_i64);
        assert_eq!(
            expr,
            Expr::Between {
                field: "age".to_owned(),
                low: Value::Int(18),
                high: Value::Int(65),
            }
        );
    }

    #[test]
    fn field_like() {
        let expr = field("email").like("%@gmail.com");
        assert_eq!(
            expr,
            Expr::Like {
                field: "email".to_owned(),
                pattern: "%@gmail.com".to_owned(),
            }
        );
    }

    #[test]
    fn field_not_like() {
        let expr = field("email").not_like("%@test.%");
        assert_eq!(
            expr,
            Expr::NotLike {
                field: "email".to_owned(),
                pattern: "%@test.%".to_owned(),
            }
        );
    }

    #[test]
    fn field_is_null() {
        let expr = field("middle_name").is_null();
        assert_eq!(expr, Expr::IsNull("middle_name".to_owned()));
    }

    #[test]
    fn field_is_not_null() {
        let expr = field("middle_name").is_not_null();
        assert_eq!(expr, Expr::IsNotNull("middle_name".to_owned()));
    }

    #[test]
    fn all_compare_ops() {
        let ops = vec![
            (field("f").eq(1_i64), CompareOp::Eq),
            (field("f").neq(1_i64), CompareOp::Neq),
            (field("f").gt(1_i64), CompareOp::Gt),
            (field("f").gte(1_i64), CompareOp::Gte),
            (field("f").lt(1_i64), CompareOp::Lt),
            (field("f").lte(1_i64), CompareOp::Lte),
        ];
        for (expr, expected_op) in ops {
            match expr {
                Expr::Compare { op, .. } => assert_eq!(op, expected_op),
                other => panic!("expected Compare, got {other:?}"),
            }
        }
    }
}