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 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(); 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(); 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 let inner_clause = &clause[7..clause.len() - 1]; 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 let inner_clause = &clause[7..clause.len() - 1]; 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 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 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 return self.parse_conditions_within_object(conditions_str);
475 }
476
477 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 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 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 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 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 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 if trimmed.eq_ignore_ascii_case("null") {
585 return Ok(Value::Null);
586 }
587
588 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 if trimmed.contains('.') {
599 return Ok(Value::String(trimmed.to_string()));
600 }
601
602 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 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 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 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 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 {
704 group: agenda_group,
705 })
706 }
707 "schedulerule" | "schedule_rule" => {
708 let parts: Vec<&str> = args_str.split(',').collect();
710 if parts.len() != 2 {
711 return Err(RuleEngineError::ParseError {
712 message: "ScheduleRule requires delay_ms and rule_name".to_string(),
713 });
714 }
715
716 let delay_ms = self.parse_value(parts[0].trim())?;
717 let rule_name = self.parse_value(parts[1].trim())?;
718
719 let delay_ms = match delay_ms {
720 Value::Integer(i) => i as u64,
721 Value::Number(f) => f as u64,
722 _ => {
723 return Err(RuleEngineError::ParseError {
724 message: "ScheduleRule delay_ms must be a number".to_string(),
725 })
726 }
727 };
728
729 let rule_name = match rule_name {
730 Value::String(s) => s,
731 _ => rule_name.to_string(),
732 };
733
734 Ok(ActionType::ScheduleRule {
735 delay_ms,
736 rule_name,
737 })
738 }
739 "completeworkflow" | "complete_workflow" => {
740 let workflow_id = if args_str.is_empty() {
741 return Err(RuleEngineError::ParseError {
742 message: "CompleteWorkflow requires workflow_id".to_string(),
743 });
744 } else {
745 let value = self.parse_value(args_str.trim())?;
746 match value {
747 Value::String(s) => s,
748 _ => value.to_string(),
749 }
750 };
751 Ok(ActionType::CompleteWorkflow {
752 workflow_name: workflow_id,
753 })
754 }
755 "setworkflowdata" | "set_workflow_data" => {
756 let data_str = args_str.trim();
758
759 let (key, value) = if let Some(eq_pos) = data_str.find('=') {
761 let key = data_str[..eq_pos].trim().trim_matches('"');
762 let value_str = data_str[eq_pos + 1..].trim();
763 let value = self.parse_value(value_str)?;
764 (key.to_string(), value)
765 } else {
766 return Err(RuleEngineError::ParseError {
767 message: "SetWorkflowData data must be in key=value format".to_string(),
768 });
769 };
770
771 Ok(ActionType::SetWorkflowData { key, value })
772 }
773 _ => {
774 let params = if args_str.is_empty() {
776 HashMap::new()
777 } else {
778 self.parse_function_args_as_params(args_str)?
779 };
780
781 Ok(ActionType::Custom {
782 action_type: function_name.to_string(),
783 params,
784 })
785 }
786 }
787 } else {
788 Ok(ActionType::Custom {
790 action_type: "statement".to_string(),
791 params: {
792 let mut params = HashMap::new();
793 params.insert("statement".to_string(), Value::String(trimmed.to_string()));
794 params
795 },
796 })
797 }
798 }
799
800 fn parse_method_args(&self, args_str: &str) -> Result<Vec<Value>> {
801 if args_str.trim().is_empty() {
802 return Ok(Vec::new());
803 }
804
805 let mut args = Vec::new();
807 let parts: Vec<&str> = args_str.split(',').collect();
808
809 for part in parts {
810 let trimmed = part.trim();
811
812 if trimmed.contains('+')
814 || trimmed.contains('-')
815 || trimmed.contains('*')
816 || trimmed.contains('/')
817 {
818 args.push(Value::String(trimmed.to_string()));
820 } else {
821 args.push(self.parse_value(trimmed)?);
822 }
823 }
824
825 Ok(args)
826 }
827
828 fn parse_function_args_as_params(&self, args_str: &str) -> Result<HashMap<String, Value>> {
830 let mut params = HashMap::new();
831
832 if args_str.trim().is_empty() {
833 return Ok(params);
834 }
835
836 let parts: Vec<&str> = args_str.split(',').collect();
838 for (i, part) in parts.iter().enumerate() {
839 let trimmed = part.trim();
840 let value = self.parse_value(trimmed)?;
841
842 params.insert(i.to_string(), value);
844 }
845
846 Ok(params)
847 }
848}
849
850#[cfg(test)]
851mod tests {
852 use super::GRLParser;
853
854 #[test]
855 fn test_parse_simple_rule() {
856 let grl = r#"
857 rule "CheckAge" salience 10 {
858 when
859 User.Age >= 18
860 then
861 log("User is adult");
862 }
863 "#;
864
865 let rules = GRLParser::parse_rules(grl).unwrap();
866 assert_eq!(rules.len(), 1);
867 let rule = &rules[0];
868 assert_eq!(rule.name, "CheckAge");
869 assert_eq!(rule.salience, 10);
870 assert_eq!(rule.actions.len(), 1);
871 }
872
873 #[test]
874 fn test_parse_complex_condition() {
875 let grl = r#"
876 rule "ComplexRule" {
877 when
878 User.Age >= 18 && User.Country == "US"
879 then
880 User.Qualified = true;
881 }
882 "#;
883
884 let rules = GRLParser::parse_rules(grl).unwrap();
885 assert_eq!(rules.len(), 1);
886 let rule = &rules[0];
887 assert_eq!(rule.name, "ComplexRule");
888 }
889
890 #[test]
891 fn test_parse_new_syntax_with_parentheses() {
892 let grl = r#"
893 rule "Default Rule" salience 10 {
894 when
895 (user.age >= 18)
896 then
897 set(user.status, "approved");
898 }
899 "#;
900
901 let rules = GRLParser::parse_rules(grl).unwrap();
902 assert_eq!(rules.len(), 1);
903 let rule = &rules[0];
904 assert_eq!(rule.name, "Default Rule");
905 assert_eq!(rule.salience, 10);
906 assert_eq!(rule.actions.len(), 1);
907
908 match &rule.actions[0] {
910 crate::types::ActionType::Custom {
911 action_type,
912 params,
913 } => {
914 assert_eq!(action_type, "set");
915 assert_eq!(
916 params.get("0"),
917 Some(&crate::types::Value::String("user.status".to_string()))
918 );
919 assert_eq!(
920 params.get("1"),
921 Some(&crate::types::Value::String("approved".to_string()))
922 );
923 }
924 _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
925 }
926 }
927
928 #[test]
929 fn test_parse_complex_nested_conditions() {
930 let grl = r#"
931 rule "Complex Business Rule" salience 10 {
932 when
933 (((user.vipStatus == true) && (order.amount > 500)) || ((date.isHoliday == true) && (order.hasCoupon == true)))
934 then
935 apply_discount(20000);
936 }
937 "#;
938
939 let rules = GRLParser::parse_rules(grl).unwrap();
940 assert_eq!(rules.len(), 1);
941 let rule = &rules[0];
942 assert_eq!(rule.name, "Complex Business Rule");
943 assert_eq!(rule.salience, 10);
944 assert_eq!(rule.actions.len(), 1);
945
946 match &rule.actions[0] {
948 crate::types::ActionType::Custom {
949 action_type,
950 params,
951 } => {
952 assert_eq!(action_type, "apply_discount");
953 assert_eq!(params.get("0"), Some(&crate::types::Value::Integer(20000)));
954 }
955 _ => panic!("Expected Custom action, got: {:?}", rule.actions[0]),
956 }
957 }
958
959 #[test]
960 fn test_parse_no_loop_attribute() {
961 let grl = r#"
962 rule "NoLoopRule" no-loop salience 15 {
963 when
964 User.Score < 100
965 then
966 set(User.Score, User.Score + 10);
967 }
968 "#;
969
970 let rules = GRLParser::parse_rules(grl).unwrap();
971 assert_eq!(rules.len(), 1);
972 let rule = &rules[0];
973 assert_eq!(rule.name, "NoLoopRule");
974 assert_eq!(rule.salience, 15);
975 assert!(rule.no_loop, "Rule should have no-loop=true");
976 }
977
978 #[test]
979 fn test_parse_no_loop_different_positions() {
980 let grl1 = r#"
982 rule "Rule1" no-loop salience 10 {
983 when User.Age >= 18
984 then log("adult");
985 }
986 "#;
987
988 let grl2 = r#"
990 rule "Rule2" salience 10 no-loop {
991 when User.Age >= 18
992 then log("adult");
993 }
994 "#;
995
996 let rules1 = GRLParser::parse_rules(grl1).unwrap();
997 let rules2 = GRLParser::parse_rules(grl2).unwrap();
998
999 assert_eq!(rules1.len(), 1);
1000 assert_eq!(rules2.len(), 1);
1001
1002 assert!(rules1[0].no_loop, "Rule1 should have no-loop=true");
1003 assert!(rules2[0].no_loop, "Rule2 should have no-loop=true");
1004
1005 assert_eq!(rules1[0].salience, 10);
1006 assert_eq!(rules2[0].salience, 10);
1007 }
1008
1009 #[test]
1010 fn test_parse_without_no_loop() {
1011 let grl = r#"
1012 rule "RegularRule" salience 5 {
1013 when
1014 User.Active == true
1015 then
1016 log("active user");
1017 }
1018 "#;
1019
1020 let rules = GRLParser::parse_rules(grl).unwrap();
1021 assert_eq!(rules.len(), 1);
1022 let rule = &rules[0];
1023 assert_eq!(rule.name, "RegularRule");
1024 assert!(!rule.no_loop, "Rule should have no-loop=false by default");
1025 }
1026
1027 #[test]
1028 fn test_parse_exists_pattern() {
1029 let grl = r#"
1030 rule "ExistsRule" salience 20 {
1031 when
1032 exists(Customer.tier == "VIP")
1033 then
1034 System.premiumActive = true;
1035 }
1036 "#;
1037
1038 let rules = GRLParser::parse_rules(grl).unwrap();
1039 assert_eq!(rules.len(), 1);
1040 let rule = &rules[0];
1041 assert_eq!(rule.name, "ExistsRule");
1042 assert_eq!(rule.salience, 20);
1043
1044 match &rule.conditions {
1046 crate::engine::rule::ConditionGroup::Exists(_) => {
1047 }
1049 _ => panic!(
1050 "Expected EXISTS condition group, got: {:?}",
1051 rule.conditions
1052 ),
1053 }
1054 }
1055
1056 #[test]
1057 fn test_parse_forall_pattern() {
1058 let grl = r#"
1059 rule "ForallRule" salience 15 {
1060 when
1061 forall(Order.status == "processed")
1062 then
1063 Shipping.enabled = true;
1064 }
1065 "#;
1066
1067 let rules = GRLParser::parse_rules(grl).unwrap();
1068 assert_eq!(rules.len(), 1);
1069 let rule = &rules[0];
1070 assert_eq!(rule.name, "ForallRule");
1071
1072 match &rule.conditions {
1074 crate::engine::rule::ConditionGroup::Forall(_) => {
1075 }
1077 _ => panic!(
1078 "Expected FORALL condition group, got: {:?}",
1079 rule.conditions
1080 ),
1081 }
1082 }
1083
1084 #[test]
1085 fn test_parse_combined_patterns() {
1086 let grl = r#"
1087 rule "CombinedRule" salience 25 {
1088 when
1089 exists(Customer.tier == "VIP") && !exists(Alert.priority == "high")
1090 then
1091 System.vipMode = true;
1092 }
1093 "#;
1094
1095 let rules = GRLParser::parse_rules(grl).unwrap();
1096 assert_eq!(rules.len(), 1);
1097 let rule = &rules[0];
1098 assert_eq!(rule.name, "CombinedRule");
1099
1100 match &rule.conditions {
1102 crate::engine::rule::ConditionGroup::Compound {
1103 left,
1104 operator,
1105 right,
1106 } => {
1107 assert_eq!(*operator, crate::types::LogicalOperator::And);
1108
1109 match left.as_ref() {
1111 crate::engine::rule::ConditionGroup::Exists(_) => {
1112 }
1114 _ => panic!("Expected EXISTS in left side, got: {:?}", left),
1115 }
1116
1117 match right.as_ref() {
1119 crate::engine::rule::ConditionGroup::Not(inner) => {
1120 match inner.as_ref() {
1121 crate::engine::rule::ConditionGroup::Exists(_) => {
1122 }
1124 _ => panic!("Expected EXISTS inside NOT, got: {:?}", inner),
1125 }
1126 }
1127 _ => panic!("Expected NOT in right side, got: {:?}", right),
1128 }
1129 }
1130 _ => panic!("Expected compound condition, got: {:?}", rule.conditions),
1131 }
1132 }
1133}