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        // Single condition
302        self.parse_single_condition(clause)
303    }
304
305    fn is_balanced_parentheses(&self, text: &str) -> bool {
306        let mut count = 0;
307        for ch in text.chars() {
308            match ch {
309                '(' => count += 1,
310                ')' => {
311                    count -= 1;
312                    if count < 0 {
313                        return false;
314                    }
315                }
316                _ => {}
317            }
318        }
319        count == 0
320    }
321
322    fn split_logical_operator(&self, clause: &str, operator: &str) -> Option<Vec<String>> {
323        let mut parts = Vec::new();
324        let mut current_part = String::new();
325        let mut paren_count = 0;
326        let mut chars = clause.chars().peekable();
327
328        while let Some(ch) = chars.next() {
329            match ch {
330                '(' => {
331                    paren_count += 1;
332                    current_part.push(ch);
333                }
334                ')' => {
335                    paren_count -= 1;
336                    current_part.push(ch);
337                }
338                '&' if operator == "&&" && paren_count == 0 => {
339                    if chars.peek() == Some(&'&') {
340                        chars.next(); // consume second &
341                        parts.push(current_part.trim().to_string());
342                        current_part.clear();
343                    } else {
344                        current_part.push(ch);
345                    }
346                }
347                '|' if operator == "||" && paren_count == 0 => {
348                    if chars.peek() == Some(&'|') {
349                        chars.next(); // consume second |
350                        parts.push(current_part.trim().to_string());
351                        current_part.clear();
352                    } else {
353                        current_part.push(ch);
354                    }
355                }
356                _ => {
357                    current_part.push(ch);
358                }
359            }
360        }
361
362        if !current_part.trim().is_empty() {
363            parts.push(current_part.trim().to_string());
364        }
365
366        if parts.len() > 1 {
367            Some(parts)
368        } else {
369            None
370        }
371    }
372
373    fn parse_or_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
374        let mut conditions = Vec::new();
375        for part in parts {
376            let condition = self.parse_when_clause(&part)?;
377            conditions.push(condition);
378        }
379
380        if conditions.is_empty() {
381            return Err(RuleEngineError::ParseError {
382                message: "No conditions found in OR".to_string(),
383            });
384        }
385
386        let mut iter = conditions.into_iter();
387        let mut result = iter.next().unwrap();
388        for condition in iter {
389            result = ConditionGroup::or(result, condition);
390        }
391
392        Ok(result)
393    }
394
395    fn parse_and_parts(&self, parts: Vec<String>) -> Result<ConditionGroup> {
396        let mut conditions = Vec::new();
397        for part in parts {
398            let condition = self.parse_when_clause(&part)?;
399            conditions.push(condition);
400        }
401
402        if conditions.is_empty() {
403            return Err(RuleEngineError::ParseError {
404                message: "No conditions found in AND".to_string(),
405            });
406        }
407
408        let mut iter = conditions.into_iter();
409        let mut result = iter.next().unwrap();
410        for condition in iter {
411            result = ConditionGroup::and(result, condition);
412        }
413
414        Ok(result)
415    }
416
417    fn parse_not_condition(&self, clause: &str) -> Result<ConditionGroup> {
418        let inner_clause = clause.strip_prefix("!").unwrap().trim();
419        let inner_condition = self.parse_when_clause(inner_clause)?;
420        Ok(ConditionGroup::not(inner_condition))
421    }
422
423    fn parse_exists_condition(&self, clause: &str) -> Result<ConditionGroup> {
424        let clause = clause.trim_start();
425        if !clause.starts_with("exists(") || !clause.ends_with(")") {
426            return Err(RuleEngineError::ParseError {
427                message: "Invalid exists syntax. Expected: exists(condition)".to_string(),
428            });
429        }
430
431        // Extract content between parentheses
432        let inner_clause = &clause[7..clause.len() - 1]; // Remove "exists(" and ")"
433        let inner_condition = self.parse_when_clause(inner_clause)?;
434        Ok(ConditionGroup::exists(inner_condition))
435    }
436
437    fn parse_forall_condition(&self, clause: &str) -> Result<ConditionGroup> {
438        let clause = clause.trim_start();
439        if !clause.starts_with("forall(") || !clause.ends_with(")") {
440            return Err(RuleEngineError::ParseError {
441                message: "Invalid forall syntax. Expected: forall(condition)".to_string(),
442            });
443        }
444
445        // Extract content between parentheses
446        let inner_clause = &clause[7..clause.len() - 1]; // Remove "forall(" and ")"
447        let inner_condition = self.parse_when_clause(inner_clause)?;
448        Ok(ConditionGroup::forall(inner_condition))
449    }
450
451    fn parse_single_condition(&self, clause: &str) -> Result<ConditionGroup> {
452        // Remove outer parentheses if they exist (handle new syntax like "(user.age >= 18)")
453        let trimmed_clause = clause.trim();
454        let clause_to_parse = if trimmed_clause.starts_with('(') && trimmed_clause.ends_with(')') {
455            trimmed_clause[1..trimmed_clause.len() - 1].trim()
456        } else {
457            trimmed_clause
458        };
459
460        // Handle typed object conditions like: $TestCar : TestCarClass( speedUp == true && speed < maxSpeed )
461        let typed_object_regex =
462            Regex::new(r#"\$(\w+)\s*:\s*(\w+)\s*\(\s*(.+?)\s*\)"#).map_err(|e| {
463                RuleEngineError::ParseError {
464                    message: format!("Typed object regex error: {}", e),
465                }
466            })?;
467
468        if let Some(captures) = typed_object_regex.captures(clause_to_parse) {
469            let _object_name = captures.get(1).unwrap().as_str();
470            let _object_type = captures.get(2).unwrap().as_str();
471            let conditions_str = captures.get(3).unwrap().as_str();
472
473            // Parse conditions inside parentheses
474            return self.parse_conditions_within_object(conditions_str);
475        }
476
477        // Parse expressions like: User.Age >= 18, Product.Price < 100.0, user.age >= 18, etc.
478        // Support both PascalCase (User.Age) and lowercase (user.age) field naming
479        let condition_regex = Regex::new(
480            r#"([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\s*(>=|<=|==|!=|>|<|contains|matches)\s*(.+)"#,
481        )
482        .map_err(|e| RuleEngineError::ParseError {
483            message: format!("Condition regex error: {}", e),
484        })?;
485
486        let captures = condition_regex.captures(clause_to_parse).ok_or_else(|| {
487            RuleEngineError::ParseError {
488                message: format!("Invalid condition format: {}", clause_to_parse),
489            }
490        })?;
491
492        let field = captures.get(1).unwrap().as_str().to_string();
493        let operator_str = captures.get(2).unwrap().as_str();
494        let value_str = captures.get(3).unwrap().as_str().trim();
495
496        let operator =
497            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
498                operator: operator_str.to_string(),
499            })?;
500
501        let value = self.parse_value(value_str)?;
502
503        let condition = Condition::new(field, operator, value);
504        Ok(ConditionGroup::single(condition))
505    }
506
507    fn parse_conditions_within_object(&self, conditions_str: &str) -> Result<ConditionGroup> {
508        // Parse conditions like: speedUp == true && speed < maxSpeed
509        let parts: Vec<&str> = conditions_str.split("&&").collect();
510
511        let mut conditions = Vec::new();
512        for part in parts {
513            let trimmed = part.trim();
514            let condition = self.parse_simple_condition(trimmed)?;
515            conditions.push(condition);
516        }
517
518        // Combine with AND
519        if conditions.is_empty() {
520            return Err(RuleEngineError::ParseError {
521                message: "No conditions found".to_string(),
522            });
523        }
524
525        let mut iter = conditions.into_iter();
526        let mut result = iter.next().unwrap();
527        for condition in iter {
528            result = ConditionGroup::and(result, condition);
529        }
530
531        Ok(result)
532    }
533
534    fn parse_simple_condition(&self, clause: &str) -> Result<ConditionGroup> {
535        // Parse simple condition like: speedUp == true or speed < maxSpeed
536        let condition_regex = Regex::new(r#"(\w+)\s*(>=|<=|==|!=|>|<)\s*(.+)"#).map_err(|e| {
537            RuleEngineError::ParseError {
538                message: format!("Simple condition regex error: {}", e),
539            }
540        })?;
541
542        let captures =
543            condition_regex
544                .captures(clause)
545                .ok_or_else(|| RuleEngineError::ParseError {
546                    message: format!("Invalid simple condition format: {}", clause),
547                })?;
548
549        let field = captures.get(1).unwrap().as_str().to_string();
550        let operator_str = captures.get(2).unwrap().as_str();
551        let value_str = captures.get(3).unwrap().as_str().trim();
552
553        let operator =
554            Operator::from_str(operator_str).ok_or_else(|| RuleEngineError::InvalidOperator {
555                operator: operator_str.to_string(),
556            })?;
557
558        let value = self.parse_value(value_str)?;
559
560        let condition = Condition::new(field, operator, value);
561        Ok(ConditionGroup::single(condition))
562    }
563
564    fn parse_value(&self, value_str: &str) -> Result<Value> {
565        let trimmed = value_str.trim();
566
567        // String literal
568        if (trimmed.starts_with('"') && trimmed.ends_with('"'))
569            || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
570        {
571            let unquoted = &trimmed[1..trimmed.len() - 1];
572            return Ok(Value::String(unquoted.to_string()));
573        }
574
575        // Boolean
576        if trimmed.eq_ignore_ascii_case("true") {
577            return Ok(Value::Boolean(true));
578        }
579        if trimmed.eq_ignore_ascii_case("false") {
580            return Ok(Value::Boolean(false));
581        }
582
583        // Null
584        if trimmed.eq_ignore_ascii_case("null") {
585            return Ok(Value::Null);
586        }
587
588        // Number (try integer first, then float)
589        if let Ok(int_val) = trimmed.parse::<i64>() {
590            return Ok(Value::Integer(int_val));
591        }
592
593        if let Ok(float_val) = trimmed.parse::<f64>() {
594            return Ok(Value::Number(float_val));
595        }
596
597        // Field reference (like User.Name)
598        if trimmed.contains('.') {
599            return Ok(Value::String(trimmed.to_string()));
600        }
601
602        // Default to string
603        Ok(Value::String(trimmed.to_string()))
604    }
605
606    fn parse_then_clause(&self, then_clause: &str) -> Result<Vec<ActionType>> {
607        let statements: Vec<&str> = then_clause
608            .split(';')
609            .map(|s| s.trim())
610            .filter(|s| !s.is_empty())
611            .collect();
612
613        let mut actions = Vec::new();
614
615        for statement in statements {
616            let action = self.parse_action_statement(statement)?;
617            actions.push(action);
618        }
619
620        Ok(actions)
621    }
622
623    fn parse_action_statement(&self, statement: &str) -> Result<ActionType> {
624        let trimmed = statement.trim();
625
626        // Method call: $Object.method(args)
627        let method_regex = Regex::new(r#"\$(\w+)\.(\w+)\s*\(([^)]*)\)"#).map_err(|e| {
628            RuleEngineError::ParseError {
629                message: format!("Method regex error: {}", e),
630            }
631        })?;
632
633        if let Some(captures) = method_regex.captures(trimmed) {
634            let object = captures.get(1).unwrap().as_str().to_string();
635            let method = captures.get(2).unwrap().as_str().to_string();
636            let args_str = captures.get(3).unwrap().as_str();
637
638            let args = if args_str.trim().is_empty() {
639                Vec::new()
640            } else {
641                self.parse_method_args(args_str)?
642            };
643
644            return Ok(ActionType::MethodCall {
645                object,
646                method,
647                args,
648            });
649        }
650
651        // Assignment: Field = Value
652        if let Some(eq_pos) = trimmed.find('=') {
653            let field = trimmed[..eq_pos].trim().to_string();
654            let value_str = trimmed[eq_pos + 1..].trim();
655            let value = self.parse_value(value_str)?;
656
657            return Ok(ActionType::Set { field, value });
658        }
659
660        // Function calls: update($Object), retract($Object), etc.
661        let func_regex =
662            Regex::new(r#"(\w+)\s*\(\s*(.+?)?\s*\)"#).map_err(|e| RuleEngineError::ParseError {
663                message: format!("Function regex error: {}", e),
664            })?;
665
666        if let Some(captures) = func_regex.captures(trimmed) {
667            let function_name = captures.get(1).unwrap().as_str();
668            let args_str = captures.get(2).map(|m| m.as_str()).unwrap_or("");
669
670            match function_name.to_lowercase().as_str() {
671                "update" => {
672                    // Extract object name from $Object
673                    let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
674                        stripped.to_string()
675                    } else {
676                        args_str.to_string()
677                    };
678                    Ok(ActionType::Update {
679                        object: object_name,
680                    })
681                }
682                "log" => {
683                    let message = if args_str.is_empty() {
684                        "Log message".to_string()
685                    } else {
686                        let value = self.parse_value(args_str.trim())?;
687                        value.to_string()
688                    };
689                    Ok(ActionType::Log { message })
690                }
691                "activateagendagroup" | "activate_agenda_group" => {
692                    let agenda_group = if args_str.is_empty() {
693                        return Err(RuleEngineError::ParseError {
694                            message: "ActivateAgendaGroup requires agenda group name".to_string(),
695                        });
696                    } else {
697                        let value = self.parse_value(args_str.trim())?;
698                        match value {
699                            Value::String(s) => s,
700                            _ => value.to_string(),
701                        }
702                    };
703                    Ok(ActionType::ActivateAgendaGroup { group: agenda_group })
704                }
705                "schedulerule" | "schedule_rule" => {
706                    // Parse delay and target rule: ScheduleRule(5000, "next-rule")
707                    let parts: Vec<&str> = args_str.split(',').collect();
708                    if parts.len() != 2 {
709                        return Err(RuleEngineError::ParseError {
710                            message: "ScheduleRule requires delay_ms and rule_name".to_string(),
711                        });
712                    }
713                    
714                    let delay_ms = self.parse_value(parts[0].trim())?;
715                    let rule_name = self.parse_value(parts[1].trim())?;
716                    
717                    let delay_ms = match delay_ms {
718                        Value::Integer(i) => i as u64,
719                        Value::Number(f) => f as u64,
720                        _ => return Err(RuleEngineError::ParseError {
721                            message: "ScheduleRule delay_ms must be a number".to_string(),
722                        }),
723                    };
724                    
725                    let rule_name = match rule_name {
726                        Value::String(s) => s,
727                        _ => rule_name.to_string(),
728                    };
729                    
730                    Ok(ActionType::ScheduleRule { delay_ms, rule_name })
731                }
732                "completeworkflow" | "complete_workflow" => {
733                    let workflow_id = if args_str.is_empty() {
734                        return Err(RuleEngineError::ParseError {
735                            message: "CompleteWorkflow requires workflow_id".to_string(),
736                        });
737                    } else {
738                        let value = self.parse_value(args_str.trim())?;
739                        match value {
740                            Value::String(s) => s,
741                            _ => value.to_string(),
742                        }
743                    };
744                    Ok(ActionType::CompleteWorkflow { workflow_name: workflow_id })
745                }
746                "setworkflowdata" | "set_workflow_data" => {
747                    // Parse key=value: SetWorkflowData("key=value")
748                    let data_str = args_str.trim();
749                    
750                    // Simple key=value parsing
751                    let (key, value) = if let Some(eq_pos) = data_str.find('=') {
752                        let key = data_str[..eq_pos].trim().trim_matches('"');
753                        let value_str = data_str[eq_pos + 1..].trim();
754                        let value = self.parse_value(value_str)?;
755                        (key.to_string(), value)
756                    } else {
757                        return Err(RuleEngineError::ParseError {
758                            message: "SetWorkflowData data must be in key=value format".to_string(),
759                        });
760                    };
761                    
762                    Ok(ActionType::SetWorkflowData { key, value })
763                }
764                _ => {
765                    // All other functions become custom actions
766                    let params = if args_str.is_empty() {
767                        HashMap::new()
768                    } else {
769                        self.parse_function_args_as_params(args_str)?
770                    };
771                    
772                    Ok(ActionType::Custom {
773                        action_type: function_name.to_string(),
774                        params,
775                    })
776                }
777            }
778        } else {
779            // Custom statement
780            Ok(ActionType::Custom {
781                action_type: "statement".to_string(),
782                params: {
783                    let mut params = HashMap::new();
784                    params.insert("statement".to_string(), Value::String(trimmed.to_string()));
785                    params
786                },
787            })
788        }
789    }
790
791    fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
792        if args_str.trim().is_empty() {
793            return Ok(Vec::new());
794        }
795
796        // Handle expressions like: $TestCar.Speed + $TestCar.SpeedIncrement
797        let mut args = Vec::new();
798        let parts: Vec<&str> = args_str.split(',').collect();
799
800        for part in parts {
801            let trimmed = part.trim();
802
803            // Handle arithmetic expressions
804            if trimmed.contains('+')
805                || trimmed.contains('-')
806                || trimmed.contains('*')
807                || trimmed.contains('/')
808            {
809                // For now, store as string - the engine will evaluate
810                args.push(Value::String(trimmed.to_string()));
811            } else {
812                args.push(self.parse_value(trimmed)?);
813            }
814        }
815
816        Ok(args)
817    }
818
819    /// Parse function arguments as parameters for custom actions
820    fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
821        let mut params = HashMap::new();
822
823        if args_str.trim().is_empty() {
824            return Ok(params);
825        }
826
827        // Parse positional parameters as numbered args
828        let parts: Vec<&str> = args_str.split(',').collect();
829        for (i, part) in parts.iter().enumerate() {
830            let trimmed = part.trim();
831            let value = self.parse_value(trimmed)?;
832            
833            // Use simple numeric indexing - engine will resolve references dynamically
834            params.insert(i.to_string(), value);
835        }
836
837        Ok(params)
838    }
839}
840
841#[cfg(test)]
842mod tests {
843    use super::GRLParser;
844
845    #[test]
846    fn test_parse_simple_rule() {
847        let grl = r#"
848        rule "CheckAge" salience 10 {
849            when
850                User.Age >= 18
851            then
852                log("User is adult");
853        }
854        "#;
855
856        let rules = GRLParser::parse_rules(grl).unwrap();
857        assert_eq!(rules.len(), 1);
858        let rule = &rules[0];
859        assert_eq!(rule.name, "CheckAge");
860        assert_eq!(rule.salience, 10);
861        assert_eq!(rule.actions.len(), 1);
862    }
863
864    #[test]
865    fn test_parse_complex_condition() {
866        let grl = r#"
867        rule "ComplexRule" {
868            when
869                User.Age >= 18 && User.Country == "US"
870            then
871                User.Qualified = true;
872        }
873        "#;
874
875        let rules = GRLParser::parse_rules(grl).unwrap();
876        assert_eq!(rules.len(), 1);
877        let rule = &rules[0];
878        assert_eq!(rule.name, "ComplexRule");
879    }
880
881    #[test]
882    fn test_parse_new_syntax_with_parentheses() {
883        let grl = r#"
884        rule "Default Rule" salience 10 {
885            when
886                (user.age >= 18)
887            then
888                set(user.status, "approved");
889        }
890        "#;
891
892        let rules = GRLParser::parse_rules(grl).unwrap();
893        assert_eq!(rules.len(), 1);
894        let rule = &rules[0];
895        assert_eq!(rule.name, "Default Rule");
896        assert_eq!(rule.salience, 10);
897        assert_eq!(rule.actions.len(), 1);
898
899        // Check that the action is parsed as a Custom action (set is now custom)
900        match &rule.actions[0] {
901            crate::types::ActionType::Custom { action_type, params } => {
902                assert_eq!(action_type, "set");
903                assert_eq!(params.get("0"), Some(&crate::types::Value::String("user.status".to_string())));
904                assert_eq!(params.get("1"), Some(&crate::types::Value::String("approved".to_string())));
905            }
906            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
907        }
908    }
909
910    #[test]
911    fn test_parse_complex_nested_conditions() {
912        let grl = r#"
913        rule "Complex Business Rule" salience 10 {
914            when
915                (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
916            then
917                apply_discount(20000);
918        }
919        "#;
920
921        let rules = GRLParser::parse_rules(grl).unwrap();
922        assert_eq!(rules.len(), 1);
923        let rule = &rules[0];
924        assert_eq!(rule.name, "Complex Business Rule");
925        assert_eq!(rule.salience, 10);
926        assert_eq!(rule.actions.len(), 1);
927
928        // Check that the action is parsed as a Custom action (apply_discount is now custom)
929        match &rule.actions[0] {
930            crate::types::ActionType::Custom { action_type, params } => {
931                assert_eq!(action_type, "apply_discount");
932                assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
933            }
934            _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
935        }
936    }
937
938    #[test]
939    fn test_parse_no_loop_attribute() {
940        let grl = r#"
941        rule "NoLoopRule" no-loop salience 15 {
942            when
943                User.Score < 100
944            then
945                set(User.Score, User.Score + 10);
946        }
947        "#;
948
949        let rules = GRLParser::parse_rules(grl).unwrap();
950        assert_eq!(rules.len(), 1);
951        let rule = &rules[0];
952        assert_eq!(rule.name, "NoLoopRule");
953        assert_eq!(rule.salience, 15);
954        assert!(rule.no_loop, "Rule should have no-loop=true");
955    }
956
957    #[test]
958    fn test_parse_no_loop_different_positions() {
959        // Test no-loop before salience
960        let grl1 = r#"
961        rule "Rule1" no-loop salience 10 {
962            when User.Age >= 18
963            then log("adult");
964        }
965        "#;
966
967        // Test no-loop after salience
968        let grl2 = r#"
969        rule "Rule2" salience 10 no-loop {
970            when User.Age >= 18
971            then log("adult");
972        }
973        "#;
974
975        let rules1 = GRLParser::parse_rules(grl1).unwrap();
976        let rules2 = GRLParser::parse_rules(grl2).unwrap();
977
978        assert_eq!(rules1.len(), 1);
979        assert_eq!(rules2.len(), 1);
980
981        assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
982        assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
983
984        assert_eq!(rules1[0].salience, 10);
985        assert_eq!(rules2[0].salience, 10);
986    }
987
988    #[test]
989    fn test_parse_without_no_loop() {
990        let grl = r#"
991        rule "RegularRule" salience 5 {
992            when
993                User.Active == true
994            then
995                log("active user");
996        }
997        "#;
998
999        let rules = GRLParser::parse_rules(grl).unwrap();
1000        assert_eq!(rules.len(), 1);
1001        let rule = &rules[0];
1002        assert_eq!(rule.name, "RegularRule");
1003        assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1004    }
1005
1006    #[test]
1007    fn test_parse_exists_pattern() {
1008        let grl = r#"
1009        rule "ExistsRule" salience 20 {
1010            when
1011                exists(Customer.tier == "VIP")
1012            then
1013                System.premiumActive = true;
1014        }
1015        "#;
1016
1017        let rules = GRLParser::parse_rules(grl).unwrap();
1018        assert_eq!(rules.len(), 1);
1019        let rule = &rules[0];
1020        assert_eq!(rule.name, "ExistsRule");
1021        assert_eq!(rule.salience, 20);
1022
1023        // Check that condition is EXISTS pattern
1024        match &rule.conditions {
1025            crate::engine::rule::ConditionGroup::Exists(_) => {
1026                // Test passes
1027            }
1028            _ => panic!(
1029                "Expected EXISTS condition group, got: {:?}",
1030                rule.conditions
1031            ),
1032        }
1033    }
1034
1035    #[test]
1036    fn test_parse_forall_pattern() {
1037        let grl = r#"
1038        rule "ForallRule" salience 15 {
1039            when
1040                forall(Order.status == "processed")
1041            then
1042                Shipping.enabled = true;
1043        }
1044        "#;
1045
1046        let rules = GRLParser::parse_rules(grl).unwrap();
1047        assert_eq!(rules.len(), 1);
1048        let rule = &rules[0];
1049        assert_eq!(rule.name, "ForallRule");
1050
1051        // Check that condition is FORALL pattern
1052        match &rule.conditions {
1053            crate::engine::rule::ConditionGroup::Forall(_) => {
1054                // Test passes
1055            }
1056            _ => panic!(
1057                "Expected FORALL condition group, got: {:?}",
1058                rule.conditions
1059            ),
1060        }
1061    }
1062
1063    #[test]
1064    fn test_parse_combined_patterns() {
1065        let grl = r#"
1066        rule "CombinedRule" salience 25 {
1067            when
1068                exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1069            then
1070                System.vipMode = true;
1071        }
1072        "#;
1073
1074        let rules = GRLParser::parse_rules(grl).unwrap();
1075        assert_eq!(rules.len(), 1);
1076        let rule = &rules[0];
1077        assert_eq!(rule.name, "CombinedRule");
1078
1079        // Check that condition is AND with EXISTS and NOT(EXISTS) patterns
1080        match &rule.conditions {
1081            crate::engine::rule::ConditionGroup::Compound {
1082                left,
1083                operator,
1084                right,
1085            } => {
1086                assert_eq!(*operator, crate::types::LogicalOperator::And);
1087
1088                // Left should be EXISTS
1089                match left.as_ref() {
1090                    crate::engine::rule::ConditionGroup::Exists(_) => {
1091                        // Expected
1092                    }
1093                    _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1094                }
1095
1096                // Right should be NOT(EXISTS)
1097                match right.as_ref() {
1098                    crate::engine::rule::ConditionGroup::Not(inner) => {
1099                        match inner.as_ref() {
1100                            crate::engine::rule::ConditionGroup::Exists(_) => {
1101                                // Expected
1102                            }
1103                            _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1104                        }
1105                    }
1106                    _ => panic!("Expected NOT in right side, got: {:?}", right),
1107                }
1108            }
1109            _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1110        }
1111    }
1112}