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
8pub struct GRLParser;
11
12#[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 pub fn parse_rule(grl_text: &str) -> Result<Rule> {
37 let mut parser = GRLParser;
38 parser.parse_single_rule(grl_text)
39 }
40
41 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 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 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 let attributes_section = captures.get(3).map(|m| m.as_str()).unwrap_or("");
76
77 let rule_body = captures.get(4).unwrap().as_str();
79
80 let salience = self.extract_salience(attributes_section)?;
82
83 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 let conditions = self.parse_when_clause(when_clause)?;
101 let actions = self.parse_then_clause(then_clause)?;
102
103 let attributes = self.parse_rule_attributes(attributes_section)?;
105
106 let mut rule = Rule::new(rule_name, conditions, actions);
108 rule = rule.with_priority(salience);
109
110 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 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 fn parse_rule_attributes(&self, rule_header: &str) -> Result<RuleAttributes> {
156 let mut attributes = RuleAttributes::default();
157
158 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 if let Some(agenda_group) = self.extract_quoted_attribute(rule_header, "agenda-group")? {
168 attributes.agenda_group = Some(agenda_group);
169 }
170
171 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 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 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 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 fn parse_date_string(&self, date_str: &str) -> Result<DateTime<Utc>> {
209 if let Ok(date) = DateTime::parse_from_rfc3339(date_str) {
211 return Ok(date.with_timezone(&Utc));
212 }
213
214 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 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) }
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 let trimmed = when_clause.trim();
262
263 let clause = if trimmed.starts_with('(') && trimmed.ends_with(')') {
265 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 if let Some(parts) = self.split_logical_operator(clause, "||") {
278 return self.parse_or_parts(parts);
279 }
280
281 if let Some(parts) = self.split_logical_operator(clause, "&&") {
283 return self.parse_and_parts(parts);
284 }
285
286 if clause.trim_start().starts_with("!") {
288 return self.parse_not_condition(clause);
289 }
290
291 if clause.trim_start().starts_with("exists(") {
293 return self.parse_exists_condition(clause);
294 }
295
296 if clause.trim_start().starts_with("forall(") {
298 return self.parse_forall_condition(clause);
299 }
300
301 if clause.trim_start().starts_with("accumulate(") {
303 return self.parse_accumulate_condition(clause);
304 }
305
306 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(); 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(); 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 let inner_clause = &clause[7..clause.len() - 1]; 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 let inner_clause = &clause[7..clause.len() - 1]; 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 let inner = &clause[11..clause.len() - 1]; 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 let (source_pattern, extract_field, source_conditions) =
484 self.parse_accumulate_pattern(pattern_part)?;
485
486 let (function, function_arg) = self.parse_accumulate_function(function_part)?;
488
489 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 let pattern = pattern.trim();
544
545 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 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 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 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 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 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 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 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 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 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 return self.parse_conditions_within_object(conditions_str);
702 }
703
704 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 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 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 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 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 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 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 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 if trimmed.eq_ignore_ascii_case("null") {
847 return Ok(Value::Null);
848 }
849
850 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 if self.is_expression(trimmed) {
862 return Ok(Value::Expression(trimmed.to_string()));
863 }
864
865 if trimmed.contains('.') {
867 return Ok(Value::String(trimmed.to_string()));
868 }
869
870 Ok(Value::String(trimmed.to_string()))
872 }
873
874 fn is_expression(&self, s: &str) -> bool {
876 let has_operator = s.contains('+') || s.contains('-') || s.contains('*') || s.contains('/') || s.contains('%');
878
879 let has_field_ref = s.contains('.');
881
882 let has_spaces = s.contains(' ');
884
885 has_operator && (has_field_ref || has_spaces)
887 }
888
889 fn parse_then_clause(&self, then_clause: &str) -> Result<Vec<ActionType>> {
890 let statements: Vec<&str> = then_clause
891 .split(';')
892 .map(|s| s.trim())
893 .filter(|s| !s.is_empty())
894 .collect();
895
896 let mut actions = Vec::new();
897
898 for statement in statements {
899 let action = self.parse_action_statement(statement)?;
900 actions.push(action);
901 }
902
903 Ok(actions)
904 }
905
906 fn parse_action_statement(&self, statement: &str) -> Result<ActionType> {
907 let trimmed = statement.trim();
908
909 let method_regex = Regex::new(r#"\$(\w+)\.(\w+)\s*\(([^)]*)\)"#).map_err(|e| {
911 RuleEngineError::ParseError {
912 message: format!("Method regex error: {}", e),
913 }
914 })?;
915
916 if let Some(captures) = method_regex.captures(trimmed) {
917 let object = captures.get(1).unwrap().as_str().to_string();
918 let method = captures.get(2).unwrap().as_str().to_string();
919 let args_str = captures.get(3).unwrap().as_str();
920
921 let args = if args_str.trim().is_empty() {
922 Vec::new()
923 } else {
924 self.parse_method_args(args_str)?
925 };
926
927 return Ok(ActionType::MethodCall {
928 object,
929 method,
930 args,
931 });
932 }
933
934 if let Some(eq_pos) = trimmed.find('=') {
936 let field = trimmed[..eq_pos].trim().to_string();
937 let value_str = trimmed[eq_pos + 1..].trim();
938 let value = self.parse_value(value_str)?;
939
940 return Ok(ActionType::Set { field, value });
941 }
942
943 let func_regex =
945 Regex::new(r#"(\w+)\s*\(\s*(.+?)?\s*\)"#).map_err(|e| RuleEngineError::ParseError {
946 message: format!("Function regex error: {}", e),
947 })?;
948
949 if let Some(captures) = func_regex.captures(trimmed) {
950 let function_name = captures.get(1).unwrap().as_str();
951 let args_str = captures.get(2).map(|m| m.as_str()).unwrap_or("");
952
953 match function_name.to_lowercase().as_str() {
954 "update" => {
955 let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
957 stripped.to_string()
958 } else {
959 args_str.to_string()
960 };
961 Ok(ActionType::Update {
962 object: object_name,
963 })
964 }
965 "retract" => {
966 let object_name = if let Some(stripped) = args_str.strip_prefix('$') {
968 stripped.to_string()
969 } else {
970 args_str.to_string()
971 };
972 Ok(ActionType::Retract {
973 object: object_name,
974 })
975 }
976 "log" => {
977 let message = if args_str.is_empty() {
978 "Log message".to_string()
979 } else {
980 let value = self.parse_value(args_str.trim())?;
981 value.to_string()
982 };
983 Ok(ActionType::Log { message })
984 }
985 "activateagendagroup" | "activate_agenda_group" => {
986 let agenda_group = if args_str.is_empty() {
987 return Err(RuleEngineError::ParseError {
988 message: "ActivateAgendaGroup requires agenda group name".to_string(),
989 });
990 } else {
991 let value = self.parse_value(args_str.trim())?;
992 match value {
993 Value::String(s) => s,
994 _ => value.to_string(),
995 }
996 };
997 Ok(ActionType::ActivateAgendaGroup {
998 group: agenda_group,
999 })
1000 }
1001 "schedulerule" | "schedule_rule" => {
1002 let parts: Vec<&str> = args_str.split(',').collect();
1004 if parts.len() != 2 {
1005 return Err(RuleEngineError::ParseError {
1006 message: "ScheduleRule requires delay_ms and rule_name".to_string(),
1007 });
1008 }
1009
1010 let delay_ms = self.parse_value(parts[0].trim())?;
1011 let rule_name = self.parse_value(parts[1].trim())?;
1012
1013 let delay_ms = match delay_ms {
1014 Value::Integer(i) => i as u64,
1015 Value::Number(f) => f as u64,
1016 _ => {
1017 return Err(RuleEngineError::ParseError {
1018 message: "ScheduleRule delay_ms must be a number".to_string(),
1019 })
1020 }
1021 };
1022
1023 let rule_name = match rule_name {
1024 Value::String(s) => s,
1025 _ => rule_name.to_string(),
1026 };
1027
1028 Ok(ActionType::ScheduleRule {
1029 delay_ms,
1030 rule_name,
1031 })
1032 }
1033 "completeworkflow" | "complete_workflow" => {
1034 let workflow_id = if args_str.is_empty() {
1035 return Err(RuleEngineError::ParseError {
1036 message: "CompleteWorkflow requires workflow_id".to_string(),
1037 });
1038 } else {
1039 let value = self.parse_value(args_str.trim())?;
1040 match value {
1041 Value::String(s) => s,
1042 _ => value.to_string(),
1043 }
1044 };
1045 Ok(ActionType::CompleteWorkflow {
1046 workflow_name: workflow_id,
1047 })
1048 }
1049 "setworkflowdata" | "set_workflow_data" => {
1050 let data_str = args_str.trim();
1052
1053 let (key, value) = if let Some(eq_pos) = data_str.find('=') {
1055 let key = data_str[..eq_pos].trim().trim_matches('"');
1056 let value_str = data_str[eq_pos + 1..].trim();
1057 let value = self.parse_value(value_str)?;
1058 (key.to_string(), value)
1059 } else {
1060 return Err(RuleEngineError::ParseError {
1061 message: "SetWorkflowData data must be in key=value format".to_string(),
1062 });
1063 };
1064
1065 Ok(ActionType::SetWorkflowData { key, value })
1066 }
1067 _ => {
1068 let params = if args_str.is_empty() {
1070 HashMap::new()
1071 } else {
1072 self.parse_function_args_as_params(args_str)?
1073 };
1074
1075 Ok(ActionType::Custom {
1076 action_type: function_name.to_string(),
1077 params,
1078 })
1079 }
1080 }
1081 } else {
1082 Ok(ActionType::Custom {
1084 action_type: "statement".to_string(),
1085 params: {
1086 let mut params = HashMap::new();
1087 params.insert("statement".to_string(), Value::String(trimmed.to_string()));
1088 params
1089 },
1090 })
1091 }
1092 }
1093
1094 fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
1095 if args_str.trim().is_empty() {
1096 return Ok(Vec::new());
1097 }
1098
1099 let mut args = Vec::new();
1101 let parts: Vec<&str> = args_str.split(',').collect();
1102
1103 for part in parts {
1104 let trimmed = part.trim();
1105
1106 if trimmed.contains('+')
1108 || trimmed.contains('-')
1109 || trimmed.contains('*')
1110 || trimmed.contains('/')
1111 {
1112 args.push(Value::String(trimmed.to_string()));
1114 } else {
1115 args.push(self.parse_value(trimmed)?);
1116 }
1117 }
1118
1119 Ok(args)
1120 }
1121
1122 fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
1124 let mut params = HashMap::new();
1125
1126 if args_str.trim().is_empty() {
1127 return Ok(params);
1128 }
1129
1130 let parts: Vec<&str> = args_str.split(',').collect();
1132 for (i, part) in parts.iter().enumerate() {
1133 let trimmed = part.trim();
1134 let value = self.parse_value(trimmed)?;
1135
1136 params.insert(i.to_string(), value);
1138 }
1139
1140 Ok(params)
1141 }
1142}
1143
1144#[cfg(test)]
1145mod tests {
1146 use super::GRLParser;
1147
1148 #[test]
1149 fn test_parse_simple_rule() {
1150 let grl = r#"
1151 rule "CheckAge" salience 10 {
1152 when
1153 User.Age >= 18
1154 then
1155 log("User is adult");
1156 }
1157 "#;
1158
1159 let rules = GRLParser::parse_rules(grl).unwrap();
1160 assert_eq!(rules.len(), 1);
1161 let rule = &rules[0];
1162 assert_eq!(rule.name, "CheckAge");
1163 assert_eq!(rule.salience, 10);
1164 assert_eq!(rule.actions.len(), 1);
1165 }
1166
1167 #[test]
1168 fn test_parse_complex_condition() {
1169 let grl = r#"
1170 rule "ComplexRule" {
1171 when
1172 User.Age >= 18 && User.Country == "US"
1173 then
1174 User.Qualified = true;
1175 }
1176 "#;
1177
1178 let rules = GRLParser::parse_rules(grl).unwrap();
1179 assert_eq!(rules.len(), 1);
1180 let rule = &rules[0];
1181 assert_eq!(rule.name, "ComplexRule");
1182 }
1183
1184 #[test]
1185 fn test_parse_new_syntax_with_parentheses() {
1186 let grl = r#"
1187 rule "Default Rule" salience 10 {
1188 when
1189 (user.age >= 18)
1190 then
1191 set(user.status, "approved");
1192 }
1193 "#;
1194
1195 let rules = GRLParser::parse_rules(grl).unwrap();
1196 assert_eq!(rules.len(), 1);
1197 let rule = &rules[0];
1198 assert_eq!(rule.name, "Default Rule");
1199 assert_eq!(rule.salience, 10);
1200 assert_eq!(rule.actions.len(), 1);
1201
1202 match &rule.actions[0] {
1204 crate::types::ActionType::Custom {
1205 action_type,
1206 params,
1207 } => {
1208 assert_eq!(action_type, "set");
1209 assert_eq!(
1210 params.get("0"),
1211 Some(&crate::types::Value::String("user.status".to_string()))
1212 );
1213 assert_eq!(
1214 params.get("1"),
1215 Some(&crate::types::Value::String("approved".to_string()))
1216 );
1217 }
1218 _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1219 }
1220 }
1221
1222 #[test]
1223 fn test_parse_complex_nested_conditions() {
1224 let grl = r#"
1225 rule "Complex Business Rule" salience 10 {
1226 when
1227 (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
1228 then
1229 apply_discount(20000);
1230 }
1231 "#;
1232
1233 let rules = GRLParser::parse_rules(grl).unwrap();
1234 assert_eq!(rules.len(), 1);
1235 let rule = &rules[0];
1236 assert_eq!(rule.name, "Complex Business Rule");
1237 assert_eq!(rule.salience, 10);
1238 assert_eq!(rule.actions.len(), 1);
1239
1240 match &rule.actions[0] {
1242 crate::types::ActionType::Custom {
1243 action_type,
1244 params,
1245 } => {
1246 assert_eq!(action_type, "apply_discount");
1247 assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
1248 }
1249 _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
1250 }
1251 }
1252
1253 #[test]
1254 fn test_parse_no_loop_attribute() {
1255 let grl = r#"
1256 rule "NoLoopRule" no-loop salience 15 {
1257 when
1258 User.Score < 100
1259 then
1260 set(User.Score, User.Score + 10);
1261 }
1262 "#;
1263
1264 let rules = GRLParser::parse_rules(grl).unwrap();
1265 assert_eq!(rules.len(), 1);
1266 let rule = &rules[0];
1267 assert_eq!(rule.name, "NoLoopRule");
1268 assert_eq!(rule.salience, 15);
1269 assert!(rule.no_loop, "Rule should have no-loop=true");
1270 }
1271
1272 #[test]
1273 fn test_parse_no_loop_different_positions() {
1274 let grl1 = r#"
1276 rule "Rule1" no-loop salience 10 {
1277 when User.Age >= 18
1278 then log("adult");
1279 }
1280 "#;
1281
1282 let grl2 = r#"
1284 rule "Rule2" salience 10 no-loop {
1285 when User.Age >= 18
1286 then log("adult");
1287 }
1288 "#;
1289
1290 let rules1 = GRLParser::parse_rules(grl1).unwrap();
1291 let rules2 = GRLParser::parse_rules(grl2).unwrap();
1292
1293 assert_eq!(rules1.len(), 1);
1294 assert_eq!(rules2.len(), 1);
1295
1296 assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
1297 assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
1298
1299 assert_eq!(rules1[0].salience, 10);
1300 assert_eq!(rules2[0].salience, 10);
1301 }
1302
1303 #[test]
1304 fn test_parse_without_no_loop() {
1305 let grl = r#"
1306 rule "RegularRule" salience 5 {
1307 when
1308 User.Active == true
1309 then
1310 log("active user");
1311 }
1312 "#;
1313
1314 let rules = GRLParser::parse_rules(grl).unwrap();
1315 assert_eq!(rules.len(), 1);
1316 let rule = &rules[0];
1317 assert_eq!(rule.name, "RegularRule");
1318 assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1319 }
1320
1321 #[test]
1322 fn test_parse_exists_pattern() {
1323 let grl = r#"
1324 rule "ExistsRule" salience 20 {
1325 when
1326 exists(Customer.tier == "VIP")
1327 then
1328 System.premiumActive = true;
1329 }
1330 "#;
1331
1332 let rules = GRLParser::parse_rules(grl).unwrap();
1333 assert_eq!(rules.len(), 1);
1334 let rule = &rules[0];
1335 assert_eq!(rule.name, "ExistsRule");
1336 assert_eq!(rule.salience, 20);
1337
1338 match &rule.conditions {
1340 crate::engine::rule::ConditionGroup::Exists(_) => {
1341 }
1343 _ => panic!(
1344 "Expected EXISTS condition group, got: {:?}",
1345 rule.conditions
1346 ),
1347 }
1348 }
1349
1350 #[test]
1351 fn test_parse_forall_pattern() {
1352 let grl = r#"
1353 rule "ForallRule" salience 15 {
1354 when
1355 forall(Order.status == "processed")
1356 then
1357 Shipping.enabled = true;
1358 }
1359 "#;
1360
1361 let rules = GRLParser::parse_rules(grl).unwrap();
1362 assert_eq!(rules.len(), 1);
1363 let rule = &rules[0];
1364 assert_eq!(rule.name, "ForallRule");
1365
1366 match &rule.conditions {
1368 crate::engine::rule::ConditionGroup::Forall(_) => {
1369 }
1371 _ => panic!(
1372 "Expected FORALL condition group, got: {:?}",
1373 rule.conditions
1374 ),
1375 }
1376 }
1377
1378 #[test]
1379 fn test_parse_combined_patterns() {
1380 let grl = r#"
1381 rule "CombinedRule" salience 25 {
1382 when
1383 exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1384 then
1385 System.vipMode = true;
1386 }
1387 "#;
1388
1389 let rules = GRLParser::parse_rules(grl).unwrap();
1390 assert_eq!(rules.len(), 1);
1391 let rule = &rules[0];
1392 assert_eq!(rule.name, "CombinedRule");
1393
1394 match &rule.conditions {
1396 crate::engine::rule::ConditionGroup::Compound {
1397 left,
1398 operator,
1399 right,
1400 } => {
1401 assert_eq!(*operator, crate::types::LogicalOperator::And);
1402
1403 match left.as_ref() {
1405 crate::engine::rule::ConditionGroup::Exists(_) => {
1406 }
1408 _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1409 }
1410
1411 match right.as_ref() {
1413 crate::engine::rule::ConditionGroup::Not(inner) => {
1414 match inner.as_ref() {
1415 crate::engine::rule::ConditionGroup::Exists(_) => {
1416 }
1418 _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1419 }
1420 }
1421 _ => panic!("Expected NOT in right side, got: {:?}", right),
1422 }
1423 }
1424 _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1425 }
1426 }
1427}