rust_rule_engine/parser/
grl.rs

1use crate::engine::rule::{Condition, ConditionGroup, Rule};
2use crate::errors::{Result, RuleEngineError};
3use crate::types::{ActionType, Operator, Value};
4use chrono::{DateTime, Utc};
5use regex::Regex;
6use std::collections::HashMap;
7
8/// GRL (Grule Rule Language) Parser
9/// Parses Grule-like syntax into Rule objects
10pub struct GRLParser;
11
12/// Parsed rule attributes from GRL header
13#[derive(Debug, Default)]
14struct RuleAttributes {
15    pub no_loop: bool,
16    pub lock_on_active: bool,
17    pub agenda_group: Option<String>,
18    pub activation_group: Option<String>,
19    pub date_effective: Option<DateTime<Utc>>,
20    pub date_expires: Option<DateTime<Utc>>,
21}
22
23impl GRLParser {
24    /// Parse a single rule from GRL syntax
25    ///
26    /// Example GRL syntax:
27    /// ```grl
28    /// rule CheckAge "Age verification rule" salience 10 {
29    ///     when
30    ///         User.Age >= 18 && User.Country == "US"
31    ///     then
32    ///         User.IsAdult = true;
33    ///         Retract("User");
34    /// }
35    /// ```
36    pub fn parse_rule(grl_text: &str) -> Result<Rule> {
37        let mut parser = GRLParser;
38        parser.parse_single_rule(grl_text)
39    }
40
41    /// Parse multiple rules from GRL text
42    pub fn parse_rules(grl_text: &str) -> Result<Vec<Rule>> {
43        let mut parser = GRLParser;
44        parser.parse_multiple_rules(grl_text)
45    }
46
47    fn parse_single_rule(&mut self, grl_text: &str) -> Result<Rule> {
48        let cleaned = self.clean_text(grl_text);
49
50        // Extract rule components using regex - support various attributes
51        let rule_regex = Regex::new(r#"rule\s+(?:"([^"]+)"|([a-zA-Z_]\w*))\s*([^{]*)\{(.+)\}"#)
52            .map_err(|e| RuleEngineError::ParseError {
53                message: format!("Invalid rule regex: {}", e),
54            })?;
55
56        let captures =
57            rule_regex
58                .captures(&cleaned)
59                .ok_or_else(|| RuleEngineError::ParseError {
60                    message: format!("Invalid GRL rule format. Input: {}", cleaned),
61                })?;
62
63        // Rule name can be either quoted (group 1) or unquoted (group 2)
64        let rule_name = if let Some(quoted_name) = captures.get(1) {
65            quoted_name.as_str().to_string()
66        } else if let Some(unquoted_name) = captures.get(2) {
67            unquoted_name.as_str().to_string()
68        } else {
69            return Err(RuleEngineError::ParseError {
70                message: "Could not extract rule name".to_string(),
71            });
72        };
73
74        // Attributes section (group 3)
75        let attributes_section = captures.get(3).map(|m| m.as_str()).unwrap_or("");
76
77        // Rule body (group 4)
78        let rule_body = captures.get(4).unwrap().as_str();
79
80        // Parse salience from attributes section
81        let salience = self.extract_salience(attributes_section)?;
82
83        // Parse when and then sections
84        let when_then_regex =
85            Regex::new(r"when\s+(.+?)\s+then\s+(.+)").map_err(|e| RuleEngineError::ParseError {
86                message: format!("Invalid when-then regex: {}", e),
87            })?;
88
89        let when_then_captures =
90            when_then_regex
91                .captures(rule_body)
92                .ok_or_else(|| RuleEngineError::ParseError {
93                    message: "Missing when or then clause".to_string(),
94                })?;
95
96        let when_clause = when_then_captures.get(1).unwrap().as_str().trim();
97        let then_clause = when_then_captures.get(2).unwrap().as_str().trim();
98
99        // Parse conditions and actions
100        let conditions = self.parse_when_clause(when_clause)?;
101        let actions = self.parse_then_clause(then_clause)?;
102
103        // Parse all attributes from rule header
104        let attributes = self.parse_rule_attributes(attributes_section)?;
105
106        // Build rule
107        let mut rule = Rule::new(rule_name, conditions, actions);
108        rule = rule.with_priority(salience);
109
110        // Apply parsed attributes
111        if attributes.no_loop {
112            rule = rule.with_no_loop(true);
113        }
114        if attributes.lock_on_active {
115            rule = rule.with_lock_on_active(true);
116        }
117        if let Some(agenda_group) = attributes.agenda_group {
118            rule = rule.with_agenda_group(agenda_group);
119        }
120        if let Some(activation_group) = attributes.activation_group {
121            rule = rule.with_activation_group(activation_group);
122        }
123        if let Some(date_effective) = attributes.date_effective {
124            rule = rule.with_date_effective(date_effective);
125        }
126        if let Some(date_expires) = attributes.date_expires {
127            rule = rule.with_date_expires(date_expires);
128        }
129
130        Ok(rule)
131    }
132
133    fn parse_multiple_rules(&mut self, grl_text: &str) -> Result<Vec<Rule>> {
134        // Split by rule boundaries - support both quoted and unquoted rule names
135        // Use DOTALL flag to match newlines in rule body
136        let rule_regex =
137            Regex::new(r#"(?s)rule\s+(?:"[^"]+"|[a-zA-Z_]\w*).*?\}"#).map_err(|e| {
138                RuleEngineError::ParseError {
139                    message: format!("Rule splitting regex error: {}", e),
140                }
141            })?;
142
143        let mut rules = Vec::new();
144
145        for rule_match in rule_regex.find_iter(grl_text) {
146            let rule_text = rule_match.as_str();
147            let rule = self.parse_single_rule(rule_text)?;
148            rules.push(rule);
149        }
150
151        Ok(rules)
152    }
153
154    /// Parse rule attributes from the rule header
155    fn parse_rule_attributes(&self, rule_header: &str) -> Result<RuleAttributes> {
156        let mut attributes = RuleAttributes::default();
157
158        // Check for simple boolean attributes
159        if rule_header.contains("no-loop") {
160            attributes.no_loop = true;
161        }
162        if rule_header.contains("lock-on-active") {
163            attributes.lock_on_active = true;
164        }
165
166        // Parse agenda-group attribute
167        if let Some(agenda_group) = self.extract_quoted_attribute(rule_header, "agenda-group")? {
168            attributes.agenda_group = Some(agenda_group);
169        }
170
171        // Parse activation-group attribute
172        if let Some(activation_group) =
173            self.extract_quoted_attribute(rule_header, "activation-group")?
174        {
175            attributes.activation_group = Some(activation_group);
176        }
177
178        // Parse date-effective attribute
179        if let Some(date_str) = self.extract_quoted_attribute(rule_header, "date-effective")? {
180            attributes.date_effective = Some(self.parse_date_string(&date_str)?);
181        }
182
183        // Parse date-expires attribute
184        if let Some(date_str) = self.extract_quoted_attribute(rule_header, "date-expires")? {
185            attributes.date_expires = Some(self.parse_date_string(&date_str)?);
186        }
187
188        Ok(attributes)
189    }
190
191    /// Extract quoted attribute value from rule header
192    fn extract_quoted_attribute(&self, header: &str, attribute: &str) -> Result<Option<String>> {
193        let pattern = format!(r#"{}\s+"([^"]+)""#, attribute);
194        let regex = Regex::new(&pattern).map_err(|e| RuleEngineError::ParseError {
195            message: format!("Invalid attribute regex for {}: {}", attribute, e),
196        })?;
197
198        if let Some(captures) = regex.captures(header) {
199            if let Some(value) = captures.get(1) {
200                return Ok(Some(value.as_str().to_string()));
201            }
202        }
203
204        Ok(None)
205    }
206
207    /// Parse date string in various formats
208    fn parse_date_string(&self, date_str: &str) -> Result<DateTime<Utc>> {
209        // Try ISO 8601 format first
210        if let Ok(date) = DateTime::parse_from_rfc3339(date_str) {
211            return Ok(date.with_timezone(&Utc));
212        }
213
214        // Try simple date formats
215        let formats = ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%d-%b-%Y", "%d-%m-%Y"];
216
217        for format in &formats {
218            if let Ok(naive_date) = chrono::NaiveDateTime::parse_from_str(date_str, format) {
219                return Ok(naive_date.and_utc());
220            }
221            if let Ok(naive_date) = chrono::NaiveDate::parse_from_str(date_str, format) {
222                return Ok(naive_date.and_hms_opt(0, 0, 0).unwrap().and_utc());
223            }
224        }
225
226        Err(RuleEngineError::ParseError {
227            message: format!("Unable to parse date: {}", date_str),
228        })
229    }
230
231    /// Extract salience value from attributes section
232    fn extract_salience(&self, attributes_section: &str) -> Result<i32> {
233        let salience_regex =
234            Regex::new(r"salience\s+(\d+)").map_err(|e| RuleEngineError::ParseError {
235                message: format!("Invalid salience regex: {}", e),
236            })?;
237
238        if let Some(captures) = salience_regex.captures(attributes_section) {
239            if let Some(salience_match) = captures.get(1) {
240                return salience_match.as_str().parse::<i32>().map_err(|e| {
241                    RuleEngineError::ParseError {
242                        message: format!("Invalid salience value: {}", e),
243                    }
244                });
245            }
246        }
247
248        Ok(0) // Default salience
249    }
250
251    fn clean_text(&self, text: &str) -> String {
252        text.lines()
253            .map(|line| line.trim())
254            .filter(|line| !line.is_empty() && !line.starts_with("//"))
255            .collect::<Vec<_>>()
256            .join(" ")
257    }
258
259    fn parse_when_clause(&self, when_clause: &str) -> Result<ConditionGroup> {
260        // Handle logical operators with proper parentheses support
261        let trimmed = when_clause.trim();
262
263        // Strip outer parentheses if they exist
264        let clause = if trimmed.starts_with('(') && trimmed.ends_with(')') {
265            // Check if these are the outermost parentheses
266            let inner = &trimmed[1..trimmed.len() - 1];
267            if self.is_balanced_parentheses(inner) {
268                inner
269            } else {
270                trimmed
271            }
272        } else {
273            trimmed
274        };
275
276        // Parse OR at the top level (lowest precedence)
277        if let Some(parts) = self.split_logical_operator(clause, "||") {
278            return self.parse_or_parts(parts);
279        }
280
281        // Parse AND (higher precedence)
282        if let Some(parts) = self.split_logical_operator(clause, "&&") {
283            return self.parse_and_parts(parts);
284        }
285
286        // Handle NOT condition
287        if clause.trim_start().starts_with("!") {
288            return self.parse_not_condition(clause);
289        }
290
291        // Handle EXISTS condition
292        if clause.trim_start().starts_with("exists(") {
293            return self.parse_exists_condition(clause);
294        }
295
296        // Handle FORALL condition
297        if clause.trim_start().starts_with("forall(") {
298            return self.parse_forall_condition(clause);
299        }
300
301        // Handle ACCUMULATE condition
302        if clause.trim_start().starts_with("accumulate(") {
303            return self.parse_accumulate_condition(clause);
304        }
305
306        // Single condition
307        self.parse_single_condition(clause)
308    }
309
310    fn is_balanced_parentheses(&self, text: &str) -> bool {
311        let mut count = 0;
312        for ch in text.chars() {
313            match ch {
314                '(' => count += 1,
315                ')' => {
316                    count -= 1;
317                    if count < 0 {
318                        return false;
319                    }
320                }
321                _ => {}
322            }
323        }
324        count == 0
325    }
326
327    fn split_logical_operator(&self, clause: &str, operator: &str) -> Option<Vec<String>> {
328        let mut parts = Vec::new();
329        let mut current_part = String::new();
330        let mut paren_count = 0;
331        let mut chars = clause.chars().peekable();
332
333        while let Some(ch) = chars.next() {
334            match ch {
335                '(' => {
336                    paren_count += 1;
337                    current_part.push(ch);
338                }
339                ')' => {
340                    paren_count -= 1;
341                    current_part.push(ch);
342                }
343                '&' if operator == "&&" && paren_count == 0 => {
344                    if chars.peek() == Some(&'&') {
345                        chars.next(); // consume second &
346                        parts.push(current_part.trim().to_string());
347                        current_part.clear();
348                    } else {
349                        current_part.push(ch);
350                    }
351                }
352                '|' if operator == "||" && paren_count == 0 => {
353                    if chars.peek() == Some(&'|') {
354                        chars.next(); // consume second |
355                        parts.push(current_part.trim().to_string());
356                        current_part.clear();
357                    } else {
358                        current_part.push(ch);
359                    }
360                }
361                _ => {
362                    current_part.push(ch);
363                }
364            }
365        }
366
367        if !current_part.trim().is_empty() {
368            parts.push(current_part.trim().to_string());
369        }
370
371        if parts.len() > 1 {
372            Some(parts)
373        } else {
374            None
375        }
376    }
377
378    fn parse_or_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
379        let mut conditions = Vec::new();
380        for part in parts {
381            let condition = self.parse_when_clause(&part)?;
382            conditions.push(condition);
383        }
384
385        if conditions.is_empty() {
386            return Err(RuleEngineError::ParseError {
387                message: "No conditions found in OR".to_string(),
388            });
389        }
390
391        let mut iter = conditions.into_iter();
392        let mut result = iter.next().unwrap();
393        for condition in iter {
394            result = ConditionGroup::or(result, condition);
395        }
396
397        Ok(result)
398    }
399
400    fn parse_and_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
401        let mut conditions = Vec::new();
402        for part in parts {
403            let condition = self.parse_when_clause(&part)?;
404            conditions.push(condition);
405        }
406
407        if conditions.is_empty() {
408            return Err(RuleEngineError::ParseError {
409                message: "No conditions found in AND".to_string(),
410            });
411        }
412
413        let mut iter = conditions.into_iter();
414        let mut result = iter.next().unwrap();
415        for condition in iter {
416            result = ConditionGroup::and(result, condition);
417        }
418
419        Ok(result)
420    }
421
422    fn parse_not_condition(&self, clause: &str) -> Result<ConditionGroup> {
423        let inner_clause = clause.strip_prefix("!").unwrap().trim();
424        let inner_condition = self.parse_when_clause(inner_clause)?;
425        Ok(ConditionGroup::not(inner_condition))
426    }
427
428    fn parse_exists_condition(&self, clause: &str) -> Result<ConditionGroup> {
429        let clause = clause.trim_start();
430        if !clause.starts_with("exists(") || !clause.ends_with(")") {
431            return Err(RuleEngineError::ParseError {
432                message: "Invalid exists syntax. Expected: exists(condition)".to_string(),
433            });
434        }
435
436        // Extract content between parentheses
437        let inner_clause = &clause[7..clause.len() - 1]; // Remove "exists(" and ")"
438        let inner_condition = self.parse_when_clause(inner_clause)?;
439        Ok(ConditionGroup::exists(inner_condition))
440    }
441
442    fn parse_forall_condition(&self, clause: &str) -> Result<ConditionGroup> {
443        let clause = clause.trim_start();
444        if !clause.starts_with("forall(") || !clause.ends_with(")") {
445            return Err(RuleEngineError::ParseError {
446                message: "Invalid forall syntax. Expected: forall(condition)".to_string(),
447            });
448        }
449
450        // Extract content between parentheses
451        let inner_clause = &clause[7..clause.len() - 1]; // Remove "forall(" and ")"
452        let inner_condition = self.parse_when_clause(inner_clause)?;
453        Ok(ConditionGroup::forall(inner_condition))
454    }
455
456    fn parse_accumulate_condition(&self, clause: &str) -> Result<ConditionGroup> {
457        let clause = clause.trim_start();
458        if !clause.starts_with("accumulate(") || !clause.ends_with(")") {
459            return Err(RuleEngineError::ParseError {
460                message: "Invalid accumulate syntax. Expected: accumulate(pattern, function)".to_string(),
461            });
462        }
463
464        // Extract content between parentheses
465        let inner = &clause[11..clause.len() - 1]; // Remove "accumulate(" and ")"
466
467        // Split by comma at the top level (not inside parentheses)
468        let parts = self.split_accumulate_parts(inner)?;
469
470        if parts.len() != 2 {
471            return Err(RuleEngineError::ParseError {
472                message: format!(
473                    "Invalid accumulate syntax. Expected 2 parts (pattern, function), got {}",
474                    parts.len()
475                ),
476            });
477        }
478
479        let pattern_part = parts[0].trim();
480        let function_part = parts[1].trim();
481
482        // Parse the pattern: Order($amount: amount, status == "completed")
483        let (source_pattern, extract_field, source_conditions) =
484            self.parse_accumulate_pattern(pattern_part)?;
485
486        // Parse the function: sum($amount)
487        let (function, function_arg) = self.parse_accumulate_function(function_part)?;
488
489        // For now, we'll create a placeholder result variable
490        // In a full implementation, this would be extracted from the parent context
491        // e.g., from "$total: accumulate(...)"
492        let result_var = "$result".to_string();
493
494        Ok(ConditionGroup::accumulate(
495            result_var,
496            source_pattern,
497            extract_field,
498            source_conditions,
499            function,
500            function_arg,
501        ))
502    }
503
504    fn split_accumulate_parts(&self, content: &str) -> Result<Vec<String>> {
505        let mut parts = Vec::new();
506        let mut current = String::new();
507        let mut paren_depth = 0;
508
509        for ch in content.chars() {
510            match ch {
511                '(' => {
512                    paren_depth += 1;
513                    current.push(ch);
514                }
515                ')' => {
516                    paren_depth -= 1;
517                    current.push(ch);
518                }
519                ',' if paren_depth == 0 => {
520                    parts.push(current.trim().to_string());
521                    current.clear();
522                }
523                _ => {
524                    current.push(ch);
525                }
526            }
527        }
528
529        if !current.trim().is_empty() {
530            parts.push(current.trim().to_string());
531        }
532
533        Ok(parts)
534    }
535
536    fn parse_accumulate_pattern(&self, pattern: &str) -> Result<(String, String, Vec<String>)> {
537        // Pattern format: Order($amount: amount, status == "completed", category == "electronics")
538        // We need to extract:
539        // - source_pattern: "Order"
540        // - extract_field: "amount" (from $amount: amount)
541        // - source_conditions: ["status == \"completed\"", "category == \"electronics\""]
542
543        let pattern = pattern.trim();
544
545        // Find the opening parenthesis to get the pattern type
546        let paren_pos = pattern.find('(').ok_or_else(|| RuleEngineError::ParseError {
547            message: format!("Invalid accumulate pattern: missing '(' in '{}'", pattern),
548        })?;
549
550        let source_pattern = pattern[..paren_pos].trim().to_string();
551
552        // Extract content between parentheses
553        if !pattern.ends_with(')') {
554            return Err(RuleEngineError::ParseError {
555                message: format!("Invalid accumulate pattern: missing ')' in '{}'", pattern),
556            });
557        }
558
559        let inner = &pattern[paren_pos + 1..pattern.len() - 1];
560
561        // Split by comma (respecting nested parentheses and quotes)
562        let parts = self.split_pattern_parts(inner)?;
563
564        let mut extract_field = String::new();
565        let mut source_conditions = Vec::new();
566
567        for part in parts {
568            let part = part.trim();
569
570            // Check if this is a variable binding: $var: field
571            if part.contains(':') && part.starts_with('$') {
572                let colon_pos = part.find(':').unwrap();
573                let _var_name = part[..colon_pos].trim();
574                let field_name = part[colon_pos + 1..].trim();
575                extract_field = field_name.to_string();
576            } else if part.contains("==") || part.contains("!=") ||
577                      part.contains(">=") || part.contains("<=") ||
578                      part.contains('>') || part.contains('<') {
579                // This is a condition
580                source_conditions.push(part.to_string());
581            }
582        }
583
584        Ok((source_pattern, extract_field, source_conditions))
585    }
586
587    fn split_pattern_parts(&self, content: &str) -> Result<Vec<String>> {
588        let mut parts = Vec::new();
589        let mut current = String::new();
590        let mut paren_depth = 0;
591        let mut in_quotes = false;
592        let mut quote_char = ' ';
593
594        for ch in content.chars() {
595            match ch {
596                '"' | '\'' if !in_quotes => {
597                    in_quotes = true;
598                    quote_char = ch;
599                    current.push(ch);
600                }
601                '"' | '\'' if in_quotes && ch == quote_char => {
602                    in_quotes = false;
603                    current.push(ch);
604                }
605                '(' if !in_quotes => {
606                    paren_depth += 1;
607                    current.push(ch);
608                }
609                ')' if !in_quotes => {
610                    paren_depth -= 1;
611                    current.push(ch);
612                }
613                ',' if !in_quotes && paren_depth == 0 => {
614                    parts.push(current.trim().to_string());
615                    current.clear();
616                }
617                _ => {
618                    current.push(ch);
619                }
620            }
621        }
622
623        if !current.trim().is_empty() {
624            parts.push(current.trim().to_string());
625        }
626
627        Ok(parts)
628    }
629
630    fn parse_accumulate_function(&self, function_str: &str) -> Result<(String, String)> {
631        // Function format: sum($amount) or count() or average($price)
632
633        let function_str = function_str.trim();
634
635        let paren_pos = function_str.find('(').ok_or_else(|| RuleEngineError::ParseError {
636            message: format!("Invalid accumulate function: missing '(' in '{}'", function_str),
637        })?;
638
639        let function_name = function_str[..paren_pos].trim().to_string();
640
641        if !function_str.ends_with(')') {
642            return Err(RuleEngineError::ParseError {
643                message: format!("Invalid accumulate function: missing ')' in '{}'", function_str),
644            });
645        }
646
647        let args = &function_str[paren_pos + 1..function_str.len() - 1];
648        let function_arg = args.trim().to_string();
649
650        Ok((function_name, function_arg))
651    }
652
653    fn parse_single_condition(&self, clause: &str) -> Result<ConditionGroup> {
654        // Remove outer parentheses if they exist (handle new syntax like "(user.age >= 18)")
655        let trimmed_clause = clause.trim();
656        let clause_to_parse = if trimmed_clause.starts_with('(') && trimmed_clause.ends_with(')') {
657            trimmed_clause[1..trimmed_clause.len() - 1].trim()
658        } else {
659            trimmed_clause
660        };
661
662        // Handle Test CE: test(functionName(args...))
663        // This is a CLIPS-inspired feature for arbitrary boolean expressions
664        let test_regex = Regex::new(r#"^test\s*\(\s*([a-zA-Z_]\w*)\s*\(([^)]*)\)\s*\)$"#)
665            .map_err(|e| RuleEngineError::ParseError {
666                message: format!("Test CE regex error: {}", e),
667            })?;
668
669        if let Some(captures) = test_regex.captures(clause_to_parse) {
670            let function_name = captures.get(1).unwrap().as_str().to_string();
671            let args_str = captures.get(2).unwrap().as_str();
672
673            // Parse arguments
674            let args: Vec<String> = if args_str.trim().is_empty() {
675                Vec::new()
676            } else {
677                args_str
678                    .split(',')
679                    .map(|arg| arg.trim().to_string())
680                    .collect()
681            };
682
683            let condition = Condition::with_test(function_name, args);
684            return Ok(ConditionGroup::single(condition));
685        }
686
687        // Handle typed object conditions like: $TestCar : TestCarClass( speedUp == true && speed < maxSpeed )
688        let typed_object_regex =
689            Regex::new(r#"\$(\w+)\s*:\s*(\w+)\s*\(\s*(.+?)\s*\)"#).map_err(|e| {
690                RuleEngineError::ParseError {
691                    message: format!("Typed object regex error: {}", e),
692                }
693            })?;
694
695        if let Some(captures) = typed_object_regex.captures(clause_to_parse) {
696            let _object_name = captures.get(1).unwrap().as_str();
697            let _object_type = captures.get(2).unwrap().as_str();
698            let conditions_str = captures.get(3).unwrap().as_str();
699
700            // Parse conditions inside parentheses
701            return self.parse_conditions_within_object(conditions_str);
702        }
703
704        // Try to parse function call pattern: functionName(arg1, arg2, ...) operator value
705        let function_regex = Regex::new(
706            r#"([a-zA-Z_]\w*)\s*\(([^)]*)\)\s*(>=|<=|==|!=|>|<|contains|matches)\s*(.+)"#,
707        )
708        .map_err(|e| RuleEngineError::ParseError {
709            message: format!("Function regex error: {}", e),
710        })?;
711
712        if let Some(captures) = function_regex.captures(clause_to_parse) {
713            let function_name = captures.get(1).unwrap().as_str().to_string();
714            let args_str = captures.get(2).unwrap().as_str();
715            let operator_str = captures.get(3).unwrap().as_str();
716            let value_str = captures.get(4).unwrap().as_str().trim();
717
718            // Parse arguments
719            let args: Vec<String> = if args_str.trim().is_empty() {
720                Vec::new()
721            } else {
722                args_str
723                    .split(',')
724                    .map(|arg| arg.trim().to_string())
725                    .collect()
726            };
727
728            let operator =
729                Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
730                    operator: operator_str.to_string(),
731                })?;
732
733            let value = self.parse_value(value_str)?;
734
735            let condition = Condition::with_function(function_name, args, operator, value);
736            return Ok(ConditionGroup::single(condition));
737        }
738
739        // Parse expressions like: User.Age >= 18, Product.Price < 100.0, user.age >= 18, etc.
740        // Support both PascalCase (User.Age) and lowercase (user.age) field naming
741        let condition_regex = Regex::new(
742            r#"([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\s*(>=|<=|==|!=|>|<|contains|matches)\s*(.+)"#,
743        )
744        .map_err(|e| RuleEngineError::ParseError {
745            message: format!("Condition regex error: {}", e),
746        })?;
747
748        let captures = condition_regex.captures(clause_to_parse).ok_or_else(|| {
749            RuleEngineError::ParseError {
750                message: format!("Invalid condition format: {}", clause_to_parse),
751            }
752        })?;
753
754        let field = captures.get(1).unwrap().as_str().to_string();
755        let operator_str = captures.get(2).unwrap().as_str();
756        let value_str = captures.get(3).unwrap().as_str().trim();
757
758        let operator =
759            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
760                operator: operator_str.to_string(),
761            })?;
762
763        let value = self.parse_value(value_str)?;
764
765        let condition = Condition::new(field, operator, value);
766        Ok(ConditionGroup::single(condition))
767    }
768
769    fn parse_conditions_within_object(&self, conditions_str: &str) -> Result<ConditionGroup> {
770        // Parse conditions like: speedUp == true && speed < maxSpeed
771        let parts: Vec<&str> = conditions_str.split("&&").collect();
772
773        let mut conditions = Vec::new();
774        for part in parts {
775            let trimmed = part.trim();
776            let condition = self.parse_simple_condition(trimmed)?;
777            conditions.push(condition);
778        }
779
780        // Combine with AND
781        if conditions.is_empty() {
782            return Err(RuleEngineError::ParseError {
783                message: "No conditions found".to_string(),
784            });
785        }
786
787        let mut iter = conditions.into_iter();
788        let mut result = iter.next().unwrap();
789        for condition in iter {
790            result = ConditionGroup::and(result, condition);
791        }
792
793        Ok(result)
794    }
795
796    fn parse_simple_condition(&self, clause: &str) -> Result<ConditionGroup> {
797        // Parse simple condition like: speedUp == true or speed < maxSpeed
798        let condition_regex = Regex::new(r#"(\w+)\s*(>=|<=|==|!=|>|<)\s*(.+)"#).map_err(|e| {
799            RuleEngineError::ParseError {
800                message: format!("Simple condition regex error: {}", e),
801            }
802        })?;
803
804        let captures =
805            condition_regex
806                .captures(clause)
807                .ok_or_else(|| RuleEngineError::ParseError {
808                    message: format!("Invalid simple condition format: {}", clause),
809                })?;
810
811        let field = captures.get(1).unwrap().as_str().to_string();
812        let operator_str = captures.get(2).unwrap().as_str();
813        let value_str = captures.get(3).unwrap().as_str().trim();
814
815        let operator =
816            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
817                operator: operator_str.to_string(),
818            })?;
819
820        let value = self.parse_value(value_str)?;
821
822        let condition = Condition::new(field, operator, value);
823        Ok(ConditionGroup::single(condition))
824    }
825
826    fn parse_value(&self, value_str: &str) -> Result<Value> {
827        let trimmed = value_str.trim();
828
829        // String literal
830        if (trimmed.starts_with('"') && trimmed.ends_with('"'))
831            || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
832        {
833            let unquoted = &trimmed[1..trimmed.len() - 1];
834            return Ok(Value::String(unquoted.to_string()));
835        }
836
837        // Boolean
838        if trimmed.eq_ignore_ascii_case("true") {
839            return Ok(Value::Boolean(true));
840        }
841        if trimmed.eq_ignore_ascii_case("false") {
842            return Ok(Value::Boolean(false));
843        }
844
845        // Null
846        if trimmed.eq_ignore_ascii_case("null") {
847            return Ok(Value::Null);
848        }
849
850        // Number (try integer first, then float)
851        if let Ok(int_val) = trimmed.parse::<i64>() {
852            return Ok(Value::Integer(int_val));
853        }
854
855        if let Ok(float_val) = trimmed.parse::<f64>() {
856            return Ok(Value::Number(float_val));
857        }
858
859        // Field reference (like User.Name)
860        if trimmed.contains('.') {
861            return Ok(Value::String(trimmed.to_string()));
862        }
863
864        // Default to string
865        Ok(Value::String(trimmed.to_string()))
866    }
867
868    fn parse_then_clause(&self, then_clause: &str) -> Result<Vec<ActionType>> {
869        let statements: Vec<&str> = then_clause
870            .split(';')
871            .map(|s| s.trim())
872            .filter(|s| !s.is_empty())
873            .collect();
874
875        let mut actions = Vec::new();
876
877        for statement in statements {
878            let action = self.parse_action_statement(statement)?;
879            actions.push(action);
880        }
881
882        Ok(actions)
883    }
884
885    fn parse_action_statement(&self, statement: &str) -> Result<ActionType> {
886        let trimmed = statement.trim();
887
888        // Method call: $Object.method(args)
889        let method_regex = Regex::new(r#"\$(\w+)\.(\w+)\s*\(([^)]*)\)"#).map_err(|e| {
890            RuleEngineError::ParseError {
891                message: format!("Method regex error: {}", e),
892            }
893        })?;
894
895        if let Some(captures) = method_regex.captures(trimmed) {
896            let object = captures.get(1).unwrap().as_str().to_string();
897            let method = captures.get(2).unwrap().as_str().to_string();
898            let args_str = captures.get(3).unwrap().as_str();
899
900            let args = if args_str.trim().is_empty() {
901                Vec::new()
902            } else {
903                self.parse_method_args(args_str)?
904            };
905
906            return Ok(ActionType::MethodCall {
907                object,
908                method,
909                args,
910            });
911        }
912
913        // Assignment: Field = Value
914        if let Some(eq_pos) = trimmed.find('=') {
915            let field = trimmed[..eq_pos].trim().to_string();
916            let value_str = trimmed[eq_pos + 1..].trim();
917            let value = self.parse_value(value_str)?;
918
919            return Ok(ActionType::Set { field, value });
920        }
921
922        // Function calls: update($Object), retract($Object), etc.
923        let func_regex =
924            Regex::new(r#"(\w+)\s*\(\s*(.+?)?\s*\)"#).map_err(|e| RuleEngineError::ParseError {
925                message: format!("Function regex error: {}", e),
926            })?;
927
928        if let Some(captures) = func_regex.captures(trimmed) {
929            let function_name = captures.get(1).unwrap().as_str();
930            let args_str = captures.get(2).map(|m| m.as_str()).unwrap_or("");
931
932            match function_name.to_lowercase().as_str() {
933                "update" => {
934                    // Extract object name from $Object
935                    let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
936                        stripped.to_string()
937                    } else {
938                        args_str.to_string()
939                    };
940                    Ok(ActionType::Update {
941                        object: object_name,
942                    })
943                }
944                "log" => {
945                    let message = if args_str.is_empty() {
946                        "Log message".to_string()
947                    } else {
948                        let value = self.parse_value(args_str.trim())?;
949                        value.to_string()
950                    };
951                    Ok(ActionType::Log { message })
952                }
953                "activateagendagroup" | "activate_agenda_group" => {
954                    let agenda_group = if args_str.is_empty() {
955                        return Err(RuleEngineError::ParseError {
956                            message: "ActivateAgendaGroup requires agenda group name".to_string(),
957                        });
958                    } else {
959                        let value = self.parse_value(args_str.trim())?;
960                        match value {
961                            Value::String(s) => s,
962                            _ => value.to_string(),
963                        }
964                    };
965                    Ok(ActionType::ActivateAgendaGroup {
966                        group: agenda_group,
967                    })
968                }
969                "schedulerule" | "schedule_rule" => {
970                    // Parse delay and target rule: ScheduleRule(5000, "next-rule")
971                    let parts: Vec<&str> = args_str.split(',').collect();
972                    if parts.len() != 2 {
973                        return Err(RuleEngineError::ParseError {
974                            message: "ScheduleRule requires delay_ms and rule_name".to_string(),
975                        });
976                    }
977
978                    let delay_ms = self.parse_value(parts[0].trim())?;
979                    let rule_name = self.parse_value(parts[1].trim())?;
980
981                    let delay_ms = match delay_ms {
982                        Value::Integer(i) => i as u64,
983                        Value::Number(f) => f as u64,
984                        _ => {
985                            return Err(RuleEngineError::ParseError {
986                                message: "ScheduleRule delay_ms must be a number".to_string(),
987                            })
988                        }
989                    };
990
991                    let rule_name = match rule_name {
992                        Value::String(s) => s,
993                        _ => rule_name.to_string(),
994                    };
995
996                    Ok(ActionType::ScheduleRule {
997                        delay_ms,
998                        rule_name,
999                    })
1000                }
1001                "completeworkflow" | "complete_workflow" => {
1002                    let workflow_id = if args_str.is_empty() {
1003                        return Err(RuleEngineError::ParseError {
1004                            message: "CompleteWorkflow requires workflow_id".to_string(),
1005                        });
1006                    } else {
1007                        let value = self.parse_value(args_str.trim())?;
1008                        match value {
1009                            Value::String(s) => s,
1010                            _ => value.to_string(),
1011                        }
1012                    };
1013                    Ok(ActionType::CompleteWorkflow {
1014                        workflow_name: workflow_id,
1015                    })
1016                }
1017                "setworkflowdata" | "set_workflow_data" => {
1018                    // Parse key=value: SetWorkflowData("key=value")
1019                    let data_str = args_str.trim();
1020
1021                    // Simple key=value parsing
1022                    let (key, value) = if let Some(eq_pos) = data_str.find('=') {
1023                        let key = data_str[..eq_pos].trim().trim_matches('"');
1024                        let value_str = data_str[eq_pos + 1..].trim();
1025                        let value = self.parse_value(value_str)?;
1026                        (key.to_string(), value)
1027                    } else {
1028                        return Err(RuleEngineError::ParseError {
1029                            message: "SetWorkflowData data must be in key=value format".to_string(),
1030                        });
1031                    };
1032
1033                    Ok(ActionType::SetWorkflowData { key, value })
1034                }
1035                _ => {
1036                    // All other functions become custom actions
1037                    let params = if args_str.is_empty() {
1038                        HashMap::new()
1039                    } else {
1040                        self.parse_function_args_as_params(args_str)?
1041                    };
1042
1043                    Ok(ActionType::Custom {
1044                        action_type: function_name.to_string(),
1045                        params,
1046                    })
1047                }
1048            }
1049        } else {
1050            // Custom statement
1051            Ok(ActionType::Custom {
1052                action_type: "statement".to_string(),
1053                params: {
1054                    let mut params = HashMap::new();
1055                    params.insert("statement".to_string(), Value::String(trimmed.to_string()));
1056                    params
1057                },
1058            })
1059        }
1060    }
1061
1062    fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
1063        if args_str.trim().is_empty() {
1064            return Ok(Vec::new());
1065        }
1066
1067        // Handle expressions like: $TestCar.Speed + $TestCar.SpeedIncrement
1068        let mut args = Vec::new();
1069        let parts: Vec<&str> = args_str.split(',').collect();
1070
1071        for part in parts {
1072            let trimmed = part.trim();
1073
1074            // Handle arithmetic expressions
1075            if trimmed.contains('+')
1076                || trimmed.contains('-')
1077                || trimmed.contains('*')
1078                || trimmed.contains('/')
1079            {
1080                // For now, store as string - the engine will evaluate
1081                args.push(Value::String(trimmed.to_string()));
1082            } else {
1083                args.push(self.parse_value(trimmed)?);
1084            }
1085        }
1086
1087        Ok(args)
1088    }
1089
1090    /// Parse function arguments as parameters for custom actions
1091    fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
1092        let mut params = HashMap::new();
1093
1094        if args_str.trim().is_empty() {
1095            return Ok(params);
1096        }
1097
1098        // Parse positional parameters as numbered args
1099        let parts: Vec<&str> = args_str.split(',').collect();
1100        for (i, part) in parts.iter().enumerate() {
1101            let trimmed = part.trim();
1102            let value = self.parse_value(trimmed)?;
1103
1104            // Use simple numeric indexing - engine will resolve references dynamically
1105            params.insert(i.to_string(), value);
1106        }
1107
1108        Ok(params)
1109    }
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114    use super::GRLParser;
1115
1116    #[test]
1117    fn test_parse_simple_rule() {
1118        let grl = r#"
1119        rule "CheckAge" salience 10 {
1120            when
1121                User.Age >= 18
1122            then
1123                log("User is adult");
1124        }
1125        "#;
1126
1127        let rules = GRLParser::parse_rules(grl).unwrap();
1128        assert_eq!(rules.len(), 1);
1129        let rule = &rules[0];
1130        assert_eq!(rule.name, "CheckAge");
1131        assert_eq!(rule.salience, 10);
1132        assert_eq!(rule.actions.len(), 1);
1133    }
1134
1135    #[test]
1136    fn test_parse_complex_condition() {
1137        let grl = r#"
1138        rule "ComplexRule" {
1139            when
1140                User.Age >= 18 && User.Country == "US"
1141            then
1142                User.Qualified = true;
1143        }
1144        "#;
1145
1146        let rules = GRLParser::parse_rules(grl).unwrap();
1147        assert_eq!(rules.len(), 1);
1148        let rule = &rules[0];
1149        assert_eq!(rule.name, "ComplexRule");
1150    }
1151
1152    #[test]
1153    fn test_parse_new_syntax_with_parentheses() {
1154        let grl = r#"
1155        rule "Default Rule" salience 10 {
1156            when
1157                (user.age >= 18)
1158            then
1159                set(user.status, "approved");
1160        }
1161        "#;
1162
1163        let rules = GRLParser::parse_rules(grl).unwrap();
1164        assert_eq!(rules.len(), 1);
1165        let rule = &rules[0];
1166        assert_eq!(rule.name, "Default Rule");
1167        assert_eq!(rule.salience, 10);
1168        assert_eq!(rule.actions.len(), 1);
1169
1170        // Check that the action is parsed as a Custom action (set is now custom)
1171        match &rule.actions[0] {
1172            crate::types::ActionType::Custom {
1173                action_type,
1174                params,
1175            } => {
1176                assert_eq!(action_type, "set");
1177                assert_eq!(
1178                    params.get("0"),
1179                    Some(&crate::types::Value::String("user.status".to_string()))
1180                );
1181                assert_eq!(
1182                    params.get("1"),
1183                    Some(&crate::types::Value::String("approved".to_string()))
1184                );
1185            }
1186            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1187        }
1188    }
1189
1190    #[test]
1191    fn test_parse_complex_nested_conditions() {
1192        let grl = r#"
1193        rule "Complex Business Rule" salience 10 {
1194            when
1195                (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
1196            then
1197                apply_discount(20000);
1198        }
1199        "#;
1200
1201        let rules = GRLParser::parse_rules(grl).unwrap();
1202        assert_eq!(rules.len(), 1);
1203        let rule = &rules[0];
1204        assert_eq!(rule.name, "Complex Business Rule");
1205        assert_eq!(rule.salience, 10);
1206        assert_eq!(rule.actions.len(), 1);
1207
1208        // Check that the action is parsed as a Custom action (apply_discount is now custom)
1209        match &rule.actions[0] {
1210            crate::types::ActionType::Custom {
1211                action_type,
1212                params,
1213            } => {
1214                assert_eq!(action_type, "apply_discount");
1215                assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
1216            }
1217            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1218        }
1219    }
1220
1221    #[test]
1222    fn test_parse_no_loop_attribute() {
1223        let grl = r#"
1224        rule "NoLoopRule" no-loop salience 15 {
1225            when
1226                User.Score < 100
1227            then
1228                set(User.Score, User.Score + 10);
1229        }
1230        "#;
1231
1232        let rules = GRLParser::parse_rules(grl).unwrap();
1233        assert_eq!(rules.len(), 1);
1234        let rule = &rules[0];
1235        assert_eq!(rule.name, "NoLoopRule");
1236        assert_eq!(rule.salience, 15);
1237        assert!(rule.no_loop, "Rule should have no-loop=true");
1238    }
1239
1240    #[test]
1241    fn test_parse_no_loop_different_positions() {
1242        // Test no-loop before salience
1243        let grl1 = r#"
1244        rule "Rule1" no-loop salience 10 {
1245            when User.Age >= 18
1246            then log("adult");
1247        }
1248        "#;
1249
1250        // Test no-loop after salience
1251        let grl2 = r#"
1252        rule "Rule2" salience 10 no-loop {
1253            when User.Age >= 18
1254            then log("adult");
1255        }
1256        "#;
1257
1258        let rules1 = GRLParser::parse_rules(grl1).unwrap();
1259        let rules2 = GRLParser::parse_rules(grl2).unwrap();
1260
1261        assert_eq!(rules1.len(), 1);
1262        assert_eq!(rules2.len(), 1);
1263
1264        assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
1265        assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
1266
1267        assert_eq!(rules1[0].salience, 10);
1268        assert_eq!(rules2[0].salience, 10);
1269    }
1270
1271    #[test]
1272    fn test_parse_without_no_loop() {
1273        let grl = r#"
1274        rule "RegularRule" salience 5 {
1275            when
1276                User.Active == true
1277            then
1278                log("active user");
1279        }
1280        "#;
1281
1282        let rules = GRLParser::parse_rules(grl).unwrap();
1283        assert_eq!(rules.len(), 1);
1284        let rule = &rules[0];
1285        assert_eq!(rule.name, "RegularRule");
1286        assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1287    }
1288
1289    #[test]
1290    fn test_parse_exists_pattern() {
1291        let grl = r#"
1292        rule "ExistsRule" salience 20 {
1293            when
1294                exists(Customer.tier == "VIP")
1295            then
1296                System.premiumActive = true;
1297        }
1298        "#;
1299
1300        let rules = GRLParser::parse_rules(grl).unwrap();
1301        assert_eq!(rules.len(), 1);
1302        let rule = &rules[0];
1303        assert_eq!(rule.name, "ExistsRule");
1304        assert_eq!(rule.salience, 20);
1305
1306        // Check that condition is EXISTS pattern
1307        match &rule.conditions {
1308            crate::engine::rule::ConditionGroup::Exists(_) => {
1309                // Test passes
1310            }
1311            _ => panic!(
1312                "Expected EXISTS condition group, got: {:?}",
1313                rule.conditions
1314            ),
1315        }
1316    }
1317
1318    #[test]
1319    fn test_parse_forall_pattern() {
1320        let grl = r#"
1321        rule "ForallRule" salience 15 {
1322            when
1323                forall(Order.status == "processed")
1324            then
1325                Shipping.enabled = true;
1326        }
1327        "#;
1328
1329        let rules = GRLParser::parse_rules(grl).unwrap();
1330        assert_eq!(rules.len(), 1);
1331        let rule = &rules[0];
1332        assert_eq!(rule.name, "ForallRule");
1333
1334        // Check that condition is FORALL pattern
1335        match &rule.conditions {
1336            crate::engine::rule::ConditionGroup::Forall(_) => {
1337                // Test passes
1338            }
1339            _ => panic!(
1340                "Expected FORALL condition group, got: {:?}",
1341                rule.conditions
1342            ),
1343        }
1344    }
1345
1346    #[test]
1347    fn test_parse_combined_patterns() {
1348        let grl = r#"
1349        rule "CombinedRule" salience 25 {
1350            when
1351                exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1352            then
1353                System.vipMode = true;
1354        }
1355        "#;
1356
1357        let rules = GRLParser::parse_rules(grl).unwrap();
1358        assert_eq!(rules.len(), 1);
1359        let rule = &rules[0];
1360        assert_eq!(rule.name, "CombinedRule");
1361
1362        // Check that condition is AND with EXISTS and NOT(EXISTS) patterns
1363        match &rule.conditions {
1364            crate::engine::rule::ConditionGroup::Compound {
1365                left,
1366                operator,
1367                right,
1368            } => {
1369                assert_eq!(*operator, crate::types::LogicalOperator::And);
1370
1371                // Left should be EXISTS
1372                match left.as_ref() {
1373                    crate::engine::rule::ConditionGroup::Exists(_) => {
1374                        // Expected
1375                    }
1376                    _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1377                }
1378
1379                // Right should be NOT(EXISTS)
1380                match right.as_ref() {
1381                    crate::engine::rule::ConditionGroup::Not(inner) => {
1382                        match inner.as_ref() {
1383                            crate::engine::rule::ConditionGroup::Exists(_) => {
1384                                // Expected
1385                            }
1386                            _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1387                        }
1388                    }
1389                    _ => panic!("Expected NOT in right side, got: {:?}", right),
1390                }
1391            }
1392            _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1393        }
1394    }
1395}