rust_rule_engine/rete/
grl_loader.rs

1//! GRL to RETE Converter
2//!
3//! This module converts GRL (Grule Rule Language) rules into RETE-UL structures
4//! for efficient pattern matching and rule execution.
5
6use crate::engine::rule::{Condition, ConditionGroup, Rule};
7use crate::parser::GRLParser;
8use crate::rete::{AlphaNode, ReteUlNode, TypedReteUlRule};
9use crate::rete::facts::{TypedFacts, FactValue};
10use crate::rete::propagation::IncrementalEngine;
11use crate::types::{Operator, Value};
12use crate::errors::{Result, RuleEngineError};
13use std::fs;
14use std::path::Path;
15
16/// GRL to RETE Loader
17/// Converts GRL rules into RETE-UL structures
18pub struct GrlReteLoader;
19
20impl GrlReteLoader {
21    /// Load rules from a GRL file into RETE engine
22    pub fn load_from_file<P: AsRef<Path>>(
23        path: P,
24        engine: &mut IncrementalEngine,
25    ) -> Result<usize> {
26        let grl_text = fs::read_to_string(path.as_ref()).map_err(|e| {
27            RuleEngineError::ParseError {
28                message: format!("Failed to read GRL file: {}", e),
29            }
30        })?;
31
32        Self::load_from_string(&grl_text, engine)
33    }
34
35    /// Load rules from GRL string into RETE engine
36    pub fn load_from_string(
37        grl_text: &str,
38        engine: &mut IncrementalEngine,
39    ) -> Result<usize> {
40        // Parse GRL rules
41        let rules = GRLParser::parse_rules(grl_text)?;
42
43        let mut loaded_count = 0;
44
45        for rule in rules {
46            // Convert GRL rule to RETE rule
47            let rete_rule = Self::convert_rule_to_rete(rule)?;
48
49            // Extract dependencies (fact types used in conditions)
50            let dependencies = Self::extract_dependencies(&rete_rule);
51
52            // Add to engine
53            engine.add_rule(rete_rule, dependencies);
54            loaded_count += 1;
55        }
56
57        Ok(loaded_count)
58    }
59
60    /// Convert GRL Rule to TypedReteUlRule
61    fn convert_rule_to_rete(rule: Rule) -> Result<TypedReteUlRule> {
62        // Convert ConditionGroup to ReteUlNode
63        let node = Self::convert_condition_group(&rule.conditions)?;
64
65        // Create RETE rule
66        let rete_rule = TypedReteUlRule {
67            name: rule.name.clone(),
68            node,
69            priority: rule.salience,
70            no_loop: rule.no_loop,
71            action: Self::create_action_closure(rule.actions),
72        };
73
74        Ok(rete_rule)
75    }
76
77    /// Convert ConditionGroup to ReteUlNode
78    fn convert_condition_group(group: &ConditionGroup) -> Result<ReteUlNode> {
79        match group {
80            ConditionGroup::Single(condition) => {
81                Self::convert_condition(condition)
82            }
83            ConditionGroup::Compound { left, operator, right } => {
84                let left_node = Self::convert_condition_group(left)?;
85                let right_node = Self::convert_condition_group(right)?;
86
87                match operator {
88                    crate::types::LogicalOperator::And => {
89                        Ok(ReteUlNode::UlAnd(Box::new(left_node), Box::new(right_node)))
90                    }
91                    crate::types::LogicalOperator::Or => {
92                        Ok(ReteUlNode::UlOr(Box::new(left_node), Box::new(right_node)))
93                    }
94                    crate::types::LogicalOperator::Not => {
95                        // For NOT, we only use left node
96                        Ok(ReteUlNode::UlNot(Box::new(left_node)))
97                    }
98                }
99            }
100            ConditionGroup::Not(inner) => {
101                let inner_node = Self::convert_condition_group(inner)?;
102                Ok(ReteUlNode::UlNot(Box::new(inner_node)))
103            }
104            ConditionGroup::Exists(inner) => {
105                let inner_node = Self::convert_condition_group(inner)?;
106                Ok(ReteUlNode::UlExists(Box::new(inner_node)))
107            }
108            ConditionGroup::Forall(inner) => {
109                let inner_node = Self::convert_condition_group(inner)?;
110                Ok(ReteUlNode::UlForall(Box::new(inner_node)))
111            }
112            ConditionGroup::Accumulate {
113                result_var,
114                source_pattern,
115                extract_field,
116                source_conditions,
117                function,
118                function_arg,
119            } => {
120                Ok(ReteUlNode::UlAccumulate {
121                    result_var: result_var.clone(),
122                    source_pattern: source_pattern.clone(),
123                    extract_field: extract_field.clone(),
124                    source_conditions: source_conditions.clone(),
125                    function: function.clone(),
126                    function_arg: function_arg.clone(),
127                })
128            }
129        }
130    }
131
132    /// Convert single Condition to ReteUlNode (AlphaNode or UlMultiField)
133    fn convert_condition(condition: &Condition) -> Result<ReteUlNode> {
134        use crate::engine::rule::ConditionExpression;
135
136        // Check if this is a multifield condition
137        match &condition.expression {
138            ConditionExpression::MultiField { field, operation, variable } => {
139                // Convert to UlMultiField node
140                let operator_str = Self::operator_to_string(&condition.operator);
141                let value_str = if !matches!(condition.value, Value::Boolean(_)) {
142                    Some(Self::value_to_string(&condition.value))
143                } else {
144                    None
145                };
146
147                // Determine if this is a count operation with comparison
148                let (op, cmp_val) = if operation == "count" && operator_str != "==" {
149                    // Count with comparison: "count > 5"
150                    (Some(operator_str), value_str)
151                } else {
152                    // Other operations
153                    (None, value_str)
154                };
155
156                Ok(ReteUlNode::UlMultiField {
157                    field: field.clone(),
158                    operation: operation.clone(),
159                    value: if operation == "contains" { cmp_val.clone() } else { None },
160                    operator: op,
161                    compare_value: if operation == "count" { cmp_val } else { None },
162                })
163            }
164            _ => {
165                // Standard alpha node for regular conditions
166                let operator_str = Self::operator_to_string(&condition.operator);
167                let value_str = Self::value_to_string(&condition.value);
168
169                let alpha = AlphaNode {
170                    field: condition.field.clone(),
171                    operator: operator_str,
172                    value: value_str,
173                };
174
175                Ok(ReteUlNode::UlAlpha(alpha))
176            }
177        }
178    }
179
180    /// Convert Operator to string
181    fn operator_to_string(op: &Operator) -> String {
182        match op {
183            Operator::Equal => "==".to_string(),
184            Operator::NotEqual => "!=".to_string(),
185            Operator::GreaterThan => ">".to_string(),
186            Operator::GreaterThanOrEqual => ">=".to_string(),
187            Operator::LessThan => "<".to_string(),
188            Operator::LessThanOrEqual => "<=".to_string(),
189            Operator::Contains => "contains".to_string(),
190            Operator::NotContains => "!contains".to_string(),
191            Operator::StartsWith => "startsWith".to_string(),
192            Operator::EndsWith => "endsWith".to_string(),
193            Operator::Matches => "matches".to_string(),
194        }
195    }
196
197    /// Convert Value to string for AlphaNode
198    fn value_to_string(value: &Value) -> String {
199        match value {
200            Value::Number(n) => n.to_string(),
201            Value::Integer(i) => i.to_string(),
202            Value::String(s) => s.clone(),
203            Value::Boolean(b) => b.to_string(),
204            Value::Null => "null".to_string(),
205            Value::Array(arr) => {
206                // Convert array to JSON-like string
207                let items: Vec<String> = arr.iter()
208                    .map(|v| Self::value_to_string(v))
209                    .collect();
210                format!("[{}]", items.join(","))
211            }
212            Value::Object(_) => {
213                // For objects, we'll use a simplified representation
214                "object".to_string()
215            }
216            Value::Expression(expr) => {
217                // For expressions, return the expression string
218                expr.clone()
219            }
220        }
221    }
222
223    /// Create action closure from ActionType list
224    fn create_action_closure(
225        actions: Vec<crate::types::ActionType>,
226    ) -> std::sync::Arc<dyn Fn(&mut TypedFacts, &mut super::ActionResults) + Send + Sync> {
227        std::sync::Arc::new(move |facts: &mut TypedFacts, results: &mut super::ActionResults| {
228            // Execute actions
229            for action in &actions {
230                Self::execute_action(action, facts, results);
231            }
232        })
233    }
234
235    /// Execute a single action
236    fn execute_action(
237        action: &crate::types::ActionType, 
238        facts: &mut TypedFacts,
239        results: &mut super::ActionResults,
240    ) {
241        use crate::types::ActionType;
242
243        match action {
244            ActionType::Set { field, value } => {
245                // Assignment action (from "field = value" syntax in GRL)
246                // Note: Set() function syntax is NOT supported.
247                // Use: Player.score = Player.score + 10;
248                
249                // Check if value is an expression that needs evaluation
250                let evaluated_value = match value {
251                    Value::Expression(expr) => {
252                        // Evaluate expression with current facts
253                        Self::evaluate_expression_for_rete(expr, facts)
254                    }
255                    _ => value.clone(),
256                };
257
258                // Convert evaluated value to FactValue
259                let fact_value = Self::value_to_fact_value(&evaluated_value);
260                facts.set(field, fact_value);
261            }
262            ActionType::Log { message } => {
263                println!("📝 LOG: {}", message);
264            }
265            ActionType::MethodCall { object, method, args } => {
266                // Method calls can be treated as function calls with object as first arg
267                let mut all_args = vec![object.clone()];
268                all_args.extend(args.iter().map(|v| Self::value_to_string(v)));
269                
270                results.add(super::ActionResult::CallFunction {
271                    function_name: format!("{}.{}", object, method),
272                    args: all_args,
273                });
274                println!("� METHOD: {}.{}", object, method);
275            }
276            ActionType::Retract { object } => {
277                // Strip quotes from object name if present
278                let object_name = object.trim_matches('"');
279                
280                // Try to get the handle for this fact type from metadata
281                if let Some(handle) = facts.get_fact_handle(object_name) {
282                    // Retract specific fact by handle
283                    results.add(super::ActionResult::Retract(handle));
284                    println!("🗑️ RETRACT: {} (handle: {:?})", object_name, handle);
285                } else {
286                    // Fallback: retract by type (first matching fact)
287                    results.add(super::ActionResult::RetractByType(object_name.to_string()));
288                    println!("🗑️ RETRACT: {} (by type, no handle found)", object_name);
289                }
290            }
291            ActionType::Custom { action_type, params } => {
292                // Treat custom actions as function calls
293                let args: Vec<String> = params.values()
294                    .map(|v| Self::value_to_string(v))
295                    .collect();
296                
297                results.add(super::ActionResult::CallFunction {
298                    function_name: action_type.clone(),
299                    args,
300                });
301                println!("🔧 CUSTOM CALL: {}", action_type);
302            }
303            ActionType::ActivateAgendaGroup { group } => {
304                // Queue agenda group activation
305                results.add(super::ActionResult::ActivateAgendaGroup(group.clone()));
306                println!("📋 ACTIVATE GROUP: {}", group);
307            }
308            ActionType::ScheduleRule { rule_name, delay_ms } => {
309                // Queue rule scheduling
310                results.add(super::ActionResult::ScheduleRule {
311                    rule_name: rule_name.clone(),
312                    delay_ms: *delay_ms,
313                });
314                println!("⏰ SCHEDULE: {} (delay: {}ms)", rule_name, delay_ms);
315            }
316            ActionType::CompleteWorkflow { workflow_name } => {
317                // Mark workflow as completed by setting a fact
318                let completion_key = format!("workflow.{}.completed", workflow_name);
319                facts.set(&completion_key, FactValue::Boolean(true));
320                
321                let timestamp_key = format!("workflow.{}.completed_at", workflow_name);
322                facts.set(&timestamp_key, FactValue::Integer(chrono::Utc::now().timestamp()));
323                
324                println!("✔️ WORKFLOW COMPLETED: {}", workflow_name);
325            }
326            ActionType::SetWorkflowData { key, value } => {
327                // Store workflow data as facts with "workflow.data." prefix
328                let data_key = format!("workflow.data.{}", key);
329                let fact_value = Self::value_to_fact_value(value);
330                facts.set(&data_key, fact_value);
331                
332                println!("📊 WORKFLOW DATA SET: {} = {:?}", key, value);
333            }
334        }
335    }
336
337    /// Convert Value to FactValue
338    fn value_to_fact_value(value: &Value) -> FactValue {
339        match value {
340            Value::Number(n) => {
341                // Try integer first, fall back to float
342                if n.fract() == 0.0 {
343                    FactValue::Integer(*n as i64)
344                } else {
345                    FactValue::Float(*n)
346                }
347            }
348            Value::Integer(i) => FactValue::Integer(*i),
349            Value::String(s) => FactValue::String(s.clone()),
350            Value::Boolean(b) => FactValue::Boolean(*b),
351            Value::Null => FactValue::Null,
352            Value::Array(arr) => {
353                let fact_arr: Vec<FactValue> = arr.iter()
354                    .map(Self::value_to_fact_value)
355                    .collect();
356                FactValue::Array(fact_arr)
357            }
358            Value::Object(_) => {
359                // For now, treat objects as strings
360                FactValue::String("object".to_string())
361            }
362            Value::Expression(expr) => {
363                // For expressions, store as string - will be evaluated at runtime
364                FactValue::String(format!("[EXPR: {}]", expr))
365            }
366        }
367    }
368
369    /// Extract fact type dependencies from rule
370    fn extract_dependencies(rule: &TypedReteUlRule) -> Vec<String> {
371        let mut deps = Vec::new();
372        Self::extract_deps_from_node(&rule.node, &mut deps);
373
374        // Deduplicate
375        deps.sort();
376        deps.dedup();
377
378        deps
379    }
380
381    /// Recursively extract dependencies from ReteUlNode
382    fn extract_deps_from_node(node: &ReteUlNode, deps: &mut Vec<String>) {
383        match node {
384            ReteUlNode::UlAlpha(alpha) => {
385                // Extract fact type from field (e.g., "Person.age" -> "Person")
386                if let Some(dot_pos) = alpha.field.find('.') {
387                    let fact_type = alpha.field[..dot_pos].to_string();
388                    deps.push(fact_type);
389                }
390            }
391            ReteUlNode::UlMultiField { field, .. } => {
392                // Extract fact type from field (e.g., "Order.items" -> "Order")
393                if let Some(dot_pos) = field.find('.') {
394                    let fact_type = field[..dot_pos].to_string();
395                    deps.push(fact_type);
396                }
397            }
398            ReteUlNode::UlAnd(left, right) | ReteUlNode::UlOr(left, right) => {
399                Self::extract_deps_from_node(left, deps);
400                Self::extract_deps_from_node(right, deps);
401            }
402            ReteUlNode::UlNot(inner)
403            | ReteUlNode::UlExists(inner)
404            | ReteUlNode::UlForall(inner) => {
405                Self::extract_deps_from_node(inner, deps);
406            }
407            ReteUlNode::UlAccumulate { source_pattern, .. } => {
408                // Add source pattern as a dependency
409                deps.push(source_pattern.clone());
410            }
411            ReteUlNode::UlTerminal(_) => {
412                // Terminal nodes don't have dependencies
413            }
414        }
415    }
416
417    /// Evaluate expression for RETE engine (converts TypedFacts to Facts temporarily)
418    fn evaluate_expression_for_rete(expr: &str, typed_facts: &TypedFacts) -> Value {
419        // Convert TypedFacts to Facts for expression evaluation
420        use crate::engine::facts::Facts;
421
422        let mut facts = Facts::new();
423
424        // Copy all facts from TypedFacts to Facts
425        // RETE stores facts as "quantity" while GRL uses "Order.quantity"
426        // We need to support both formats
427        for (key, value) in typed_facts.get_all() {
428            let converted_value = Self::fact_value_to_value(value);
429
430            // Store both with and without prefix
431            // E.g., "quantity" -> both "quantity" and "Order.quantity"
432            facts.set(key, converted_value.clone());
433
434            // Also try to add with "Order." prefix if not already present
435            if !key.contains('.') {
436                facts.set(&format!("Order.{}", key), converted_value);
437            }
438        }
439
440        // Evaluate expression
441        match crate::expression::evaluate_expression(expr, &facts) {
442            Ok(result) => result,
443            Err(e) => {
444                // Silently fallback - this can happen with chained expressions in RETE
445                // due to working memory complexity
446                Value::String(expr.to_string())
447            }
448        }
449    }
450
451    /// Convert FactValue back to Value (reverse of value_to_fact_value)
452    fn fact_value_to_value(fact_value: &FactValue) -> Value {
453        match fact_value {
454            FactValue::String(s) => {
455                // Try to parse as number first
456                if let Ok(i) = s.parse::<i64>() {
457                    Value::Integer(i)
458                } else if let Ok(f) = s.parse::<f64>() {
459                    Value::Number(f)
460                } else if s == "true" {
461                    Value::Boolean(true)
462                } else if s == "false" {
463                    Value::Boolean(false)
464                } else {
465                    Value::String(s.clone())
466                }
467            }
468            FactValue::Integer(i) => Value::Integer(*i),
469            FactValue::Float(f) => Value::Number(*f),
470            FactValue::Boolean(b) => Value::Boolean(*b),
471            FactValue::Array(arr) => {
472                Value::Array(arr.iter().map(Self::fact_value_to_value).collect())
473            }
474            FactValue::Null => Value::Null,
475        }
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    #[test]
484    fn test_convert_simple_rule() {
485        let grl = r#"
486        rule "TestRule" salience 10 no-loop {
487            when
488                Person.age > 18
489            then
490                Person.is_adult = true;
491        }
492        "#;
493
494        let rules = GRLParser::parse_rules(grl).unwrap();
495        assert_eq!(rules.len(), 1);
496
497        let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
498        assert_eq!(rete_rule.name, "TestRule");
499        assert_eq!(rete_rule.priority, 10);
500        assert!(rete_rule.no_loop);
501    }
502
503    #[test]
504    fn test_extract_dependencies() {
505        let grl = r#"
506        rule "MultiTypeRule" {
507            when
508                Person.age > 18 && Order.amount > 1000
509            then
510                Person.premium = true;
511        }
512        "#;
513
514        let rules = GRLParser::parse_rules(grl).unwrap();
515        let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
516        let deps = GrlReteLoader::extract_dependencies(&rete_rule);
517
518        assert_eq!(deps.len(), 2);
519        assert!(deps.contains(&"Person".to_string()));
520        assert!(deps.contains(&"Order".to_string()));
521    }
522
523    #[test]
524    fn test_load_from_string() {
525        let grl = r#"
526        rule "Rule1" {
527            when
528                Person.age > 18
529            then
530                Person.is_adult = true;
531        }
532
533        rule "Rule2" {
534            when
535                Order.amount > 1000
536            then
537                Order.high_value = true;
538        }
539        "#;
540
541        let mut engine = IncrementalEngine::new();
542        let count = GrlReteLoader::load_from_string(grl, &mut engine).unwrap();
543
544        assert_eq!(count, 2);
545    }
546}