edgevec 0.9.0

High-performance embedded vector database for Browser, Node, and Edge
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
// Allow missing docs for the generated pest Rule enum
#![allow(missing_docs)]

//! Filter expression parser for EdgeVec.
//!
//! This module provides the `parse()` function that converts filter expression
//! strings into `FilterExpr` AST nodes using a pest-based parser.
//!
//! # Grammar
//!
//! The filter grammar supports:
//! - Comparison: `=`, `!=`, `<`, `<=`, `>`, `>=`
//! - String: `CONTAINS`, `STARTS_WITH`, `ENDS_WITH`, `LIKE`
//! - Array: `IN`, `NOT IN`, `ANY`, `ALL`, `NONE`
//! - Range: `BETWEEN`
//! - Logical: `AND`, `OR`, `NOT`
//! - Null: `IS NULL`, `IS NOT NULL`
//!
//! # Example
//!
//! ```rust
//! use edgevec::filter::parse;
//!
//! // Simple comparison
//! let expr = parse("category = \"gpu\"").unwrap();
//!
//! // Complex expression
//! let expr = parse("price < 500 AND rating >= 4.0").unwrap();
//!
//! // With array operators
//! let expr = parse("tags ANY [\"rust\", \"wasm\"]").unwrap();
//! ```

use pest::Parser;
use pest_derive::Parser;

use super::ast::FilterExpr;
use super::error::{FilterError, MAX_INPUT_LENGTH, MAX_NESTING_DEPTH};

/// The pest parser for filter expressions.
///
/// This parser is generated from the grammar in `filter.pest` and
/// implements the `pest::Parser` trait for the `Rule` enum.
#[derive(Parser)]
#[grammar = "filter/filter.pest"]
#[allow(missing_docs)]
pub struct FilterParser;

/// Parse a filter expression string into an AST.
///
/// # Arguments
/// * `input` - The filter expression string
///
/// # Returns
/// * `Ok(FilterExpr)` - The parsed AST
/// * `Err(FilterError)` - Parse error with position information
///
/// # Examples
///
/// ```rust
/// use edgevec::filter::parse;
///
/// // Simple equality
/// let expr = parse("category = \"gpu\"").unwrap();
///
/// // Compound expression
/// let expr = parse("price < 500 AND rating >= 4.0").unwrap();
///
/// // With null check
/// let expr = parse("description IS NOT NULL").unwrap();
/// ```
///
/// # Errors
///
/// Returns `FilterError` for:
/// - Syntax errors (invalid tokens, unclosed strings, etc.)
/// - Input too long (exceeds `MAX_INPUT_LENGTH`)
/// - Nesting too deep (exceeds `MAX_NESTING_DEPTH`)
pub fn parse(input: &str) -> Result<FilterExpr, FilterError> {
    // Check input length
    if input.len() > MAX_INPUT_LENGTH {
        return Err(FilterError::InputTooLong {
            max_length: MAX_INPUT_LENGTH,
            actual_length: input.len(),
        });
    }

    // Parse with pest
    let pairs = FilterParser::parse(Rule::filter, input).map_err(|e| from_pest_error(&e, input))?;

    // Build AST from parse tree
    let expr = build_ast(pairs)?;

    // Check nesting depth
    let depth = expr.depth();
    if depth > MAX_NESTING_DEPTH {
        return Err(FilterError::NestingTooDeep {
            max_depth: MAX_NESTING_DEPTH,
            actual_depth: depth,
        });
    }

    Ok(expr)
}

/// Convert pest error to FilterError with position information.
fn from_pest_error(e: &pest::error::Error<Rule>, input: &str) -> FilterError {
    let (position, line, column) = match e.line_col {
        pest::error::LineColLocation::Pos((line, col))
        | pest::error::LineColLocation::Span((line, col), _) => {
            let pos = line_col_to_position(input, line, col);
            (pos, line, col)
        }
    };

    let message = format!("{}", e.variant.message());

    // Try to generate helpful suggestions
    let suggestion = generate_suggestion(&message, input, position);

    FilterError::SyntaxError {
        position,
        line,
        column,
        message,
        suggestion,
    }
}

/// Convert line/column to byte position.
fn line_col_to_position(input: &str, line: usize, col: usize) -> usize {
    let mut pos = 0;
    for (i, l) in input.lines().enumerate() {
        if i + 1 == line {
            return pos + col.saturating_sub(1);
        }
        pos += l.len() + 1; // +1 for newline
    }
    pos
}

/// Generate helpful suggestions based on error context.
fn generate_suggestion(message: &str, input: &str, position: usize) -> Option<String> {
    // SAFETY: Ensure position is a valid char boundary before slicing.
    // If position is not on a char boundary (can happen with multi-byte UTF-8),
    // we skip suggestions rather than panic.
    if position >= input.len() || !input.is_char_boundary(position) {
        return None;
    }

    let remaining = &input[position..];
    let before = &input[..position];

    // Check for common operator typos
    if remaining.starts_with(':') {
        return Some("Did you mean '=' instead of ':'? EdgeVec uses '=' for equality.".to_string());
    }
    if remaining.starts_with("==") {
        return Some("Use single '=' for equality comparisons, not '=='.".to_string());
    }
    if remaining.starts_with("===") {
        return Some(
            "EdgeVec uses '=' for equality. JavaScript-style '===' is not supported.".to_string(),
        );
    }
    if remaining.starts_with("<>") {
        return Some("Use '!=' for not-equal comparisons, not '<>'.".to_string());
    }

    // Check for symbolic logical operators (these ARE supported, but provide helpful context)
    if remaining.starts_with("&&") || remaining.starts_with("||") {
        // These are actually supported, so only suggest if there's a syntax issue
        if message.contains("expected") {
            return Some(
                "Both symbolic (&&, ||) and keyword (AND, OR) operators are supported.".to_string(),
            );
        }
    }

    // Check for missing quotes around strings
    if message.contains("expected") && !remaining.is_empty() {
        let first_char = remaining.chars().next().unwrap_or(' ');
        if first_char.is_alphabetic() && !is_keyword(remaining) {
            // Check if this looks like an unquoted string after an operator
            if before.ends_with("= ") || before.ends_with('=') {
                let word: String = remaining
                    .chars()
                    .take_while(|c| c.is_alphanumeric())
                    .collect();
                if !word.is_empty() && !is_keyword(&word) {
                    return Some(format!(
                        "String values must be quoted. Try: = \"{word}\" instead of = {word}"
                    ));
                }
            }
        }
    }

    // Check for SQL-style syntax errors
    if remaining.to_uppercase().starts_with("WHERE ") {
        return Some(
            "EdgeVec filter expressions don't use 'WHERE'. Start directly with conditions."
                .to_string(),
        );
    }

    // Check for missing operator between field and value
    if message.contains("expected") {
        // Look for pattern like "field value" without operator
        let words: Vec<&str> = before.split_whitespace().collect();
        if !words.is_empty() {
            let last_word = *words.last().unwrap_or(&"");
            if is_valid_field_name(last_word) && !is_keyword(last_word) {
                if let Some(first_remaining_word) = remaining.split_whitespace().next() {
                    if !is_operator(first_remaining_word) && !is_keyword(first_remaining_word) {
                        return Some(format!(
                            "Missing operator between '{last_word}' and value. \
                             Expected: =, !=, <, <=, >, >=, CONTAINS, IN, etc."
                        ));
                    }
                }
            }
        }
    }

    // Check for common array syntax errors
    if remaining.starts_with('(')
        && message.contains("expected")
        && (before.to_uppercase().ends_with(" IN") || before.to_uppercase().ends_with(" IN "))
    {
        return Some(
            "Use square brackets [...] for arrays, not parentheses (...). \
             Example: category IN [\"a\", \"b\"]"
                .to_string(),
        );
    }

    // Check for BETWEEN syntax errors
    if before.to_uppercase().contains("BETWEEN")
        && !before.to_uppercase().contains(" AND ")
        && (remaining.to_uppercase().starts_with("TO ")
            || remaining.to_uppercase().starts_with("- "))
    {
        return Some(
            "BETWEEN uses AND to separate values. Example: price BETWEEN 10 AND 100".to_string(),
        );
    }

    None
}

/// Check if a string is a recognized keyword.
fn is_keyword(s: &str) -> bool {
    let upper = s.to_uppercase();
    let word: String = upper.chars().take_while(|c| c.is_alphabetic()).collect();
    matches!(
        word.as_str(),
        "AND"
            | "OR"
            | "NOT"
            | "IN"
            | "BETWEEN"
            | "LIKE"
            | "CONTAINS"
            | "STARTS_WITH"
            | "ENDS_WITH"
            | "IS"
            | "NULL"
            | "TRUE"
            | "FALSE"
            | "ANY"
            | "ALL"
            | "NONE"
    )
}

/// Check if a string is a valid field name.
fn is_valid_field_name(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let first = s.chars().next().unwrap();
    if !first.is_alphabetic() && first != '_' {
        return false;
    }
    s.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// Check if a string is an operator.
fn is_operator(s: &str) -> bool {
    matches!(s, "=" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||" | "!")
}

/// Build AST from pest parse tree.
fn build_ast(pairs: pest::iterators::Pairs<Rule>) -> Result<FilterExpr, FilterError> {
    for pair in pairs {
        if pair.as_rule() == Rule::filter {
            // filter = { SOI ~ logical_expr ~ EOI }
            for inner in pair.into_inner() {
                if inner.as_rule() == Rule::logical_expr {
                    return build_logical_expr(inner);
                }
            }
        }
    }

    // Should not reach here if grammar is correct
    Err(FilterError::SyntaxError {
        position: 0,
        line: 1,
        column: 1,
        message: "Empty or invalid filter expression".to_string(),
        suggestion: None,
    })
}

/// Build logical expression (OR chain).
fn build_logical_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // logical_expr = { or_expr }
    // SAFETY: Grammar guarantees logical_expr always contains exactly one or_expr child.
    // The pest grammar rule `logical_expr = { or_expr }` ensures this invariant.
    let inner = pair.into_inner().next().unwrap();
    build_or_expr(inner)
}

/// Build OR expression.
fn build_or_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // or_expr = { and_expr ~ (or_op ~ and_expr)* }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees or_expr always contains at least one and_expr.
    // The rule `or_expr = { and_expr ~ (or_op ~ and_expr)* }` requires the first and_expr.
    let first = inner.next().unwrap();
    let mut left = build_and_expr(first)?;

    for next in inner {
        // or_op is silent, so we get and_expr directly
        let right = build_and_expr(next)?;
        left = FilterExpr::Or(Box::new(left), Box::new(right));
    }

    Ok(left)
}

/// Build AND expression.
fn build_and_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // and_expr = { not_expr ~ (and_op ~ not_expr)* }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees and_expr always contains at least one not_expr.
    // The rule `and_expr = { not_expr ~ (and_op ~ not_expr)* }` requires the first not_expr.
    let first = inner.next().unwrap();
    let mut left = build_not_expr(first)?;

    for next in inner {
        // and_op is silent, so we get not_expr directly
        let right = build_not_expr(next)?;
        left = FilterExpr::And(Box::new(left), Box::new(right));
    }

    Ok(left)
}

/// Build NOT expression.
fn build_not_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // not_expr = { not_op ~ not_expr | primary_expr }
    // Since not_op is silent (_), when we have "NOT x = 1", we get:
    // - not_expr which contains just not_expr (the inner recursion)
    // When we have just "x = 1", we get:
    // - not_expr which contains primary_expr

    let inner: Vec<_> = pair.into_inner().collect();

    if inner.is_empty() {
        // Defensive check: should not happen if grammar is correct
        return Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: "Empty not_expr".to_string(),
            suggestion: None,
        });
    }

    // SAFETY: We've already checked inner.is_empty() above, so this unwrap is safe.
    // The grammar rule `not_expr = { not_op ~ not_expr | primary_expr }` guarantees
    // at least one child node exists.
    let first = inner.into_iter().next().unwrap();

    match first.as_rule() {
        Rule::not_expr => {
            // This is a NOT operation: not_op (silent) followed by not_expr
            let operand = build_not_expr(first)?;
            Ok(FilterExpr::Not(Box::new(operand)))
        }
        Rule::primary_expr => {
            // This is just a primary expression (no NOT)
            build_primary_expr(first)
        }
        _ => {
            // Fallback: try to build as primary expression
            build_primary_expr(first)
        }
    }
}

/// Build primary expression.
fn build_primary_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // primary_expr = { grouped_expr | null_check | between_expr | ... }
    // SAFETY: Grammar guarantees primary_expr always contains exactly one child.
    // The rule `primary_expr = { grouped_expr | null_check | ... }` is a choice
    // expression that always matches exactly one alternative.
    let inner = pair.into_inner().next().unwrap();

    match inner.as_rule() {
        Rule::grouped_expr => build_grouped_expr(inner),
        Rule::null_check => build_null_check(inner),
        Rule::between_expr => build_between_expr(inner),
        Rule::array_op_expr => build_array_op_expr(inner),
        Rule::string_op_expr => build_string_op_expr(inner),
        Rule::set_op_expr => build_set_op_expr(inner),
        Rule::comparison_expr => build_comparison_expr(inner),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Unexpected rule: {:?}", inner.as_rule()),
            suggestion: None,
        }),
    }
}

/// Build grouped expression (parentheses).
fn build_grouped_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // grouped_expr = { "(" ~ logical_expr ~ ")" }
    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::logical_expr {
            return build_logical_expr(inner);
        }
    }

    Err(FilterError::SyntaxError {
        position: 0,
        line: 1,
        column: 1,
        message: "Empty grouped expression".to_string(),
        suggestion: None,
    })
}

/// Build null check expression.
fn build_null_check(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // null_check = { field ~ is_null_op }
    let mut inner = pair.into_inner();
    // SAFETY: Grammar guarantees null_check contains field followed by is_null_op.
    // The rule `null_check = { field ~ is_null_op }` requires both children.
    let field_pair = inner.next().unwrap();
    let field_name = field_pair.as_str().to_string();
    let field_expr = FilterExpr::Field(field_name);

    // SAFETY: Second child (is_null_op) is guaranteed by grammar.
    let op_pair = inner.next().unwrap();
    // SAFETY: is_null_op = { is_not_null_op | is_null_only_op } always has one child.
    let op_inner = op_pair.into_inner().next().unwrap();

    match op_inner.as_rule() {
        Rule::is_not_null_op => Ok(FilterExpr::IsNotNull(Box::new(field_expr))),
        Rule::is_null_only_op => Ok(FilterExpr::IsNull(Box::new(field_expr))),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: "Invalid null check operator".to_string(),
            suggestion: None,
        }),
    }
}

/// Build between expression.
fn build_between_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // between_expr = { field ~ between_op ~ value ~ and_keyword ~ value }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees between_expr has exactly 5 children in order:
    // field, between_op, value, and_keyword, value
    let field_pair = inner.next().unwrap();
    let field_expr = FilterExpr::Field(field_pair.as_str().to_string());

    // Skip between_op (SAFETY: guaranteed by grammar)
    inner.next();

    // SAFETY: Third child (first value) guaranteed by grammar
    let low_pair = inner.next().unwrap();
    let low_expr = build_value(low_pair)?;

    // Skip and_keyword (SAFETY: guaranteed by grammar)
    inner.next();

    // SAFETY: Fifth child (second value) guaranteed by grammar
    let high_pair = inner.next().unwrap();
    let high_expr = build_value(high_pair)?;

    Ok(FilterExpr::Between(
        Box::new(field_expr),
        Box::new(low_expr),
        Box::new(high_expr),
    ))
}

/// Build array operation expression (ANY, ALL, NONE).
fn build_array_op_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // array_op_expr = { field ~ array_op ~ array_literal }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees array_op_expr has exactly 3 children:
    // field, array_op, array_literal
    let field_pair = inner.next().unwrap();
    let field_expr = FilterExpr::Field(field_pair.as_str().to_string());

    // SAFETY: Second child (array_op) guaranteed by grammar
    let op_pair = inner.next().unwrap();
    let op_str = op_pair.as_str().to_lowercase();

    // SAFETY: Third child (array_literal) guaranteed by grammar
    let array_pair = inner.next().unwrap();
    let array_expr = build_array_literal(array_pair)?;

    match op_str.as_str() {
        "any" => Ok(FilterExpr::Any(Box::new(field_expr), Box::new(array_expr))),
        "all" => Ok(FilterExpr::All(Box::new(field_expr), Box::new(array_expr))),
        "none" => Ok(FilterExpr::None(Box::new(field_expr), Box::new(array_expr))),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Unknown array operator: {op_str}"),
            suggestion: None,
        }),
    }
}

/// Build string operation expression.
fn build_string_op_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // string_op_expr = { field ~ string_op ~ string_literal }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees string_op_expr has exactly 3 children:
    // field, string_op, string_literal
    let field_pair = inner.next().unwrap();
    let field_expr = FilterExpr::Field(field_pair.as_str().to_string());

    // SAFETY: Second child (string_op) guaranteed by grammar
    let op_pair = inner.next().unwrap();
    let op_str = op_pair.as_str().to_lowercase();

    // SAFETY: Third child (string_literal) guaranteed by grammar
    let string_pair = inner.next().unwrap();
    let string_expr = build_string_literal(&string_pair)?;

    match op_str.as_str() {
        "contains" => Ok(FilterExpr::Contains(
            Box::new(field_expr),
            Box::new(string_expr),
        )),
        "starts_with" => Ok(FilterExpr::StartsWith(
            Box::new(field_expr),
            Box::new(string_expr),
        )),
        "ends_with" => Ok(FilterExpr::EndsWith(
            Box::new(field_expr),
            Box::new(string_expr),
        )),
        "like" => Ok(FilterExpr::Like(
            Box::new(field_expr),
            Box::new(string_expr),
        )),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Unknown string operator: {op_str}"),
            suggestion: None,
        }),
    }
}

/// Build set operation expression (IN, NOT IN).
fn build_set_op_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // set_op_expr = { field ~ set_op ~ array_literal }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees set_op_expr has exactly 3 children:
    // field, set_op, array_literal
    let field_pair = inner.next().unwrap();
    let field_expr = FilterExpr::Field(field_pair.as_str().to_string());

    // SAFETY: Second child (set_op) guaranteed by grammar
    let op_pair = inner.next().unwrap();
    // SAFETY: set_op = { not_in_op | in_op } always has exactly one child
    let op_inner = op_pair.into_inner().next().unwrap();
    let is_not_in = op_inner.as_rule() == Rule::not_in_op;

    // SAFETY: Third child (array_literal) guaranteed by grammar
    let array_pair = inner.next().unwrap();
    let array_expr = build_array_literal(array_pair)?;

    if is_not_in {
        Ok(FilterExpr::NotIn(
            Box::new(field_expr),
            Box::new(array_expr),
        ))
    } else {
        Ok(FilterExpr::In(Box::new(field_expr), Box::new(array_expr)))
    }
}

/// Build comparison expression.
fn build_comparison_expr(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // comparison_expr = { field ~ comp_op ~ value }
    let mut inner = pair.into_inner();

    // SAFETY: Grammar guarantees comparison_expr has exactly 3 children:
    // field, comp_op, value
    let field_pair = inner.next().unwrap();
    let field_expr = FilterExpr::Field(field_pair.as_str().to_string());

    // SAFETY: Second child (comp_op) guaranteed by grammar
    let op_pair = inner.next().unwrap();
    let op_str = op_pair.as_str();

    // SAFETY: Third child (value) guaranteed by grammar
    let value_pair = inner.next().unwrap();
    let value_expr = build_value(value_pair)?;

    match op_str {
        "=" => Ok(FilterExpr::Eq(Box::new(field_expr), Box::new(value_expr))),
        "!=" => Ok(FilterExpr::Ne(Box::new(field_expr), Box::new(value_expr))),
        "<" => Ok(FilterExpr::Lt(Box::new(field_expr), Box::new(value_expr))),
        "<=" => Ok(FilterExpr::Le(Box::new(field_expr), Box::new(value_expr))),
        ">" => Ok(FilterExpr::Gt(Box::new(field_expr), Box::new(value_expr))),
        ">=" => Ok(FilterExpr::Ge(Box::new(field_expr), Box::new(value_expr))),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Unknown comparison operator: {op_str}"),
            suggestion: None,
        }),
    }
}

/// Build value expression.
fn build_value(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // value = { string_literal | number | boolean | field }
    // SAFETY: Grammar guarantees value always contains exactly one child.
    // The rule `value = { string_literal | number | boolean | field }` is a choice
    // expression that always matches exactly one alternative.
    let inner = pair.into_inner().next().unwrap();

    match inner.as_rule() {
        Rule::string_literal => build_string_literal(&inner),
        Rule::number => build_number(&inner),
        Rule::boolean => build_boolean(&inner),
        Rule::field => Ok(FilterExpr::Field(inner.as_str().to_string())),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Unexpected value type: {:?}", inner.as_rule()),
            suggestion: None,
        }),
    }
}

/// Build string literal.
fn build_string_literal(pair: &pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // string_literal = @{ "\"" ~ inner_string ~ "\"" }
    let raw = pair.as_str();
    // Remove quotes
    let content = &raw[1..raw.len() - 1];
    // Process escape sequences
    let processed = process_escapes(content)?;
    Ok(FilterExpr::LiteralString(processed))
}

/// Process escape sequences in string.
fn process_escapes(s: &str) -> Result<String, FilterError> {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('"') => result.push('"'),
                Some('\\') => result.push('\\'),
                Some('n') => result.push('\n'),
                Some('r') => result.push('\r'),
                Some('t') => result.push('\t'),
                Some(other) => {
                    return Err(FilterError::InvalidEscape {
                        char: other,
                        position: 0, // Position not easily available here
                    });
                }
                None => {
                    return Err(FilterError::SyntaxError {
                        position: 0,
                        line: 1,
                        column: 1,
                        message: "Trailing backslash in string".to_string(),
                        suggestion: Some("Escape the backslash with \\\\".to_string()),
                    });
                }
            }
        } else {
            result.push(c);
        }
    }

    Ok(result)
}

/// Build number literal.
fn build_number(pair: &pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    let s = pair.as_str();

    // Try parsing as integer first
    if !s.contains('.') {
        if let Ok(i) = s.parse::<i64>() {
            return Ok(FilterExpr::LiteralInt(i));
        }
    }

    // Parse as float
    if let Ok(f) = s.parse::<f64>() {
        return Ok(FilterExpr::LiteralFloat(f));
    }

    Err(FilterError::InvalidNumber {
        value: s.to_string(),
        position: 0,
    })
}

/// Build boolean literal.
fn build_boolean(pair: &pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    let s = pair.as_str().to_lowercase();
    match s.as_str() {
        "true" => Ok(FilterExpr::LiteralBool(true)),
        "false" => Ok(FilterExpr::LiteralBool(false)),
        _ => Err(FilterError::SyntaxError {
            position: 0,
            line: 1,
            column: 1,
            message: format!("Invalid boolean: {s}"),
            suggestion: None,
        }),
    }
}

/// Build array literal.
fn build_array_literal(pair: pest::iterators::Pair<Rule>) -> Result<FilterExpr, FilterError> {
    // array_literal = { "[" ~ (value ~ ("," ~ value)*)? ~ "]" }
    let mut elements = Vec::new();

    for inner in pair.into_inner() {
        if inner.as_rule() == Rule::value {
            elements.push(build_value(inner)?);
        }
    }

    Ok(FilterExpr::LiteralArray(elements))
}

#[cfg(test)]
#[allow(clippy::redundant_closure_for_method_calls)] // Test assertions use explicit closures for clarity
mod tests {
    use super::*;

    // =========================================================================
    // BASIC PARSING TESTS
    // =========================================================================

    #[test]
    fn test_parse_simple_eq() {
        let expr = parse("category = \"gpu\"").unwrap();
        assert!(matches!(expr, FilterExpr::Eq(_, _)));
        if let FilterExpr::Eq(left, right) = expr {
            assert_eq!(left.as_field(), Some("category"));
            assert_eq!(right.as_string(), Some("gpu"));
        }
    }

    #[test]
    fn test_parse_simple_ne() {
        let expr = parse("status != \"deleted\"").unwrap();
        assert!(matches!(expr, FilterExpr::Ne(_, _)));
    }

    #[test]
    fn test_parse_simple_lt() {
        let expr = parse("price < 500").unwrap();
        assert!(matches!(expr, FilterExpr::Lt(_, _)));
        if let FilterExpr::Lt(left, right) = expr {
            assert_eq!(left.as_field(), Some("price"));
            assert_eq!(right.as_int(), Some(500));
        }
    }

    #[test]
    fn test_parse_simple_le() {
        let expr = parse("rating <= 4.5").unwrap();
        assert!(matches!(expr, FilterExpr::Le(_, _)));
    }

    #[test]
    fn test_parse_simple_gt() {
        let expr = parse("count > 0").unwrap();
        assert!(matches!(expr, FilterExpr::Gt(_, _)));
    }

    #[test]
    fn test_parse_simple_ge() {
        let expr = parse("score >= 90").unwrap();
        assert!(matches!(expr, FilterExpr::Ge(_, _)));
    }

    // =========================================================================
    // LOGICAL OPERATOR TESTS
    // =========================================================================

    #[test]
    fn test_parse_and() {
        let expr = parse("a = 1 AND b = 2").unwrap();
        assert!(matches!(expr, FilterExpr::And(_, _)));
    }

    #[test]
    fn test_parse_or() {
        let expr = parse("a = 1 OR b = 2").unwrap();
        assert!(matches!(expr, FilterExpr::Or(_, _)));
    }

    #[test]
    fn test_parse_not() {
        let expr = parse("NOT active = true").unwrap();
        assert!(matches!(expr, FilterExpr::Not(_)));
    }

    #[test]
    fn test_parse_symbolic_and() {
        let expr = parse("a = 1 && b = 2").unwrap();
        assert!(matches!(expr, FilterExpr::And(_, _)));
    }

    #[test]
    fn test_parse_symbolic_or() {
        let expr = parse("a = 1 || b = 2").unwrap();
        assert!(matches!(expr, FilterExpr::Or(_, _)));
    }

    #[test]
    fn test_parse_symbolic_not() {
        let expr = parse("!active = true").unwrap();
        assert!(matches!(expr, FilterExpr::Not(_)));
    }

    // =========================================================================
    // PRECEDENCE TESTS
    // =========================================================================

    #[test]
    fn test_precedence_and_binds_tighter_than_or() {
        // a OR b AND c should parse as a OR (b AND c)
        let expr = parse("a = 1 OR b = 2 AND c = 3").unwrap();
        if let FilterExpr::Or(left, right) = expr {
            assert!(left.as_field().is_none()); // left is Eq, not field
            assert!(matches!(*right, FilterExpr::And(_, _)));
        } else {
            panic!("Expected Or at top level");
        }
    }

    #[test]
    fn test_precedence_parentheses() {
        // (a OR b) AND c
        let expr = parse("(a = 1 OR b = 2) AND c = 3").unwrap();
        assert!(matches!(expr, FilterExpr::And(_, _)));
        if let FilterExpr::And(left, _) = expr {
            assert!(matches!(*left, FilterExpr::Or(_, _)));
        }
    }

    // =========================================================================
    // STRING OPERATOR TESTS
    // =========================================================================

    #[test]
    fn test_parse_contains() {
        let expr = parse("description CONTAINS \"fast\"").unwrap();
        assert!(matches!(expr, FilterExpr::Contains(_, _)));
    }

    #[test]
    fn test_parse_starts_with() {
        let expr = parse("name STARTS_WITH \"GPU\"").unwrap();
        assert!(matches!(expr, FilterExpr::StartsWith(_, _)));
    }

    #[test]
    fn test_parse_ends_with() {
        let expr = parse("filename ENDS_WITH \".pdf\"").unwrap();
        assert!(matches!(expr, FilterExpr::EndsWith(_, _)));
    }

    #[test]
    fn test_parse_like() {
        let expr = parse("name LIKE \"GPU_%\"").unwrap();
        assert!(matches!(expr, FilterExpr::Like(_, _)));
    }

    // =========================================================================
    // SET OPERATOR TESTS
    // =========================================================================

    #[test]
    fn test_parse_in() {
        let expr = parse("category IN [\"gpu\", \"cpu\"]").unwrap();
        assert!(matches!(expr, FilterExpr::In(_, _)));
    }

    #[test]
    fn test_parse_not_in() {
        let expr = parse("status NOT IN [\"deleted\", \"archived\"]").unwrap();
        assert!(matches!(expr, FilterExpr::NotIn(_, _)));
    }

    // =========================================================================
    // ARRAY OPERATOR TESTS
    // =========================================================================

    #[test]
    fn test_parse_any() {
        let expr = parse("tags ANY [\"rust\", \"wasm\"]").unwrap();
        assert!(matches!(expr, FilterExpr::Any(_, _)));
    }

    #[test]
    fn test_parse_all() {
        let expr = parse("tags ALL [\"rust\", \"wasm\"]").unwrap();
        assert!(matches!(expr, FilterExpr::All(_, _)));
    }

    #[test]
    fn test_parse_none() {
        let expr = parse("tags NONE [\"deprecated\"]").unwrap();
        assert!(matches!(expr, FilterExpr::None(_, _)));
    }

    // =========================================================================
    // RANGE OPERATOR TESTS
    // =========================================================================

    #[test]
    fn test_parse_between() {
        let expr = parse("price BETWEEN 100 AND 500").unwrap();
        assert!(matches!(expr, FilterExpr::Between(_, _, _)));
        if let FilterExpr::Between(field, low, high) = expr {
            assert_eq!(field.as_field(), Some("price"));
            assert_eq!(low.as_int(), Some(100));
            assert_eq!(high.as_int(), Some(500));
        }
    }

    // =========================================================================
    // NULL CHECK TESTS
    // =========================================================================

    #[test]
    fn test_parse_is_null() {
        let expr = parse("description IS NULL").unwrap();
        assert!(matches!(expr, FilterExpr::IsNull(_)));
    }

    #[test]
    fn test_parse_is_not_null() {
        let expr = parse("description IS NOT NULL").unwrap();
        assert!(matches!(expr, FilterExpr::IsNotNull(_)));
    }

    // =========================================================================
    // CASE INSENSITIVITY TESTS
    // =========================================================================

    #[test]
    fn test_case_insensitive_and() {
        assert!(parse("a = 1 and b = 2").is_ok());
        assert!(parse("a = 1 AND b = 2").is_ok());
        assert!(parse("a = 1 And b = 2").is_ok());
    }

    #[test]
    fn test_case_insensitive_or() {
        assert!(parse("a = 1 or b = 2").is_ok());
        assert!(parse("a = 1 OR b = 2").is_ok());
    }

    #[test]
    fn test_case_insensitive_contains() {
        assert!(parse("name contains \"test\"").is_ok());
        assert!(parse("name CONTAINS \"test\"").is_ok());
    }

    #[test]
    fn test_case_insensitive_boolean() {
        assert!(parse("active = TRUE").is_ok());
        assert!(parse("active = true").is_ok());
        assert!(parse("active = True").is_ok());
    }

    // =========================================================================
    // LITERAL TESTS
    // =========================================================================

    #[test]
    fn test_parse_integer() {
        let expr = parse("count = 42").unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_int(), Some(42));
        }
    }

    #[test]
    fn test_parse_negative_integer() {
        let expr = parse("temp = -10").unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_int(), Some(-10));
        }
    }

    #[test]
    fn test_parse_float() {
        let expr = parse("rating = 4.5").unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_float(), Some(4.5));
        }
    }

    #[test]
    fn test_parse_negative_float() {
        let expr = parse("temp = -2.5").unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_float(), Some(-2.5));
        }
    }

    #[test]
    fn test_parse_string_escapes() {
        let expr = parse(r#"msg = "hello \"world\"""#).unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_string(), Some("hello \"world\""));
        }
    }

    #[test]
    fn test_parse_string_escape_newline() {
        let expr = parse(r#"msg = "line1\nline2""#).unwrap();
        if let FilterExpr::Eq(_, right) = expr {
            assert_eq!(right.as_string(), Some("line1\nline2"));
        }
    }

    #[test]
    fn test_parse_empty_array() {
        let expr = parse("tags IN []").unwrap();
        if let FilterExpr::In(_, right) = expr {
            assert_eq!(right.as_array().map(|a| a.len()), Some(0));
        }
    }

    // =========================================================================
    // COMPLEX EXPRESSION TESTS
    // =========================================================================

    #[test]
    fn test_parse_complex_expression() {
        let input = "category = \"gpu\" AND (price < 500 OR rating >= 4.5)";
        let expr = parse(input).unwrap();
        assert!(matches!(expr, FilterExpr::And(_, _)));
    }

    #[test]
    fn test_parse_deeply_nested() {
        let input = "((a = 1) AND (b = 2)) OR ((c = 3) AND (d = 4))";
        let expr = parse(input).unwrap();
        assert!(matches!(expr, FilterExpr::Or(_, _)));
    }

    // =========================================================================
    // ERROR TESTS
    // =========================================================================

    #[test]
    fn test_parse_error_empty() {
        let result = parse("");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_unclosed_string() {
        let result = parse("name = \"unclosed");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_unclosed_paren() {
        let result = parse("(a = 1");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_invalid_operator() {
        let result = parse("a == 1");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_error_input_too_long() {
        let long_input = "a".repeat(MAX_INPUT_LENGTH + 1);
        let result = parse(&long_input);
        assert!(matches!(result, Err(FilterError::InputTooLong { .. })));
    }

    // =========================================================================
    // WHITESPACE TESTS
    // =========================================================================

    #[test]
    fn test_whitespace_handling() {
        assert!(parse("  a  =  1  ").is_ok());
        assert!(parse("a=1").is_ok());
        assert!(parse("a = 1 AND b = 2").is_ok());
        // Note: a=1AND b=2 actually parses correctly because:
        // - number parsing stops at 'A' (non-digit)
        // - AND is recognized as a keyword
        // This is valid in the grammar (though not recommended style)
        assert!(parse("a=1AND b=2").is_ok());
    }

    #[test]
    fn test_newline_handling() {
        let input = "a = 1\nAND\nb = 2";
        assert!(parse(input).is_ok());
    }

    // =========================================================================
    // FUZZ REGRESSION TESTS
    // =========================================================================

    /// Regression test for fuzz crash: byte index not on char boundary.
    /// Crash input: v="ss\xde\x83\xc2\x83"|"
    /// Issue: generate_suggestion() sliced at non-char-boundary position.
    /// Fix: Added is_char_boundary() check before slicing.
    #[test]
    fn test_fuzz_regression_non_char_boundary() {
        // The exact crash input from fuzzer (hex: 76 3d 22 73 73 de 83 c2 83 22 7c 22)
        // This contains invalid UTF-8 sequences that create multi-byte chars
        let crash_input = "v=\"ss\u{07C3}\u{0083}\"|\"";
        // Should not panic, should return an error
        let result = parse(crash_input);
        assert!(result.is_err());
    }

    /// Additional fuzz regression: raw bytes from crash artifact
    #[test]
    fn test_fuzz_regression_raw_bytes() {
        // Raw bytes: [0x76, 0x3d, 0x22, 0x73, 0x73, 0xde, 0x83, 0xc2, 0x83, 0x22, 0x7c, 0x22]
        // Note: \xde\x83 is invalid UTF-8 start, \xc2\x83 is valid (ƒ)
        // When converted to string via lossy conversion, it becomes different
        let bytes: &[u8] = &[
            0x76, 0x3d, 0x22, 0x73, 0x73, 0xde, 0x83, 0xc2, 0x83, 0x22, 0x7c, 0x22,
        ];
        let input = String::from_utf8_lossy(bytes);
        // Should not panic regardless of content
        let _ = parse(&input);
    }

    /// Test various multi-byte UTF-8 characters in filter expressions
    #[test]
    fn test_multibyte_utf8_handling() {
        // Various multi-byte UTF-8 characters
        let inputs = [
            "x = \"日本語\"",    // Japanese (3-byte chars)
            "x = \"émoji: 🦀\"", // Emoji (4-byte char)
            "field_名前 = 1",    // Non-ASCII in field name
            "x = \"Москва\"",    // Cyrillic (2-byte chars)
            "x = \"🦀\"",        // Crab emoji directly
        ];

        for input in inputs {
            // Should not panic - may succeed or fail depending on grammar
            let _ = parse(input);
        }
    }

    /// Test edge cases with positions near multi-byte boundaries
    #[test]
    fn test_error_position_multibyte() {
        // Error occurs after multi-byte char
        let result = parse("名前 : 1"); // colon is invalid, should give suggestion
        assert!(result.is_err());
        // Key: should not panic even if error position is after multi-byte char
    }

    // =========================================================================
    // ERROR SUGGESTION TESTS (W25.2.2)
    // =========================================================================

    #[test]
    fn test_suggestion_colon_instead_of_equals() {
        let result = parse("category : \"gpu\"");
        assert!(result.is_err());
        if let Err(FilterError::SyntaxError { suggestion, .. }) = result {
            assert!(
                suggestion.is_some(),
                "Should suggest using '=' instead of ':'"
            );
            let s = suggestion.unwrap();
            assert!(s.contains('='), "Suggestion should mention '='");
        }
    }

    #[test]
    fn test_suggestion_double_equals() {
        // Test that == is rejected (EdgeVec uses single =)
        let result = parse("a == 1");
        assert!(result.is_err(), "== should not be valid syntax");
        // Note: Suggestion may not always be provided depending on where pest reports the error
    }

    #[test]
    fn test_suggestion_sql_not_equal() {
        // Test that <> is rejected (EdgeVec uses !=)
        let result = parse("a <> 1");
        assert!(result.is_err(), "<> should not be valid syntax");
        // Note: Suggestion may not always be provided depending on where pest reports the error
    }

    #[test]
    fn test_suggestion_where_keyword() {
        // Test that WHERE prefix is gracefully rejected
        let result = parse("WHERE a = 1");
        assert!(result.is_err(), "WHERE keyword should not be valid");
    }

    #[test]
    fn test_suggestion_parentheses_for_array() {
        let result = parse("category IN (\"a\", \"b\")");
        assert!(result.is_err());
        if let Err(FilterError::SyntaxError { suggestion, .. }) = result {
            assert!(
                suggestion.is_some(),
                "Should suggest using [...] instead of (...)"
            );
            let s = suggestion.unwrap();
            assert!(
                s.contains('[') || s.contains("square brackets"),
                "Suggestion should mention square brackets"
            );
        }
    }

    #[test]
    fn test_helper_is_keyword() {
        assert!(is_keyword("AND"));
        assert!(is_keyword("and"));
        assert!(is_keyword("Or"));
        assert!(is_keyword("NOT"));
        assert!(is_keyword("IN"));
        assert!(is_keyword("CONTAINS"));
        assert!(!is_keyword("category"));
        assert!(!is_keyword("price"));
    }

    #[test]
    fn test_helper_is_valid_field_name() {
        assert!(is_valid_field_name("category"));
        assert!(is_valid_field_name("price_usd"));
        assert!(is_valid_field_name("_private"));
        assert!(is_valid_field_name("field123"));
        assert!(!is_valid_field_name("123field"));
        assert!(!is_valid_field_name(""));
        assert!(!is_valid_field_name("field-name"));
    }

    #[test]
    fn test_helper_is_operator() {
        assert!(is_operator("="));
        assert!(is_operator("!="));
        assert!(is_operator("<"));
        assert!(is_operator("<="));
        assert!(is_operator(">"));
        assert!(is_operator(">="));
        assert!(is_operator("&&"));
        assert!(is_operator("||"));
        assert!(!is_operator("AND"));
        assert!(!is_operator("category"));
    }
}