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                "retract" => {
945                    // Extract object name from $Object
946                    let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
947                        stripped.to_string()
948                    } else {
949                        args_str.to_string()
950                    };
951                    Ok(ActionType::Retract {
952                        object: object_name,
953                    })
954                }
955                "log" => {
956                    let message = if args_str.is_empty() {
957                        "Log message".to_string()
958                    } else {
959                        let value = self.parse_value(args_str.trim())?;
960                        value.to_string()
961                    };
962                    Ok(ActionType::Log { message })
963                }
964                "activateagendagroup" | "activate_agenda_group" => {
965                    let agenda_group = if args_str.is_empty() {
966                        return Err(RuleEngineError::ParseError {
967                            message: "ActivateAgendaGroup requires agenda group name".to_string(),
968                        });
969                    } else {
970                        let value = self.parse_value(args_str.trim())?;
971                        match value {
972                            Value::String(s) => s,
973                            _ => value.to_string(),
974                        }
975                    };
976                    Ok(ActionType::ActivateAgendaGroup {
977                        group: agenda_group,
978                    })
979                }
980                "schedulerule" | "schedule_rule" => {
981                    // Parse delay and target rule: ScheduleRule(5000, "next-rule")
982                    let parts: Vec<&str> = args_str.split(',').collect();
983                    if parts.len() != 2 {
984                        return Err(RuleEngineError::ParseError {
985                            message: "ScheduleRule requires delay_ms and rule_name".to_string(),
986                        });
987                    }
988
989                    let delay_ms = self.parse_value(parts[0].trim())?;
990                    let rule_name = self.parse_value(parts[1].trim())?;
991
992                    let delay_ms = match delay_ms {
993                        Value::Integer(i) => i as u64,
994                        Value::Number(f) => f as u64,
995                        _ => {
996                            return Err(RuleEngineError::ParseError {
997                                message: "ScheduleRule delay_ms must be a number".to_string(),
998                            })
999                        }
1000                    };
1001
1002                    let rule_name = match rule_name {
1003                        Value::String(s) => s,
1004                        _ => rule_name.to_string(),
1005                    };
1006
1007                    Ok(ActionType::ScheduleRule {
1008                        delay_ms,
1009                        rule_name,
1010                    })
1011                }
1012                "completeworkflow" | "complete_workflow" => {
1013                    let workflow_id = if args_str.is_empty() {
1014                        return Err(RuleEngineError::ParseError {
1015                            message: "CompleteWorkflow requires workflow_id".to_string(),
1016                        });
1017                    } else {
1018                        let value = self.parse_value(args_str.trim())?;
1019                        match value {
1020                            Value::String(s) => s,
1021                            _ => value.to_string(),
1022                        }
1023                    };
1024                    Ok(ActionType::CompleteWorkflow {
1025                        workflow_name: workflow_id,
1026                    })
1027                }
1028                "setworkflowdata" | "set_workflow_data" => {
1029                    // Parse key=value: SetWorkflowData("key=value")
1030                    let data_str = args_str.trim();
1031
1032                    // Simple key=value parsing
1033                    let (key, value) = if let Some(eq_pos) = data_str.find('=') {
1034                        let key = data_str[..eq_pos].trim().trim_matches('"');
1035                        let value_str = data_str[eq_pos + 1..].trim();
1036                        let value = self.parse_value(value_str)?;
1037                        (key.to_string(), value)
1038                    } else {
1039                        return Err(RuleEngineError::ParseError {
1040                            message: "SetWorkflowData data must be in key=value format".to_string(),
1041                        });
1042                    };
1043
1044                    Ok(ActionType::SetWorkflowData { key, value })
1045                }
1046                _ => {
1047                    // All other functions become custom actions
1048                    let params = if args_str.is_empty() {
1049                        HashMap::new()
1050                    } else {
1051                        self.parse_function_args_as_params(args_str)?
1052                    };
1053
1054                    Ok(ActionType::Custom {
1055                        action_type: function_name.to_string(),
1056                        params,
1057                    })
1058                }
1059            }
1060        } else {
1061            // Custom statement
1062            Ok(ActionType::Custom {
1063                action_type: "statement".to_string(),
1064                params: {
1065                    let mut params = HashMap::new();
1066                    params.insert("statement".to_string(), Value::String(trimmed.to_string()));
1067                    params
1068                },
1069            })
1070        }
1071    }
1072
1073    fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
1074        if args_str.trim().is_empty() {
1075            return Ok(Vec::new());
1076        }
1077
1078        // Handle expressions like: $TestCar.Speed + $TestCar.SpeedIncrement
1079        let mut args = Vec::new();
1080        let parts: Vec<&str> = args_str.split(',').collect();
1081
1082        for part in parts {
1083            let trimmed = part.trim();
1084
1085            // Handle arithmetic expressions
1086            if trimmed.contains('+')
1087                || trimmed.contains('-')
1088                || trimmed.contains('*')
1089                || trimmed.contains('/')
1090            {
1091                // For now, store as string - the engine will evaluate
1092                args.push(Value::String(trimmed.to_string()));
1093            } else {
1094                args.push(self.parse_value(trimmed)?);
1095            }
1096        }
1097
1098        Ok(args)
1099    }
1100
1101    /// Parse function arguments as parameters for custom actions
1102    fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
1103        let mut params = HashMap::new();
1104
1105        if args_str.trim().is_empty() {
1106            return Ok(params);
1107        }
1108
1109        // Parse positional parameters as numbered args
1110        let parts: Vec<&str> = args_str.split(',').collect();
1111        for (i, part) in parts.iter().enumerate() {
1112            let trimmed = part.trim();
1113            let value = self.parse_value(trimmed)?;
1114
1115            // Use simple numeric indexing - engine will resolve references dynamically
1116            params.insert(i.to_string(), value);
1117        }
1118
1119        Ok(params)
1120    }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use super::GRLParser;
1126
1127    #[test]
1128    fn test_parse_simple_rule() {
1129        let grl = r#"
1130        rule "CheckAge" salience 10 {
1131            when
1132                User.Age >= 18
1133            then
1134                log("User is adult");
1135        }
1136        "#;
1137
1138        let rules = GRLParser::parse_rules(grl).unwrap();
1139        assert_eq!(rules.len(), 1);
1140        let rule = &rules[0];
1141        assert_eq!(rule.name, "CheckAge");
1142        assert_eq!(rule.salience, 10);
1143        assert_eq!(rule.actions.len(), 1);
1144    }
1145
1146    #[test]
1147    fn test_parse_complex_condition() {
1148        let grl = r#"
1149        rule "ComplexRule" {
1150            when
1151                User.Age >= 18 && User.Country == "US"
1152            then
1153                User.Qualified = true;
1154        }
1155        "#;
1156
1157        let rules = GRLParser::parse_rules(grl).unwrap();
1158        assert_eq!(rules.len(), 1);
1159        let rule = &rules[0];
1160        assert_eq!(rule.name, "ComplexRule");
1161    }
1162
1163    #[test]
1164    fn test_parse_new_syntax_with_parentheses() {
1165        let grl = r#"
1166        rule "Default Rule" salience 10 {
1167            when
1168                (user.age >= 18)
1169            then
1170                set(user.status, "approved");
1171        }
1172        "#;
1173
1174        let rules = GRLParser::parse_rules(grl).unwrap();
1175        assert_eq!(rules.len(), 1);
1176        let rule = &rules[0];
1177        assert_eq!(rule.name, "Default Rule");
1178        assert_eq!(rule.salience, 10);
1179        assert_eq!(rule.actions.len(), 1);
1180
1181        // Check that the action is parsed as a Custom action (set is now custom)
1182        match &rule.actions[0] {
1183            crate::types::ActionType::Custom {
1184                action_type,
1185                params,
1186            } => {
1187                assert_eq!(action_type, "set");
1188                assert_eq!(
1189                    params.get("0"),
1190                    Some(&crate::types::Value::String("user.status".to_string()))
1191                );
1192                assert_eq!(
1193                    params.get("1"),
1194                    Some(&crate::types::Value::String("approved".to_string()))
1195                );
1196            }
1197            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1198        }
1199    }
1200
1201    #[test]
1202    fn test_parse_complex_nested_conditions() {
1203        let grl = r#"
1204        rule "Complex Business Rule" salience 10 {
1205            when
1206                (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
1207            then
1208                apply_discount(20000);
1209        }
1210        "#;
1211
1212        let rules = GRLParser::parse_rules(grl).unwrap();
1213        assert_eq!(rules.len(), 1);
1214        let rule = &rules[0];
1215        assert_eq!(rule.name, "Complex Business Rule");
1216        assert_eq!(rule.salience, 10);
1217        assert_eq!(rule.actions.len(), 1);
1218
1219        // Check that the action is parsed as a Custom action (apply_discount is now custom)
1220        match &rule.actions[0] {
1221            crate::types::ActionType::Custom {
1222                action_type,
1223                params,
1224            } => {
1225                assert_eq!(action_type, "apply_discount");
1226                assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
1227            }
1228            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1229        }
1230    }
1231
1232    #[test]
1233    fn test_parse_no_loop_attribute() {
1234        let grl = r#"
1235        rule "NoLoopRule" no-loop salience 15 {
1236            when
1237                User.Score < 100
1238            then
1239                set(User.Score, User.Score + 10);
1240        }
1241        "#;
1242
1243        let rules = GRLParser::parse_rules(grl).unwrap();
1244        assert_eq!(rules.len(), 1);
1245        let rule = &rules[0];
1246        assert_eq!(rule.name, "NoLoopRule");
1247        assert_eq!(rule.salience, 15);
1248        assert!(rule.no_loop, "Rule should have no-loop=true");
1249    }
1250
1251    #[test]
1252    fn test_parse_no_loop_different_positions() {
1253        // Test no-loop before salience
1254        let grl1 = r#"
1255        rule "Rule1" no-loop salience 10 {
1256            when User.Age >= 18
1257            then log("adult");
1258        }
1259        "#;
1260
1261        // Test no-loop after salience
1262        let grl2 = r#"
1263        rule "Rule2" salience 10 no-loop {
1264            when User.Age >= 18
1265            then log("adult");
1266        }
1267        "#;
1268
1269        let rules1 = GRLParser::parse_rules(grl1).unwrap();
1270        let rules2 = GRLParser::parse_rules(grl2).unwrap();
1271
1272        assert_eq!(rules1.len(), 1);
1273        assert_eq!(rules2.len(), 1);
1274
1275        assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
1276        assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
1277
1278        assert_eq!(rules1[0].salience, 10);
1279        assert_eq!(rules2[0].salience, 10);
1280    }
1281
1282    #[test]
1283    fn test_parse_without_no_loop() {
1284        let grl = r#"
1285        rule "RegularRule" salience 5 {
1286            when
1287                User.Active == true
1288            then
1289                log("active user");
1290        }
1291        "#;
1292
1293        let rules = GRLParser::parse_rules(grl).unwrap();
1294        assert_eq!(rules.len(), 1);
1295        let rule = &rules[0];
1296        assert_eq!(rule.name, "RegularRule");
1297        assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1298    }
1299
1300    #[test]
1301    fn test_parse_exists_pattern() {
1302        let grl = r#"
1303        rule "ExistsRule" salience 20 {
1304            when
1305                exists(Customer.tier == "VIP")
1306            then
1307                System.premiumActive = true;
1308        }
1309        "#;
1310
1311        let rules = GRLParser::parse_rules(grl).unwrap();
1312        assert_eq!(rules.len(), 1);
1313        let rule = &rules[0];
1314        assert_eq!(rule.name, "ExistsRule");
1315        assert_eq!(rule.salience, 20);
1316
1317        // Check that condition is EXISTS pattern
1318        match &rule.conditions {
1319            crate::engine::rule::ConditionGroup::Exists(_) => {
1320                // Test passes
1321            }
1322            _ => panic!(
1323                "Expected EXISTS condition group, got: {:?}",
1324                rule.conditions
1325            ),
1326        }
1327    }
1328
1329    #[test]
1330    fn test_parse_forall_pattern() {
1331        let grl = r#"
1332        rule "ForallRule" salience 15 {
1333            when
1334                forall(Order.status == "processed")
1335            then
1336                Shipping.enabled = true;
1337        }
1338        "#;
1339
1340        let rules = GRLParser::parse_rules(grl).unwrap();
1341        assert_eq!(rules.len(), 1);
1342        let rule = &rules[0];
1343        assert_eq!(rule.name, "ForallRule");
1344
1345        // Check that condition is FORALL pattern
1346        match &rule.conditions {
1347            crate::engine::rule::ConditionGroup::Forall(_) => {
1348                // Test passes
1349            }
1350            _ => panic!(
1351                "Expected FORALL condition group, got: {:?}",
1352                rule.conditions
1353            ),
1354        }
1355    }
1356
1357    #[test]
1358    fn test_parse_combined_patterns() {
1359        let grl = r#"
1360        rule "CombinedRule" salience 25 {
1361            when
1362                exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1363            then
1364                System.vipMode = true;
1365        }
1366        "#;
1367
1368        let rules = GRLParser::parse_rules(grl).unwrap();
1369        assert_eq!(rules.len(), 1);
1370        let rule = &rules[0];
1371        assert_eq!(rule.name, "CombinedRule");
1372
1373        // Check that condition is AND with EXISTS and NOT(EXISTS) patterns
1374        match &rule.conditions {
1375            crate::engine::rule::ConditionGroup::Compound {
1376                left,
1377                operator,
1378                right,
1379            } => {
1380                assert_eq!(*operator, crate::types::LogicalOperator::And);
1381
1382                // Left should be EXISTS
1383                match left.as_ref() {
1384                    crate::engine::rule::ConditionGroup::Exists(_) => {
1385                        // Expected
1386                    }
1387                    _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1388                }
1389
1390                // Right should be NOT(EXISTS)
1391                match right.as_ref() {
1392                    crate::engine::rule::ConditionGroup::Not(inner) => {
1393                        match inner.as_ref() {
1394                            crate::engine::rule::ConditionGroup::Exists(_) => {
1395                                // Expected
1396                            }
1397                            _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1398                        }
1399                    }
1400                    _ => panic!("Expected NOT in right side, got: {:?}", right),
1401                }
1402            }
1403            _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1404        }
1405    }
1406}