Skip to main content

rsigma_parser/
condition.rs

1//! Condition expression parser using pest PEG grammar + Pratt parser.
2//!
3//! Parses Sigma condition strings like:
4//! - `"selection and not filter"`
5//! - `"1 of selection_* and not 1 of filter_*"`
6//! - `"all of them"`
7//! - `"selection_main and 1 of selection_dword_* and not 1 of filter_optional_*"`
8//!
9//! Reference: pySigma conditions.py (uses pyparsing infix_notation)
10
11use std::num::NonZeroU64;
12
13use pest::Parser;
14use pest::iterators::Pair;
15use pest::pratt_parser::{Assoc, Op, PrattParser};
16use pest_derive::Parser;
17
18use crate::ast::{ConditionExpr, Quantifier, SelectorPattern};
19use crate::error::{Result, SigmaParserError, SourceLocation};
20
21// ---------------------------------------------------------------------------
22// Pest parser (generated from sigma.pest grammar)
23// ---------------------------------------------------------------------------
24
25#[derive(Parser)]
26#[grammar = "src/sigma.pest"]
27struct SigmaConditionParser;
28
29// ---------------------------------------------------------------------------
30// Public API
31// ---------------------------------------------------------------------------
32
33const MAX_CONDITION_LEN: usize = 64 * 1024;
34const MAX_CONDITION_DEPTH: usize = 64;
35
36/// Parse a Sigma condition expression string into an AST.
37///
38/// # Examples
39///
40/// ```
41/// use rsigma_parser::condition::parse_condition;
42///
43/// let expr = parse_condition("selection and not filter").unwrap();
44/// println!("{expr}");
45/// ```
46pub fn parse_condition(input: &str) -> Result<ConditionExpr> {
47    if input.len() > MAX_CONDITION_LEN {
48        return Err(SigmaParserError::ConditionTooLong(
49            input.len(),
50            MAX_CONDITION_LEN,
51        ));
52    }
53
54    let pairs = SigmaConditionParser::parse(Rule::condition, input).map_err(|e| {
55        let loc = extract_pest_location(&e);
56        SigmaParserError::Condition(e.to_string(), loc)
57    })?;
58
59    let pratt = PrattParser::new()
60        .op(Op::infix(Rule::or_op, Assoc::Left))
61        .op(Op::infix(Rule::and_op, Assoc::Left))
62        .op(Op::prefix(Rule::not_op));
63
64    // condition = { SOI ~ expr ~ EOI }
65    let condition_pair = pairs
66        .into_iter()
67        .next()
68        .ok_or_else(|| SigmaParserError::Condition("empty condition expression".into(), None))?;
69    let expr_pair = condition_pair
70        .into_inner()
71        .find(|p| p.as_rule() == Rule::expr)
72        .ok_or_else(|| SigmaParserError::Condition("missing expr in condition".into(), None))?;
73
74    let depth = std::cell::Cell::new(0usize);
75    parse_expr(expr_pair, &pratt, &depth)
76}
77
78fn extract_pest_location(err: &pest::error::Error<Rule>) -> Option<SourceLocation> {
79    match err.line_col {
80        pest::error::LineColLocation::Pos((line, col)) => Some(SourceLocation {
81            line: line as u32,
82            col: col as u32,
83        }),
84        pest::error::LineColLocation::Span((line, col), _) => Some(SourceLocation {
85            line: line as u32,
86            col: col as u32,
87        }),
88    }
89}
90
91// ---------------------------------------------------------------------------
92// Internal parsing helpers
93// ---------------------------------------------------------------------------
94
95/// An error collected during Pratt parsing, with optional position context.
96struct PrattError {
97    message: String,
98    location: Option<SourceLocation>,
99}
100
101impl PrattError {
102    /// Keeps only the bare message of a condition error, so the location is
103    /// rendered once by the outer error instead of being nested in the text.
104    fn from_error(err: SigmaParserError, fallback: Option<SourceLocation>) -> Self {
105        let location = err.location().or(fallback);
106        let message = match err {
107            SigmaParserError::Condition(message, _) => message,
108            other => other.to_string(),
109        };
110        PrattError { message, location }
111    }
112}
113
114fn location_from_pair(pair: &Pair<'_, Rule>) -> Option<SourceLocation> {
115    let (line, col) = pair.as_span().start_pos().line_col();
116    Some(SourceLocation {
117        line: line as u32,
118        col: col as u32,
119    })
120}
121
122fn parse_expr(
123    pair: Pair<'_, Rule>,
124    pratt: &PrattParser<Rule>,
125    depth: &std::cell::Cell<usize>,
126) -> Result<ConditionExpr> {
127    let current = depth.get();
128    if current > MAX_CONDITION_DEPTH {
129        return Err(SigmaParserError::Condition(
130            format!("condition nesting exceeds maximum depth ({MAX_CONDITION_DEPTH})"),
131            None,
132        ));
133    }
134    depth.set(current + 1);
135
136    // The Pratt parser closures cannot return Result, so we collect all
137    // errors in a shared RefCell and report them after parsing completes.
138    let errors: std::cell::RefCell<Vec<PrattError>> = std::cell::RefCell::new(Vec::new());
139
140    let result = pratt
141        .map_primary(|primary| {
142            let loc = location_from_pair(&primary);
143            match primary.as_rule() {
144                Rule::ident => ConditionExpr::Identifier(primary.as_str().to_string()),
145                Rule::selector => parse_selector(primary).unwrap_or_else(|e| {
146                    errors.borrow_mut().push(PrattError::from_error(e, loc));
147                    ConditionExpr::Identifier(String::new())
148                }),
149                Rule::expr => parse_expr(primary, pratt, depth).unwrap_or_else(|e| {
150                    errors.borrow_mut().push(PrattError::from_error(e, loc));
151                    ConditionExpr::Identifier(String::new())
152                }),
153                other => {
154                    errors.borrow_mut().push(PrattError {
155                        message: format!("unexpected primary rule: {other:?}"),
156                        location: loc,
157                    });
158                    ConditionExpr::Identifier(String::new())
159                }
160            }
161        })
162        .map_prefix(|op, rhs| {
163            let loc = location_from_pair(&op);
164            match op.as_rule() {
165                Rule::not_op => ConditionExpr::Not(Box::new(rhs)),
166                other => {
167                    errors.borrow_mut().push(PrattError {
168                        message: format!("unexpected prefix rule: {other:?}"),
169                        location: loc,
170                    });
171                    rhs
172                }
173            }
174        })
175        .map_infix(|lhs, op, rhs| {
176            let loc = location_from_pair(&op);
177            match op.as_rule() {
178                Rule::and_op => merge_binary(ConditionExpr::And, lhs, rhs),
179                Rule::or_op => merge_binary(ConditionExpr::Or, lhs, rhs),
180                other => {
181                    errors.borrow_mut().push(PrattError {
182                        message: format!("unexpected infix rule: {other:?}"),
183                        location: loc,
184                    });
185                    lhs
186                }
187            }
188        })
189        .parse(pair.into_inner());
190
191    depth.set(depth.get().saturating_sub(1));
192
193    let mut collected = errors.into_inner();
194    if collected.len() == 1 {
195        let PrattError { message, location } = collected.remove(0);
196        return Err(SigmaParserError::Condition(message, location));
197    }
198    if !collected.is_empty() {
199        let combined = collected
200            .iter()
201            .map(|e| match &e.location {
202                Some(loc) => format!("at {loc}: {}", e.message),
203                None => e.message.clone(),
204            })
205            .collect::<Vec<_>>()
206            .join("; ");
207        let first_loc = collected.iter().find_map(|e| e.location);
208        return Err(SigmaParserError::Condition(combined, first_loc));
209    }
210
211    Ok(result)
212}
213
214/// Flatten nested binary operators of the same kind.
215/// `a AND (b AND c)` → `AND(a, b, c)` instead of `AND(a, AND(b, c))`.
216fn merge_binary(
217    ctor: fn(Vec<ConditionExpr>) -> ConditionExpr,
218    lhs: ConditionExpr,
219    rhs: ConditionExpr,
220) -> ConditionExpr {
221    // Flatten same-type children to avoid unnecessary nesting: And(And(a, b), c) → And(a, b, c)
222    let is_and = matches!(ctor(vec![]), ConditionExpr::And(_));
223
224    let mut args = Vec::new();
225    for expr in [lhs, rhs] {
226        match expr {
227            ConditionExpr::And(children) if is_and => args.extend(children),
228            ConditionExpr::Or(children) if !is_and => args.extend(children),
229            other => args.push(other),
230        }
231    }
232
233    ctor(args)
234}
235
236fn parse_selector(pair: Pair<'_, Rule>) -> Result<ConditionExpr> {
237    // Iterate children, skipping the of_kw_inner pair (atomic rules can't be silent
238    // in pest, so of_kw_inner leaks into the parse tree)
239    let mut quantifier_pair = None;
240    let mut target_pair = None;
241
242    for p in pair.into_inner() {
243        match p.as_rule() {
244            Rule::quantifier => quantifier_pair = Some(p),
245            Rule::selector_target => target_pair = Some(p),
246            _ => {} // skip of_kw_inner
247        }
248    }
249
250    let quantifier =
251        parse_quantifier(quantifier_pair.ok_or_else(|| {
252            SigmaParserError::Condition("selector missing quantifier".into(), None)
253        })?)?;
254    let pattern = parse_selector_target(
255        target_pair
256            .ok_or_else(|| SigmaParserError::Condition("selector missing target".into(), None))?,
257    )?;
258
259    Ok(ConditionExpr::Selector {
260        quantifier,
261        pattern,
262    })
263}
264
265fn parse_quantifier(pair: Pair<'_, Rule>) -> Result<Quantifier> {
266    let inner = pair
267        .into_inner()
268        .next()
269        .ok_or_else(|| SigmaParserError::Condition("quantifier missing child".into(), None))?;
270    match inner.as_rule() {
271        Rule::all_kw => Ok(Quantifier::All),
272        Rule::any_kw => Ok(Quantifier::Any),
273        Rule::uint => {
274            let n: u64 = inner.as_str().parse().map_err(|e| {
275                SigmaParserError::Condition(format!("invalid quantifier number: {e}"), None)
276            })?;
277            match NonZeroU64::new(n) {
278                None => {
279                    let (line, col) = inner.as_span().start_pos().line_col();
280                    Err(SigmaParserError::Condition(
281                        "'0 of' is always true and matches every event; use 'not 1 of' to \
282                         require that none of the detections match"
283                            .into(),
284                        Some(SourceLocation {
285                            line: line as u32,
286                            col: col as u32,
287                        }),
288                    ))
289                }
290                Some(n) if n.get() == 1 => Ok(Quantifier::Any),
291                Some(n) => Ok(Quantifier::Count(n)),
292            }
293        }
294        other => Err(SigmaParserError::Condition(
295            format!("unexpected quantifier rule: {other:?}"),
296            None,
297        )),
298    }
299}
300
301fn parse_selector_target(pair: Pair<'_, Rule>) -> Result<SelectorPattern> {
302    let inner = pair
303        .into_inner()
304        .next()
305        .ok_or_else(|| SigmaParserError::Condition("selector target missing child".into(), None))?;
306    match inner.as_rule() {
307        Rule::them_kw => Ok(SelectorPattern::Them),
308        Rule::ident_pattern => Ok(SelectorPattern::Pattern(inner.as_str().to_string())),
309        other => Err(SigmaParserError::Condition(
310            format!("unexpected selector target rule: {other:?}"),
311            None,
312        )),
313    }
314}
315
316// =============================================================================
317// Tests
318// =============================================================================
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    #[test]
325    fn test_simple_identifier() {
326        let expr = parse_condition("selection").unwrap();
327        assert_eq!(expr, ConditionExpr::Identifier("selection".to_string()));
328    }
329
330    #[test]
331    fn test_and() {
332        let expr = parse_condition("selection and filter").unwrap();
333        assert_eq!(
334            expr,
335            ConditionExpr::And(vec![
336                ConditionExpr::Identifier("selection".to_string()),
337                ConditionExpr::Identifier("filter".to_string()),
338            ])
339        );
340    }
341
342    #[test]
343    fn test_or() {
344        let expr = parse_condition("selection1 or selection2").unwrap();
345        assert_eq!(
346            expr,
347            ConditionExpr::Or(vec![
348                ConditionExpr::Identifier("selection1".to_string()),
349                ConditionExpr::Identifier("selection2".to_string()),
350            ])
351        );
352    }
353
354    #[test]
355    fn test_not() {
356        let expr = parse_condition("not filter").unwrap();
357        assert_eq!(
358            expr,
359            ConditionExpr::Not(Box::new(ConditionExpr::Identifier("filter".to_string())))
360        );
361    }
362
363    #[test]
364    fn test_and_not() {
365        let expr = parse_condition("selection and not filter").unwrap();
366        assert_eq!(
367            expr,
368            ConditionExpr::And(vec![
369                ConditionExpr::Identifier("selection".to_string()),
370                ConditionExpr::Not(Box::new(ConditionExpr::Identifier("filter".to_string()))),
371            ])
372        );
373    }
374
375    #[test]
376    fn test_precedence_not_and_or() {
377        // "a or not b and c" should parse as "a or ((not b) and c)"
378        let expr = parse_condition("a or not b and c").unwrap();
379        assert_eq!(
380            expr,
381            ConditionExpr::Or(vec![
382                ConditionExpr::Identifier("a".to_string()),
383                ConditionExpr::And(vec![
384                    ConditionExpr::Not(Box::new(ConditionExpr::Identifier("b".to_string()))),
385                    ConditionExpr::Identifier("c".to_string()),
386                ]),
387            ])
388        );
389    }
390
391    #[test]
392    fn test_parentheses() {
393        let expr = parse_condition("(a or b) and c").unwrap();
394        assert_eq!(
395            expr,
396            ConditionExpr::And(vec![
397                ConditionExpr::Or(vec![
398                    ConditionExpr::Identifier("a".to_string()),
399                    ConditionExpr::Identifier("b".to_string()),
400                ]),
401                ConditionExpr::Identifier("c".to_string()),
402            ])
403        );
404    }
405
406    #[test]
407    fn test_selector_1_of_pattern() {
408        let expr = parse_condition("1 of selection_*").unwrap();
409        assert_eq!(
410            expr,
411            ConditionExpr::Selector {
412                quantifier: Quantifier::Any,
413                pattern: SelectorPattern::Pattern("selection_*".to_string()),
414            }
415        );
416    }
417
418    #[test]
419    fn test_selector_all_of_them() {
420        let expr = parse_condition("all of them").unwrap();
421        assert_eq!(
422            expr,
423            ConditionExpr::Selector {
424                quantifier: Quantifier::All,
425                pattern: SelectorPattern::Them,
426            }
427        );
428    }
429
430    #[test]
431    fn test_selector_any_of() {
432        let expr = parse_condition("any of selection*").unwrap();
433        assert_eq!(
434            expr,
435            ConditionExpr::Selector {
436                quantifier: Quantifier::Any,
437                pattern: SelectorPattern::Pattern("selection*".to_string()),
438            }
439        );
440    }
441
442    #[test]
443    fn test_complex_condition() {
444        // Real-world: selection_main and 1 of selection_dword_* and not 1 of filter_optional_*
445        let expr = parse_condition(
446            "selection_main and 1 of selection_dword_* and not 1 of filter_optional_*",
447        )
448        .unwrap();
449        assert_eq!(
450            expr,
451            ConditionExpr::And(vec![
452                ConditionExpr::Identifier("selection_main".to_string()),
453                ConditionExpr::Selector {
454                    quantifier: Quantifier::Any,
455                    pattern: SelectorPattern::Pattern("selection_dword_*".to_string()),
456                },
457                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
458                    quantifier: Quantifier::Any,
459                    pattern: SelectorPattern::Pattern("filter_optional_*".to_string()),
460                })),
461            ])
462        );
463    }
464
465    #[test]
466    fn test_identifier_with_keyword_substring() {
467        // "and_filter" should be parsed as an identifier, not "and" + "filter"
468        let expr = parse_condition("selection_and_filter").unwrap();
469        assert_eq!(
470            expr,
471            ConditionExpr::Identifier("selection_and_filter".to_string())
472        );
473    }
474
475    #[test]
476    fn test_identifier_with_hyphen() {
477        let expr = parse_condition("my-selection and my-filter").unwrap();
478        assert_eq!(
479            expr,
480            ConditionExpr::And(vec![
481                ConditionExpr::Identifier("my-selection".to_string()),
482                ConditionExpr::Identifier("my-filter".to_string()),
483            ])
484        );
485    }
486
487    #[test]
488    fn test_triple_and_flattened() {
489        let expr = parse_condition("a and b and c").unwrap();
490        assert_eq!(
491            expr,
492            ConditionExpr::And(vec![
493                ConditionExpr::Identifier("a".to_string()),
494                ConditionExpr::Identifier("b".to_string()),
495                ConditionExpr::Identifier("c".to_string()),
496            ])
497        );
498    }
499
500    #[test]
501    fn test_triple_or_flattened() {
502        let expr = parse_condition("a or b or c").unwrap();
503        assert_eq!(
504            expr,
505            ConditionExpr::Or(vec![
506                ConditionExpr::Identifier("a".to_string()),
507                ConditionExpr::Identifier("b".to_string()),
508                ConditionExpr::Identifier("c".to_string()),
509            ])
510        );
511    }
512
513    #[test]
514    fn test_all_of_selection_and_not_filter() {
515        let expr =
516            parse_condition("all of selection_powershell_* or all of selection_wmic_*").unwrap();
517        assert_eq!(
518            expr,
519            ConditionExpr::Or(vec![
520                ConditionExpr::Selector {
521                    quantifier: Quantifier::All,
522                    pattern: SelectorPattern::Pattern("selection_powershell_*".to_string()),
523                },
524                ConditionExpr::Selector {
525                    quantifier: Quantifier::All,
526                    pattern: SelectorPattern::Pattern("selection_wmic_*".to_string()),
527                },
528            ])
529        );
530    }
531
532    #[test]
533    fn test_real_world_complex() {
534        // From rules: selection_key and (all of selection_powershell_* or all of selection_wmic_*)
535        let expr = parse_condition(
536            "selection_key and (all of selection_powershell_* or all of selection_wmic_*)",
537        )
538        .unwrap();
539        assert_eq!(
540            expr,
541            ConditionExpr::And(vec![
542                ConditionExpr::Identifier("selection_key".to_string()),
543                ConditionExpr::Or(vec![
544                    ConditionExpr::Selector {
545                        quantifier: Quantifier::All,
546                        pattern: SelectorPattern::Pattern("selection_powershell_*".to_string()),
547                    },
548                    ConditionExpr::Selector {
549                        quantifier: Quantifier::All,
550                        pattern: SelectorPattern::Pattern("selection_wmic_*".to_string()),
551                    },
552                ]),
553            ])
554        );
555    }
556
557    #[test]
558    fn test_1_of_them() {
559        let expr = parse_condition("1 of them").unwrap();
560        assert_eq!(
561            expr,
562            ConditionExpr::Selector {
563                quantifier: Quantifier::Any,
564                pattern: SelectorPattern::Them,
565            }
566        );
567    }
568
569    #[test]
570    fn test_nested_error_reported_once() {
571        let input = format!("{}a{}", "(".repeat(70), ")".repeat(70));
572        let message = parse_condition(&input).unwrap_err().to_string();
573        assert_eq!(
574            message.matches("Condition parse error").count(),
575            1,
576            "{message}"
577        );
578        assert_eq!(message.matches("maximum depth").count(), 1, "{message}");
579    }
580
581    #[test]
582    fn test_count_of() {
583        let expr = parse_condition("3 of selection_*").unwrap();
584        assert_eq!(
585            expr,
586            ConditionExpr::Selector {
587                quantifier: Quantifier::Count(NonZeroU64::new(3).unwrap()),
588                pattern: SelectorPattern::Pattern("selection_*".to_string()),
589            }
590        );
591    }
592
593    #[test]
594    fn test_zero_of_rejected() {
595        for input in [
596            "0 of selection_*",
597            "00 of them",
598            "selection and not 0 of filter_*",
599        ] {
600            let err = parse_condition(input).unwrap_err();
601            let SigmaParserError::Condition(message, location) = &err else {
602                panic!("expected a condition error for {input:?}, got {err:?}");
603            };
604            assert!(message.starts_with("'0 of' is always true"), "{message}");
605            let col = input.find('0').unwrap() as u32 + 1;
606            assert_eq!(*location, Some(SourceLocation { line: 1, col }), "{input}");
607        }
608    }
609
610    #[test]
611    fn test_zero_count_not_deserializable() {
612        assert!(serde_json::from_str::<Quantifier>(r#"{"Count":0}"#).is_err());
613        assert_eq!(
614            serde_json::from_str::<Quantifier>(r#"{"Count":2}"#).unwrap(),
615            Quantifier::Count(NonZeroU64::new(2).unwrap())
616        );
617    }
618
619    #[test]
620    fn test_not_1_of_filter() {
621        let expr = parse_condition("selection and not 1 of filter*").unwrap();
622        assert_eq!(
623            expr,
624            ConditionExpr::And(vec![
625                ConditionExpr::Identifier("selection".to_string()),
626                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
627                    quantifier: Quantifier::Any,
628                    pattern: SelectorPattern::Pattern("filter*".to_string()),
629                })),
630            ])
631        );
632    }
633
634    // ── Multi-wildcard selector pattern tests ──────────────────────────────
635
636    #[test]
637    fn test_selector_multi_wildcard_pattern() {
638        let expr = parse_condition("1 of selection_*_*").unwrap();
639        assert_eq!(
640            expr,
641            ConditionExpr::Selector {
642                quantifier: Quantifier::Any,
643                pattern: SelectorPattern::Pattern("selection_*_*".to_string()),
644            }
645        );
646    }
647
648    #[test]
649    fn test_selector_leading_wildcard_pattern() {
650        let expr = parse_condition("all of *_selection_*").unwrap();
651        assert_eq!(
652            expr,
653            ConditionExpr::Selector {
654                quantifier: Quantifier::All,
655                pattern: SelectorPattern::Pattern("*_selection_*".to_string()),
656            }
657        );
658    }
659
660    #[test]
661    fn test_selector_bare_wildcard() {
662        let expr = parse_condition("1 of *").unwrap();
663        assert_eq!(
664            expr,
665            ConditionExpr::Selector {
666                quantifier: Quantifier::Any,
667                pattern: SelectorPattern::Pattern("*".to_string()),
668            }
669        );
670    }
671
672    #[test]
673    fn test_selector_triple_wildcard_segment() {
674        let expr = parse_condition("any of sel_*_*_*").unwrap();
675        assert_eq!(
676            expr,
677            ConditionExpr::Selector {
678                quantifier: Quantifier::Any,
679                pattern: SelectorPattern::Pattern("sel_*_*_*".to_string()),
680            }
681        );
682    }
683
684    #[test]
685    fn test_multi_wildcard_in_complex_condition() {
686        let expr =
687            parse_condition("selection_main and 1 of sel_*_* and not 1 of filter_*_*").unwrap();
688        assert_eq!(
689            expr,
690            ConditionExpr::And(vec![
691                ConditionExpr::Identifier("selection_main".to_string()),
692                ConditionExpr::Selector {
693                    quantifier: Quantifier::Any,
694                    pattern: SelectorPattern::Pattern("sel_*_*".to_string()),
695                },
696                ConditionExpr::Not(Box::new(ConditionExpr::Selector {
697                    quantifier: Quantifier::Any,
698                    pattern: SelectorPattern::Pattern("filter_*_*".to_string()),
699                })),
700            ])
701        );
702    }
703
704    #[test]
705    fn test_selector_wildcard_only_prefix() {
706        let expr = parse_condition("all of *suffix").unwrap();
707        assert_eq!(
708            expr,
709            ConditionExpr::Selector {
710                quantifier: Quantifier::All,
711                pattern: SelectorPattern::Pattern("*suffix".to_string()),
712            }
713        );
714    }
715
716    // ── Malformed condition expression tests ─────────────────────────────
717
718    #[test]
719    fn test_empty_string_fails() {
720        let err = parse_condition("").unwrap_err();
721        assert!(matches!(err, SigmaParserError::Condition(_, _)));
722    }
723
724    #[test]
725    fn test_whitespace_only_fails() {
726        let err = parse_condition("   ").unwrap_err();
727        assert!(matches!(err, SigmaParserError::Condition(_, _)));
728    }
729
730    #[test]
731    fn test_trailing_operator_fails() {
732        let err = parse_condition("selection and").unwrap_err();
733        assert!(matches!(err, SigmaParserError::Condition(_, _)));
734    }
735
736    #[test]
737    fn test_leading_operator_fails() {
738        let err = parse_condition("and selection").unwrap_err();
739        assert!(matches!(err, SigmaParserError::Condition(_, _)));
740    }
741
742    #[test]
743    fn test_double_operator_fails() {
744        let err = parse_condition("selection and and filter").unwrap_err();
745        assert!(matches!(err, SigmaParserError::Condition(_, _)));
746    }
747
748    #[test]
749    fn test_unbalanced_open_paren_fails() {
750        let err = parse_condition("(selection and filter").unwrap_err();
751        assert!(matches!(err, SigmaParserError::Condition(_, _)));
752    }
753
754    #[test]
755    fn test_unbalanced_close_paren_fails() {
756        let err = parse_condition("selection and filter)").unwrap_err();
757        assert!(matches!(err, SigmaParserError::Condition(_, _)));
758    }
759
760    #[test]
761    fn test_empty_parens_fails() {
762        let err = parse_condition("()").unwrap_err();
763        assert!(matches!(err, SigmaParserError::Condition(_, _)));
764    }
765
766    #[test]
767    fn test_only_operator_fails() {
768        let err = parse_condition("and").unwrap_err();
769        assert!(matches!(err, SigmaParserError::Condition(_, _)));
770    }
771
772    #[test]
773    fn test_only_not_fails() {
774        let err = parse_condition("not").unwrap_err();
775        assert!(matches!(err, SigmaParserError::Condition(_, _)));
776    }
777
778    #[test]
779    fn test_or_alone_fails() {
780        let err = parse_condition("or").unwrap_err();
781        assert!(matches!(err, SigmaParserError::Condition(_, _)));
782    }
783
784    #[test]
785    fn test_incomplete_selector_missing_target_fails() {
786        let err = parse_condition("1 of").unwrap_err();
787        assert!(matches!(err, SigmaParserError::Condition(_, _)));
788    }
789
790    #[test]
791    fn test_of_without_quantifier_fails() {
792        let err = parse_condition("of selection_*").unwrap_err();
793        assert!(matches!(err, SigmaParserError::Condition(_, _)));
794    }
795
796    #[test]
797    fn test_pest_error_carries_location() {
798        let err = parse_condition("selection and").unwrap_err();
799        match &err {
800            SigmaParserError::Condition(_, loc) => {
801                assert!(
802                    loc.is_some(),
803                    "pest parse errors should carry source location"
804                );
805            }
806            _ => panic!("Expected Condition error"),
807        }
808    }
809
810    #[test]
811    fn test_invalid_characters_fails() {
812        let err = parse_condition("selection @ filter").unwrap_err();
813        assert!(matches!(err, SigmaParserError::Condition(_, _)));
814    }
815
816    #[test]
817    fn test_nested_empty_parens_fails() {
818        let err = parse_condition("selection and ()").unwrap_err();
819        assert!(matches!(err, SigmaParserError::Condition(_, _)));
820    }
821
822    #[test]
823    fn condition_too_long_returns_error() {
824        let big = "a".repeat(MAX_CONDITION_LEN + 1);
825        let err = parse_condition(&big).unwrap_err();
826        assert!(
827            matches!(err, SigmaParserError::ConditionTooLong(_, _)),
828            "expected ConditionTooLong, got: {err}"
829        );
830    }
831
832    #[test]
833    fn moderate_condition_still_parses() {
834        let expr = parse_condition("((((((((((a and b))))))))))").unwrap();
835        match expr {
836            ConditionExpr::And(children) => assert_eq!(children.len(), 2),
837            other => panic!("expected And, got {other:?}"),
838        }
839    }
840}