wirerust 0.1.0

A modular, embeddable filter engine for structured data
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Expression (AST) module: defines the parsed representation of filter expressions.
//!
//! This module provides the FilterExpr type and related AST node types.

use crate::schema::FilterSchema;
use crate::types::LiteralValue;
use crate::WirerustError;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum FilterExpr {
    LogicalOp {
        op: LogicalOp,
        left: Box<FilterExpr>,
        right: Box<FilterExpr>,
    },
    Comparison {
        left: Box<FilterExpr>,
        op: ComparisonOp,
        right: Box<FilterExpr>,
    },
    Not(Box<FilterExpr>),
    Value(LiteralValue),
    FunctionCall {
        name: String,
        args: Vec<FilterExpr>,
    },
    List(Vec<LiteralValue>),
    // TODO: Add more as needed
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum LogicalOp {
    And,
    Or,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ComparisonOp {
    Eq,
    Neq,
    Lt,
    Lte,
    Gt,
    Gte,
    In,
    NotIn,
    Matches,        // for regex
    Wildcard,       // case-insensitive wildcard
    StrictWildcard, // case-sensitive wildcard
    Contains,       // substring or element containment
}

// Visitor trait for traversing the AST
pub trait ExprVisitor {
    fn visit(&mut self, expr: &FilterExpr);
}

// Hand-written recursive descent parser for filter expressions
pub struct FilterParser<'a> {
    input: &'a str,
    pos: usize,
}

impl<'a> FilterParser<'a> {
    pub fn new(input: &'a str, _schema: &'a FilterSchema) -> Self {
        Self { input, pos: 0 }
    }

    pub fn parse(input: &str, schema: &FilterSchema) -> Result<FilterExpr, WirerustError> {
        let mut parser = FilterParser::new(input, schema);
        let expr = parser.parse_expr().map_err(|e| {
            WirerustError::ParseError(format!(
                "Failed to parse expression at position {}: {e}",
                parser.pos
            ))
        })?;
        parser.skip_whitespace();
        if parser.pos < parser.input.len() {
            return Err(WirerustError::ParseError(format!(
                "Unexpected input at position {}",
                parser.pos
            )));
        }
        Ok(expr)
    }

    fn parse_expr(&mut self) -> Result<FilterExpr, WirerustError> {
        self.parse_or()
    }

    fn parse_or(&mut self) -> Result<FilterExpr, WirerustError> {
        self.skip_whitespace();
        let mut left = self.parse_and()?;
        loop {
            self.skip_whitespace();
            if self.consume("||") || self.consume("or") {
                self.skip_whitespace();
                let right = {
                    self.skip_whitespace();
                    self.parse_and()?
                };
                left = FilterExpr::LogicalOp {
                    op: LogicalOp::Or,
                    left: Box::new(left),
                    right: Box::new(right),
                };
            } else {
                break;
            }
        }
        Ok(left)
    }

    fn parse_and(&mut self) -> Result<FilterExpr, WirerustError> {
        self.skip_whitespace();
        let mut left = self.parse_not()?;
        loop {
            self.skip_whitespace();
            if self.consume("&&") || self.consume("and") {
                self.skip_whitespace();
                let right = {
                    self.skip_whitespace();
                    self.parse_not()?
                };
                left = FilterExpr::LogicalOp {
                    op: LogicalOp::And,
                    left: Box::new(left),
                    right: Box::new(right),
                };
            } else {
                break;
            }
        }
        Ok(left)
    }

    fn parse_not(&mut self) -> Result<FilterExpr, WirerustError> {
        self.skip_whitespace();
        if self.consume("not") {
            let expr = self.parse_not()?;
            Ok(FilterExpr::Not(Box::new(expr)))
        } else {
            self.parse_comparison()
        }
    }

    fn parse_expr_or_value(&mut self) -> Result<FilterExpr, WirerustError> {
        self.skip_whitespace();
        // Try to parse as a literal first, then as an identifier, then as a full expression
        let start_pos = self.pos;

        // Try literal first (most specific)
        if let Ok(lit) = self.parse_literal() {
            return Ok(FilterExpr::Value(lit));
        }
        self.pos = start_pos;

        // Try identifier (field reference)
        if let Ok(ident) = self.parse_identifier() {
            return Ok(FilterExpr::Value(LiteralValue::Bytes(
                ident.into_bytes().into(),
            )));
        }
        self.pos = start_pos;

        // Try full expression last (least specific)
        if let Ok(expr) = self.parse_expr() {
            return Ok(expr);
        }

        Err(WirerustError::ParseError(format!(
            "Expected expression or value at position {}",
            self.pos
        )))
    }

    fn parse_comparison(&mut self) -> Result<FilterExpr, WirerustError> {
        self.skip_whitespace();
        // Parse primary expression: identifier, function call, or parenthesized expression
        let left = if self.peek() == Some('(') {
            self.consume_char();
            let inner = self.parse_expr()?;
            self.skip_whitespace();
            if !self.consume(")") {
                return Err(WirerustError::ParseError(format!(
                    "Expected ')' at position {}",
                    self.pos
                )));
            }
            inner
        } else {
            // Parse identifier or function call
            let ident = self.parse_identifier()?;
            self.skip_whitespace();
            if self.peek() == Some('(') {
                // Function call
                self.consume_char();
                let mut args = Vec::new();
                self.skip_whitespace();
                if self.peek() != Some(')') {
                    loop {
                        // Try to parse as a simple field reference first, then as a full expression
                        let start_pos = self.pos;
                        let arg = if let Ok(ident) = self.parse_identifier() {
                            // Simple field reference
                            FilterExpr::Value(LiteralValue::Bytes(ident.into_bytes().into()))
                        } else {
                            // Reset and try as full expression
                            self.pos = start_pos;
                            self.parse_expr_or_value()?
                        };
                        args.push(arg);
                        self.skip_whitespace();
                        if self.peek() == Some(',') {
                            self.consume_char();
                            self.skip_whitespace();
                        } else {
                            break;
                        }
                    }
                }
                if !self.consume(")") {
                    return Err(WirerustError::ParseError(format!(
                        "Expected ')' after function call at position {}",
                        self.pos
                    )));
                }
                FilterExpr::FunctionCall { name: ident, args }
            } else if ident == "{" {
                let list = self.parse_list_literal()?;
                FilterExpr::List(list)
            } else {
                // Just an identifier (field reference)
                FilterExpr::Value(LiteralValue::Bytes(ident.into_bytes().into()))
            }
        };
        self.skip_whitespace();
        // Check for comparison operator
        if let Ok((op, _op_str)) = self.parse_operator() {
            self.skip_whitespace();
            let right = if self.peek() == Some('{') {
                // List/set literal as value
                let list = self.parse_list_literal()?;
                self.skip_whitespace();
                FilterExpr::Value(LiteralValue::Array(list.into()))
            } else {
                // Try to parse as a full expression or value
                self.parse_expr_or_value()?
            };
            Ok(FilterExpr::Comparison {
                left: Box::new(left),
                op,
                right: Box::new(right),
            })
        } else {
            Ok(left)
        }
    }

    fn parse_identifier(&mut self) -> Result<String, WirerustError> {
        self.skip_whitespace();
        let start = self.pos;
        let mut end = self.pos;
        for (i, c) in self.input[self.pos..].char_indices() {
            if c.is_alphanumeric() || c == '_' || c == '.' {
                end = self.pos + i + c.len_utf8();
            } else {
                break;
            }
        }
        if end > start {
            let ident = &self.input[start..end];
            self.pos = end;
            Ok(ident.to_string())
        } else {
            Err(WirerustError::ParseError(format!(
                "Expected identifier at position {}",
                self.pos
            )))
        }
    }

    fn parse_operator(&mut self) -> Result<(ComparisonOp, &'static str), WirerustError> {
        let ops = [
            ("==", ComparisonOp::Eq),
            ("eq", ComparisonOp::Eq),
            ("!=", ComparisonOp::Neq),
            ("ne", ComparisonOp::Neq),
            ("<=", ComparisonOp::Lte),
            ("le", ComparisonOp::Lte),
            (">=", ComparisonOp::Gte),
            ("ge", ComparisonOp::Gte),
            ("<", ComparisonOp::Lt),
            ("lt", ComparisonOp::Lt),
            (">", ComparisonOp::Gt),
            ("gt", ComparisonOp::Gt),
            ("in", ComparisonOp::In),
            ("not in", ComparisonOp::NotIn),
            ("matches", ComparisonOp::Matches),
            ("wildcard", ComparisonOp::Wildcard),
            ("strict wildcard", ComparisonOp::StrictWildcard),
            ("contains", ComparisonOp::Contains),
        ];
        self.skip_whitespace();
        for (s, op) in ops.iter() {
            if self.input[self.pos..].starts_with(s) {
                self.pos += s.len();
                return Ok((*op, *s));
            }
        }
        Err(WirerustError::ParseError(format!(
            "Expected operator at position {}",
            self.pos
        )))
    }

    fn parse_literal(&mut self) -> Result<LiteralValue, WirerustError> {
        self.skip_whitespace();
        if let Some(c) = self.peek() {
            if c == '"' {
                return self.parse_string_literal();
            } else if c.is_ascii_digit() || c == '-' {
                return self.parse_int_literal();
            } else if self.input[self.pos..].starts_with("true") {
                self.pos += 4;
                return Ok(LiteralValue::Bool(true));
            } else if self.input[self.pos..].starts_with("false") {
                self.pos += 5;
                return Ok(LiteralValue::Bool(false));
            }
        }
        Err(WirerustError::ParseError(format!(
            "Expected literal at position {}",
            self.pos
        )))
    }

    fn parse_string_literal(&mut self) -> Result<LiteralValue, WirerustError> {
        self.skip_whitespace();
        if self.peek() != Some('"') {
            return Err(WirerustError::ParseError(format!(
                "Expected \" at position {}",
                self.pos
            )));
        }
        self.consume_char(); // consume opening quote
        let start = self.pos;
        let mut end = self.pos;
        while let Some(c) = self.peek() {
            if c == '"' {
                break;
            }
            self.consume_char();
            end = self.pos;
        }
        if self.peek() != Some('"') {
            return Err(WirerustError::ParseError(format!(
                "Unterminated string literal at position {}",
                self.pos
            )));
        }
        let s = &self.input[start..end];
        self.consume_char(); // consume closing quote
        Ok(LiteralValue::Bytes(s.as_bytes().to_vec().into()))
    }

    fn parse_int_literal(&mut self) -> Result<LiteralValue, WirerustError> {
        self.skip_whitespace();
        let start = self.pos;
        if self.peek() == Some('-') {
            self.consume_char();
        }
        while let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                self.consume_char();
            } else {
                break;
            }
        }
        if self.pos > start {
            let s = &self.input[start..self.pos];
            match s.parse::<i64>() {
                Ok(n) => Ok(LiteralValue::Int(n)),
                Err(_) => Err(WirerustError::ParseError(format!(
                    "Invalid integer literal at position {start}"
                ))),
            }
        } else {
            Err(WirerustError::ParseError(format!(
                "Expected integer literal at position {}",
                self.pos
            )))
        }
    }

    fn parse_list_literal(&mut self) -> Result<Vec<LiteralValue>, WirerustError> {
        if !self.consume("{") {
            return Err(WirerustError::ParseError(format!(
                "Expected '{{' at position {}",
                self.pos
            )));
        }
        let mut items = Vec::new();
        loop {
            self.skip_whitespace();
            if self.peek() == Some('}') {
                self.consume_char();
                break;
            }
            let item = self.parse_literal()?;
            items.push(item);
            self.skip_whitespace();
            // Accept either whitespace or comma as separator, but do not require comma
            // If next is '}', break, else continue
        }
        Ok(items)
    }

    fn skip_whitespace(&mut self) {
        while let Some(c) = self.peek() {
            if c.is_whitespace() {
                self.consume_char();
            } else {
                break;
            }
        }
    }

    fn consume(&mut self, s: &str) -> bool {
        if self.input.as_bytes()[self.pos..].starts_with(s.as_bytes()) {
            self.pos += s.len();
            true
        } else {
            false
        }
    }

    fn consume_char(&mut self) -> Option<char> {
        let mut iter = self.input[self.pos..].char_indices();
        let (offset, ch) = iter.next()?;
        self.pos += offset + ch.len_utf8();
        Some(ch)
    }

    fn peek(&self) -> Option<char> {
        self.input[self.pos..].chars().next()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::FilterSchemaBuilder;
    use crate::types::FieldType;

    fn schema() -> FilterSchema {
        FilterSchemaBuilder::new()
            .field("foo", FieldType::Int)
            .field("bar", FieldType::Bytes)
            .build()
    }

    #[test]
    fn test_parse_comparison() {
        let expr = FilterParser::parse("foo == 42", &schema()).unwrap();
        match expr {
            FilterExpr::Comparison { left, op, right } => {
                assert_eq!(
                    *left,
                    FilterExpr::Value(LiteralValue::Bytes(b"foo".to_vec().into()))
                );
                assert_eq!(op, ComparisonOp::Eq);
                assert_eq!(*right, FilterExpr::Value(LiteralValue::Int(42)));
            }
            _ => panic!("Expected comparison expr"),
        }
    }

    #[test]
    fn test_parse_comparison_word_operators() {
        let sch = schema();
        let eq = FilterParser::parse("foo eq 42", &sch).unwrap();
        match eq {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Eq),
            _ => panic!("Expected eq comparison"),
        }
        let ne = FilterParser::parse("foo ne 42", &sch).unwrap();
        match ne {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Neq),
            _ => panic!("Expected ne comparison"),
        }
        let lt = FilterParser::parse("foo lt 42", &sch).unwrap();
        match lt {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Lt),
            _ => panic!("Expected lt comparison"),
        }
        let le = FilterParser::parse("foo le 42", &sch).unwrap();
        match le {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Lte),
            _ => panic!("Expected le comparison"),
        }
        let gt = FilterParser::parse("foo gt 42", &sch).unwrap();
        match gt {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Gt),
            _ => panic!("Expected gt comparison"),
        }
        let ge = FilterParser::parse("foo ge 42", &sch).unwrap();
        match ge {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Gte),
            _ => panic!("Expected ge comparison"),
        }
    }

    #[test]
    fn test_parse_logical_and() {
        let expr = FilterParser::parse("foo == 1 && bar == \"baz\"", &schema()).unwrap();
        match expr {
            FilterExpr::LogicalOp { op, .. } => assert_eq!(op, LogicalOp::And),
            _ => panic!("Expected logical op"),
        }
        let expr_word = FilterParser::parse("foo == 1 and bar == \"baz\"", &schema()).unwrap();
        match expr_word {
            FilterExpr::LogicalOp { op, .. } => assert_eq!(op, LogicalOp::And),
            _ => panic!("Expected logical op for 'and'"),
        }
    }

    #[test]
    fn test_parse_logical_or() {
        let expr = FilterParser::parse("foo == 1 || bar == \"baz\"", &schema()).unwrap();
        match expr {
            FilterExpr::LogicalOp { op, .. } => assert_eq!(op, LogicalOp::Or),
            _ => panic!("Expected logical op"),
        }
        let expr_word = FilterParser::parse("foo == 1 or bar == \"baz\"", &schema()).unwrap();
        match expr_word {
            FilterExpr::LogicalOp { op, .. } => assert_eq!(op, LogicalOp::Or),
            _ => panic!("Expected logical op for 'or'"),
        }
    }

    #[test]
    fn test_parse_not() {
        let expr = FilterParser::parse("not foo == 0", &schema()).unwrap();
        match expr {
            FilterExpr::Not(inner) => match *inner {
                FilterExpr::Comparison { .. } => {}
                _ => panic!("Expected comparison inside not"),
            },
            _ => panic!("Expected not expr"),
        }
    }

    #[test]
    fn test_parse_parens() {
        let expr =
            FilterParser::parse("(foo == 1 || bar == \"baz\") && foo != 0", &schema()).unwrap();
        match expr {
            FilterExpr::LogicalOp {
                op: LogicalOp::And, ..
            } => {}
            _ => panic!("Expected top-level and"),
        }
    }

    #[test]
    fn test_parse_function_call() {
        let expr = FilterParser::parse("myfunc(foo, 42)", &schema()).unwrap();
        match expr {
            FilterExpr::FunctionCall { name, args } => {
                assert_eq!(name, "myfunc");
                assert_eq!(args.len(), 2);
            }
            _ => panic!("Expected function call expr"),
        }
    }

    #[test]
    fn test_parse_list_literal() {
        let expr = FilterParser::parse("foo in {1 2 3}", &schema()).unwrap();
        match expr {
            FilterExpr::Comparison { op, right, .. } => {
                assert_eq!(op, ComparisonOp::In);
                match *right {
                    FilterExpr::Value(LiteralValue::Array(ref arr)) => {
                        assert_eq!(arr.len(), 3);
                    }
                    _ => panic!("Expected array literal"),
                }
            }
            _ => panic!("Expected comparison expr with list literal"),
        }
    }

    #[test]
    fn test_parse_wildcard_operators() {
        let sch = schema();
        let wc = FilterParser::parse("bar wildcard \"foo*bar\"", &sch).unwrap();
        match wc {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Wildcard),
            _ => panic!("Expected wildcard comparison"),
        }
        let swc = FilterParser::parse("bar strict wildcard \"foo*bar\"", &sch).unwrap();
        match swc {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::StrictWildcard),
            _ => panic!("Expected strict wildcard comparison"),
        }
    }

    #[test]
    fn test_parse_contains_operator() {
        let sch = schema();
        let expr = FilterParser::parse("bar contains \"foo\"", &sch).unwrap();
        match expr {
            FilterExpr::Comparison { op, .. } => assert_eq!(op, ComparisonOp::Contains),
            _ => panic!("Expected contains comparison"),
        }
    }
}