rust_rule_engine/rete/
facts.rs

1//! Typed facts system for RETE-UL
2//!
3//! This module provides a strongly-typed facts system that supports:
4//! - Multiple data types (String, Integer, Float, Boolean, Array, Object)
5//! - Type-safe operations
6//! - Efficient conversions
7//! - Better operator support
8
9use std::collections::HashMap;
10use std::fmt;
11
12/// Strongly-typed fact value
13#[derive(Debug, Clone, PartialEq)]
14pub enum FactValue {
15    /// String value
16    String(String),
17    /// Integer value (i64)
18    Integer(i64),
19    /// Float value (f64)
20    Float(f64),
21    /// Boolean value
22    Boolean(bool),
23    /// Array of values
24    Array(Vec<FactValue>),
25    /// Null/None value
26    Null,
27}
28
29impl FactValue {
30    /// Convert to string representation
31    pub fn as_string(&self) -> String {
32        match self {
33            FactValue::String(s) => s.clone(),
34            FactValue::Integer(i) => i.to_string(),
35            FactValue::Float(f) => f.to_string(),
36            FactValue::Boolean(b) => b.to_string(),
37            FactValue::Array(arr) => format!("{:?}", arr),
38            FactValue::Null => "null".to_string(),
39        }
40    }
41
42    /// Try to convert to integer
43    pub fn as_integer(&self) -> Option<i64> {
44        match self {
45            FactValue::Integer(i) => Some(*i),
46            FactValue::Float(f) => Some(*f as i64),
47            FactValue::String(s) => s.parse().ok(),
48            FactValue::Boolean(b) => Some(if *b { 1 } else { 0 }),
49            _ => None,
50        }
51    }
52
53    /// Try to convert to float
54    pub fn as_float(&self) -> Option<f64> {
55        match self {
56            FactValue::Float(f) => Some(*f),
57            FactValue::Integer(i) => Some(*i as f64),
58            FactValue::String(s) => s.parse().ok(),
59            _ => None,
60        }
61    }
62
63    /// Convert to number (f64) for arithmetic operations
64    pub fn as_number(&self) -> Option<f64> {
65        match self {
66            FactValue::Float(f) => Some(*f),
67            FactValue::Integer(i) => Some(*i as f64),
68            FactValue::String(s) => s.parse().ok(),
69            _ => None,
70        }
71    }
72
73    /// Try to convert to boolean
74    pub fn as_boolean(&self) -> Option<bool> {
75        match self {
76            FactValue::Boolean(b) => Some(*b),
77            FactValue::Integer(i) => Some(*i != 0),
78            FactValue::String(s) => match s.to_lowercase().as_str() {
79                "true" | "yes" | "1" => Some(true),
80                "false" | "no" | "0" => Some(false),
81                _ => None,
82            },
83            FactValue::Null => Some(false),
84            _ => None,
85        }
86    }
87
88    /// Check if value is null
89    pub fn is_null(&self) -> bool {
90        matches!(self, FactValue::Null)
91    }
92
93    /// Compare with operator
94    pub fn compare(&self, operator: &str, other: &FactValue) -> bool {
95        match operator {
96            "==" => self == other,
97            "!=" => self != other,
98            ">" => self.compare_gt(other),
99            "<" => self.compare_lt(other),
100            ">=" => self.compare_gte(other),
101            "<=" => self.compare_lte(other),
102            "contains" => self.contains(other),
103            "startsWith" => self.starts_with(other),
104            "endsWith" => self.ends_with(other),
105            "matches" => self.matches_pattern(other),
106            "in" => self.in_array(other),
107            _ => false,
108        }
109    }
110
111    fn compare_gt(&self, other: &FactValue) -> bool {
112        match (self.as_float(), other.as_float()) {
113            (Some(a), Some(b)) => a > b,
114            _ => false,
115        }
116    }
117
118    fn compare_lt(&self, other: &FactValue) -> bool {
119        match (self.as_float(), other.as_float()) {
120            (Some(a), Some(b)) => a < b,
121            _ => false,
122        }
123    }
124
125    fn compare_gte(&self, other: &FactValue) -> bool {
126        match (self.as_float(), other.as_float()) {
127            (Some(a), Some(b)) => a >= b,
128            _ => self == other,
129        }
130    }
131
132    fn compare_lte(&self, other: &FactValue) -> bool {
133        match (self.as_float(), other.as_float()) {
134            (Some(a), Some(b)) => a <= b,
135            _ => self == other,
136        }
137    }
138
139    fn contains(&self, other: &FactValue) -> bool {
140        match (self, other) {
141            (FactValue::String(s), FactValue::String(pattern)) => s.contains(pattern),
142            (FactValue::Array(arr), val) => arr.contains(val),
143            _ => false,
144        }
145    }
146
147    fn starts_with(&self, other: &FactValue) -> bool {
148        match (self, other) {
149            (FactValue::String(s), FactValue::String(prefix)) => s.starts_with(prefix),
150            _ => false,
151        }
152    }
153
154    fn ends_with(&self, other: &FactValue) -> bool {
155        match (self, other) {
156            (FactValue::String(s), FactValue::String(suffix)) => s.ends_with(suffix),
157            _ => false,
158        }
159    }
160
161    fn matches_pattern(&self, other: &FactValue) -> bool {
162        match (self, other) {
163            (FactValue::String(s), FactValue::String(pattern)) => {
164                // Simple wildcard matching (* and ?)
165                wildcard_match(s, pattern)
166            }
167            _ => false,
168        }
169    }
170
171    fn in_array(&self, other: &FactValue) -> bool {
172        match other {
173            FactValue::Array(arr) => arr.contains(self),
174            _ => false,
175        }
176    }
177}
178
179impl fmt::Display for FactValue {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        write!(f, "{}", self.as_string())
182    }
183}
184
185impl From<String> for FactValue {
186    fn from(s: String) -> Self {
187        FactValue::String(s)
188    }
189}
190
191impl From<&str> for FactValue {
192    fn from(s: &str) -> Self {
193        FactValue::String(s.to_string())
194    }
195}
196
197impl From<i64> for FactValue {
198    fn from(i: i64) -> Self {
199        FactValue::Integer(i)
200    }
201}
202
203impl From<i32> for FactValue {
204    fn from(i: i32) -> Self {
205        FactValue::Integer(i as i64)
206    }
207}
208
209impl From<f64> for FactValue {
210    fn from(f: f64) -> Self {
211        FactValue::Float(f)
212    }
213}
214
215impl From<bool> for FactValue {
216    fn from(b: bool) -> Self {
217        FactValue::Boolean(b)
218    }
219}
220
221impl From<Vec<FactValue>> for FactValue {
222    fn from(arr: Vec<FactValue>) -> Self {
223        FactValue::Array(arr)
224    }
225}
226
227/// Typed facts collection
228#[derive(Debug, Clone)]
229pub struct TypedFacts {
230    data: HashMap<String, FactValue>,
231}
232
233impl TypedFacts {
234    /// Create new empty facts collection
235    pub fn new() -> Self {
236        Self {
237            data: HashMap::new(),
238        }
239    }
240
241    /// Set a fact
242    pub fn set<K: Into<String>, V: Into<FactValue>>(&mut self, key: K, value: V) {
243        self.data.insert(key.into(), value.into());
244    }
245
246    /// Get a fact
247    pub fn get(&self, key: &str) -> Option<&FactValue> {
248        self.data.get(key)
249    }
250
251    /// Remove a fact
252    pub fn remove(&mut self, key: &str) -> Option<FactValue> {
253        self.data.remove(key)
254    }
255
256    /// Check if key exists
257    pub fn contains(&self, key: &str) -> bool {
258        self.data.contains_key(key)
259    }
260
261    /// Get all facts
262    pub fn get_all(&self) -> &HashMap<String, FactValue> {
263        &self.data
264    }
265
266    /// Clear all facts
267    pub fn clear(&mut self) {
268        self.data.clear();
269    }
270
271    /// Convert to string-based HashMap (for backward compatibility)
272    pub fn to_string_map(&self) -> HashMap<String, String> {
273        self.data
274            .iter()
275            .map(|(k, v)| (k.clone(), v.as_string()))
276            .collect()
277    }
278
279    /// Create from string-based HashMap (for backward compatibility)
280    pub fn from_string_map(map: &HashMap<String, String>) -> Self {
281        let mut facts = Self::new();
282        for (k, v) in map {
283            // Try to parse as different types
284            if let Ok(i) = v.parse::<i64>() {
285                facts.set(k.clone(), i);
286            } else if let Ok(f) = v.parse::<f64>() {
287                facts.set(k.clone(), f);
288            } else if let Ok(b) = v.parse::<bool>() {
289                facts.set(k.clone(), b);
290            } else {
291                facts.set(k.clone(), v.clone());
292            }
293        }
294        facts
295    }
296
297    /// Evaluate condition with typed comparison
298    pub fn evaluate_condition(&self, field: &str, operator: &str, value: &FactValue) -> bool {
299        if let Some(fact_value) = self.get(field) {
300            fact_value.compare(operator, value)
301        } else {
302            false
303        }
304    }
305}
306
307impl Default for TypedFacts {
308    fn default() -> Self {
309        Self::new()
310    }
311}
312
313/// Simple wildcard pattern matching
314/// Supports * (any characters) and ? (single character)
315fn wildcard_match(text: &str, pattern: &str) -> bool {
316    let text_chars: Vec<char> = text.chars().collect();
317    let pattern_chars: Vec<char> = pattern.chars().collect();
318
319    wildcard_match_impl(&text_chars, &pattern_chars, 0, 0)
320}
321
322fn wildcard_match_impl(text: &[char], pattern: &[char], ti: usize, pi: usize) -> bool {
323    if pi == pattern.len() {
324        return ti == text.len();
325    }
326
327    if pattern[pi] == '*' {
328        // Match zero or more characters
329        for i in ti..=text.len() {
330            if wildcard_match_impl(text, pattern, i, pi + 1) {
331                return true;
332            }
333        }
334        false
335    } else if ti < text.len() && (pattern[pi] == '?' || pattern[pi] == text[ti]) {
336        // Match single character or exact match
337        wildcard_match_impl(text, pattern, ti + 1, pi + 1)
338    } else {
339        false
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn test_fact_value_types() {
349        let s = FactValue::String("hello".to_string());
350        let i = FactValue::Integer(42);
351        let f = FactValue::Float(3.14);
352        let b = FactValue::Boolean(true);
353
354        assert_eq!(s.as_string(), "hello");
355        assert_eq!(i.as_integer(), Some(42));
356        assert_eq!(f.as_float(), Some(3.14));
357        assert_eq!(b.as_boolean(), Some(true));
358    }
359
360    #[test]
361    fn test_comparisons() {
362        let a = FactValue::Integer(10);
363        let b = FactValue::Integer(20);
364
365        assert!(a.compare("<", &b));
366        assert!(b.compare(">", &a));
367        assert!(a.compare("<=", &a));
368        assert!(a.compare("!=", &b));
369    }
370
371    #[test]
372    fn test_string_operations() {
373        let text = FactValue::String("hello world".to_string());
374        let pattern = FactValue::String("world".to_string());
375        let prefix = FactValue::String("hello".to_string());
376
377        assert!(text.compare("contains", &pattern));
378        assert!(text.compare("startsWith", &prefix));
379    }
380
381    #[test]
382    fn test_wildcard_matching() {
383        let text = FactValue::String("hello world".to_string());
384
385        assert!(text.compare("matches", &FactValue::String("hello*".to_string())));
386        assert!(text.compare("matches", &FactValue::String("*world".to_string())));
387        assert!(text.compare("matches", &FactValue::String("hello?world".to_string())));
388        assert!(!text.compare("matches", &FactValue::String("hello?earth".to_string())));
389    }
390
391    #[test]
392    fn test_array_operations() {
393        let arr = FactValue::Array(vec![
394            FactValue::Integer(1),
395            FactValue::Integer(2),
396            FactValue::Integer(3),
397        ]);
398
399        let val = FactValue::Integer(2);
400        assert!(val.compare("in", &arr));
401
402        let val2 = FactValue::Integer(5);
403        assert!(!val2.compare("in", &arr));
404    }
405
406    #[test]
407    fn test_typed_facts() {
408        let mut facts = TypedFacts::new();
409        facts.set("age", 25i64);
410        facts.set("name", "John");
411        facts.set("score", 95.5);
412        facts.set("active", true);
413
414        assert_eq!(facts.get("age").unwrap().as_integer(), Some(25));
415        assert_eq!(facts.get("name").unwrap().as_string(), "John");
416        assert_eq!(facts.get("score").unwrap().as_float(), Some(95.5));
417        assert_eq!(facts.get("active").unwrap().as_boolean(), Some(true));
418    }
419
420    #[test]
421    fn test_evaluate_condition() {
422        let mut facts = TypedFacts::new();
423        facts.set("age", 25i64);
424        facts.set("name", "John Smith");
425
426        assert!(facts.evaluate_condition("age", ">", &FactValue::Integer(18)));
427        assert!(facts.evaluate_condition("age", "<=", &FactValue::Integer(30)));
428        assert!(facts.evaluate_condition("name", "contains", &FactValue::String("Smith".to_string())));
429        assert!(facts.evaluate_condition("name", "startsWith", &FactValue::String("John".to_string())));
430    }
431}