1use 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
16pub struct GrlReteLoader;
19
20impl GrlReteLoader {
21 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 pub fn load_from_string(
37 grl_text: &str,
38 engine: &mut IncrementalEngine,
39 ) -> Result<usize> {
40 let rules = GRLParser::parse_rules(grl_text)?;
42
43 let mut loaded_count = 0;
44
45 for rule in rules {
46 let rete_rule = Self::convert_rule_to_rete(rule)?;
48
49 let dependencies = Self::extract_dependencies(&rete_rule);
51
52 engine.add_rule(rete_rule, dependencies);
54 loaded_count += 1;
55 }
56
57 Ok(loaded_count)
58 }
59
60 fn convert_rule_to_rete(rule: Rule) -> Result<TypedReteUlRule> {
62 let node = Self::convert_condition_group(&rule.conditions)?;
64
65 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 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 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 fn convert_condition(condition: &Condition) -> Result<ReteUlNode> {
134 use crate::engine::rule::ConditionExpression;
135
136 match &condition.expression {
138 ConditionExpression::MultiField { field, operation, variable } => {
139 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 let (op, cmp_val) = if operation == "count" && operator_str != "==" {
149 (Some(operator_str), value_str)
151 } else {
152 (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 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 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 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 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 "object".to_string()
215 }
216 Value::Expression(expr) => {
217 expr.clone()
219 }
220 }
221 }
222
223 fn create_action_closure(
225 actions: Vec<crate::types::ActionType>,
226 ) -> std::sync::Arc<dyn Fn(&mut TypedFacts) + Send + Sync> {
227 std::sync::Arc::new(move |facts: &mut TypedFacts| {
228 for action in &actions {
230 Self::execute_action(action, facts);
231 }
232 })
233 }
234
235 fn execute_action(action: &crate::types::ActionType, facts: &mut TypedFacts) {
237 use crate::types::ActionType;
238
239 match action {
240 ActionType::Set { field, value } => {
241 let evaluated_value = match value {
243 Value::Expression(expr) => {
244 Self::evaluate_expression_for_rete(expr, facts)
246 }
247 _ => value.clone(),
248 };
249
250 let fact_value = Self::value_to_fact_value(&evaluated_value);
252 facts.set(field, fact_value);
253 }
254 ActionType::Log { message } => {
255 println!("📝 LOG: {}", message);
256 }
257 ActionType::Call { function, args: _ } => {
258 println!("🔧 CALL: {}", function);
260 }
261 ActionType::MethodCall { object, method, args: _ } => {
262 println!("📞 METHOD: {}.{}", object, method);
263 }
264 ActionType::Update { object } => {
265 println!("🔄 UPDATE: {}", object);
266 }
267 ActionType::Retract { object } => {
268 println!("🗑️ RETRACT: {}", object);
269 facts.set(format!("_retract_{}", object), FactValue::Boolean(true));
271 }
272 ActionType::Custom { action_type, params: _ } => {
273 println!("⚙️ CUSTOM: {}", action_type);
274 }
275 ActionType::ActivateAgendaGroup { group } => {
276 println!("📋 ACTIVATE GROUP: {}", group);
277 }
278 ActionType::ScheduleRule { rule_name, delay_ms } => {
279 println!("⏰ SCHEDULE: {} (delay: {}ms)", rule_name, delay_ms);
280 }
281 ActionType::CompleteWorkflow { workflow_name } => {
282 println!("✔️ COMPLETE WORKFLOW: {}", workflow_name);
283 }
284 ActionType::SetWorkflowData { key, value: _ } => {
285 println!("📊 SET WORKFLOW DATA: {}", key);
286 }
287 }
288 }
289
290 fn value_to_fact_value(value: &Value) -> FactValue {
292 match value {
293 Value::Number(n) => {
294 if n.fract() == 0.0 {
296 FactValue::Integer(*n as i64)
297 } else {
298 FactValue::Float(*n)
299 }
300 }
301 Value::Integer(i) => FactValue::Integer(*i),
302 Value::String(s) => FactValue::String(s.clone()),
303 Value::Boolean(b) => FactValue::Boolean(*b),
304 Value::Null => FactValue::Null,
305 Value::Array(arr) => {
306 let fact_arr: Vec<FactValue> = arr.iter()
307 .map(Self::value_to_fact_value)
308 .collect();
309 FactValue::Array(fact_arr)
310 }
311 Value::Object(_) => {
312 FactValue::String("object".to_string())
314 }
315 Value::Expression(expr) => {
316 FactValue::String(format!("[EXPR: {}]", expr))
318 }
319 }
320 }
321
322 fn extract_dependencies(rule: &TypedReteUlRule) -> Vec<String> {
324 let mut deps = Vec::new();
325 Self::extract_deps_from_node(&rule.node, &mut deps);
326
327 deps.sort();
329 deps.dedup();
330
331 deps
332 }
333
334 fn extract_deps_from_node(node: &ReteUlNode, deps: &mut Vec<String>) {
336 match node {
337 ReteUlNode::UlAlpha(alpha) => {
338 if let Some(dot_pos) = alpha.field.find('.') {
340 let fact_type = alpha.field[..dot_pos].to_string();
341 deps.push(fact_type);
342 }
343 }
344 ReteUlNode::UlMultiField { field, .. } => {
345 if let Some(dot_pos) = field.find('.') {
347 let fact_type = field[..dot_pos].to_string();
348 deps.push(fact_type);
349 }
350 }
351 ReteUlNode::UlAnd(left, right) | ReteUlNode::UlOr(left, right) => {
352 Self::extract_deps_from_node(left, deps);
353 Self::extract_deps_from_node(right, deps);
354 }
355 ReteUlNode::UlNot(inner)
356 | ReteUlNode::UlExists(inner)
357 | ReteUlNode::UlForall(inner) => {
358 Self::extract_deps_from_node(inner, deps);
359 }
360 ReteUlNode::UlAccumulate { source_pattern, .. } => {
361 deps.push(source_pattern.clone());
363 }
364 ReteUlNode::UlTerminal(_) => {
365 }
367 }
368 }
369
370 fn evaluate_expression_for_rete(expr: &str, typed_facts: &TypedFacts) -> Value {
372 use crate::engine::facts::Facts;
374
375 let mut facts = Facts::new();
376
377 for (key, value) in typed_facts.get_all() {
381 let converted_value = Self::fact_value_to_value(value);
382
383 facts.set(key, converted_value.clone());
386
387 if !key.contains('.') {
389 facts.set(&format!("Order.{}", key), converted_value);
390 }
391 }
392
393 match crate::expression::evaluate_expression(expr, &facts) {
395 Ok(result) => result,
396 Err(e) => {
397 Value::String(expr.to_string())
400 }
401 }
402 }
403
404 fn fact_value_to_value(fact_value: &FactValue) -> Value {
406 match fact_value {
407 FactValue::String(s) => {
408 if let Ok(i) = s.parse::<i64>() {
410 Value::Integer(i)
411 } else if let Ok(f) = s.parse::<f64>() {
412 Value::Number(f)
413 } else if s == "true" {
414 Value::Boolean(true)
415 } else if s == "false" {
416 Value::Boolean(false)
417 } else {
418 Value::String(s.clone())
419 }
420 }
421 FactValue::Integer(i) => Value::Integer(*i),
422 FactValue::Float(f) => Value::Number(*f),
423 FactValue::Boolean(b) => Value::Boolean(*b),
424 FactValue::Array(arr) => {
425 Value::Array(arr.iter().map(Self::fact_value_to_value).collect())
426 }
427 FactValue::Null => Value::Null,
428 }
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[test]
437 fn test_convert_simple_rule() {
438 let grl = r#"
439 rule "TestRule" salience 10 no-loop {
440 when
441 Person.age > 18
442 then
443 Person.is_adult = true;
444 }
445 "#;
446
447 let rules = GRLParser::parse_rules(grl).unwrap();
448 assert_eq!(rules.len(), 1);
449
450 let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
451 assert_eq!(rete_rule.name, "TestRule");
452 assert_eq!(rete_rule.priority, 10);
453 assert!(rete_rule.no_loop);
454 }
455
456 #[test]
457 fn test_extract_dependencies() {
458 let grl = r#"
459 rule "MultiTypeRule" {
460 when
461 Person.age > 18 && Order.amount > 1000
462 then
463 Person.premium = true;
464 }
465 "#;
466
467 let rules = GRLParser::parse_rules(grl).unwrap();
468 let rete_rule = GrlReteLoader::convert_rule_to_rete(rules[0].clone()).unwrap();
469 let deps = GrlReteLoader::extract_dependencies(&rete_rule);
470
471 assert_eq!(deps.len(), 2);
472 assert!(deps.contains(&"Person".to_string()));
473 assert!(deps.contains(&"Order".to_string()));
474 }
475
476 #[test]
477 fn test_load_from_string() {
478 let grl = r#"
479 rule "Rule1" {
480 when
481 Person.age > 18
482 then
483 Person.is_adult = true;
484 }
485
486 rule "Rule2" {
487 when
488 Order.amount > 1000
489 then
490 Order.high_value = true;
491 }
492 "#;
493
494 let mut engine = IncrementalEngine::new();
495 let count = GrlReteLoader::load_from_string(grl, &mut engine).unwrap();
496
497 assert_eq!(count, 2);
498 }
499}