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    /// Metadata: mapping from fact type to handle for retraction
232    /// Format: "FactType" -> FactHandle
233    pub(crate) fact_handles: HashMap<String, super::FactHandle>,
234}
235
236impl TypedFacts {
237    /// Create new empty facts collection
238    pub fn new() -> Self {
239        Self {
240            data: HashMap::new(),
241            fact_handles: HashMap::new(),
242        }
243    }
244    
245    /// Set metadata about which handle corresponds to which fact type
246    pub fn set_fact_handle(&mut self, fact_type: String, handle: super::FactHandle) {
247        self.fact_handles.insert(fact_type, handle);
248    }
249    
250    /// Get handle for a fact type (for retraction)
251    pub fn get_fact_handle(&self, fact_type: &str) -> Option<super::FactHandle> {
252        self.fact_handles.get(fact_type).copied()
253    }
254
255    /// Set a fact
256    pub fn set<K: Into<String>, V: Into<FactValue>>(&mut self, key: K, value: V) {
257        self.data.insert(key.into(), value.into());
258    }
259
260    /// Get a fact
261    pub fn get(&self, key: &str) -> Option<&FactValue> {
262        self.data.get(key)
263    }
264
265    /// Remove a fact
266    pub fn remove(&mut self, key: &str) -> Option<FactValue> {
267        self.data.remove(key)
268    }
269
270    /// Check if key exists
271    pub fn contains(&self, key: &str) -> bool {
272        self.data.contains_key(key)
273    }
274
275    /// Get all facts
276    pub fn get_all(&self) -> &HashMap<String, FactValue> {
277        &self.data
278    }
279
280    /// Clear all facts
281    pub fn clear(&mut self) {
282        self.data.clear();
283    }
284
285    /// Convert to string-based HashMap (for backward compatibility)
286    pub fn to_string_map(&self) -> HashMap<String, String> {
287        self.data
288            .iter()
289            .map(|(k, v)| (k.clone(), v.as_string()))
290            .collect()
291    }
292
293    /// Create from string-based HashMap (for backward compatibility)
294    pub fn from_string_map(map: &HashMap<String, String>) -> Self {
295        let mut facts = Self::new();
296        for (k, v) in map {
297            // Try to parse as different types
298            if let Ok(i) = v.parse::<i64>() {
299                facts.set(k.clone(), i);
300            } else if let Ok(f) = v.parse::<f64>() {
301                facts.set(k.clone(), f);
302            } else if let Ok(b) = v.parse::<bool>() {
303                facts.set(k.clone(), b);
304            } else {
305                facts.set(k.clone(), v.clone());
306            }
307        }
308        facts
309    }
310
311    /// Evaluate condition with typed comparison
312    pub fn evaluate_condition(&self, field: &str, operator: &str, value: &FactValue) -> bool {
313        if let Some(fact_value) = self.get(field) {
314            fact_value.compare(operator, value)
315        } else {
316            false
317        }
318    }
319}
320
321impl Default for TypedFacts {
322    fn default() -> Self {
323        Self::new()
324    }
325}
326
327/// Simple wildcard pattern matching
328/// Supports * (any characters) and ? (single character)
329fn wildcard_match(text: &str, pattern: &str) -> bool {
330    let text_chars: Vec<char> = text.chars().collect();
331    let pattern_chars: Vec<char> = pattern.chars().collect();
332
333    wildcard_match_impl(&text_chars, &pattern_chars, 0, 0)
334}
335
336fn wildcard_match_impl(text: &[char], pattern: &[char], ti: usize, pi: usize) -> bool {
337    if pi == pattern.len() {
338        return ti == text.len();
339    }
340
341    if pattern[pi] == '*' {
342        // Match zero or more characters
343        for i in ti..=text.len() {
344            if wildcard_match_impl(text, pattern, i, pi + 1) {
345                return true;
346            }
347        }
348        false
349    } else if ti < text.len() && (pattern[pi] == '?' || pattern[pi] == text[ti]) {
350        // Match single character or exact match
351        wildcard_match_impl(text, pattern, ti + 1, pi + 1)
352    } else {
353        false
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn test_fact_value_types() {
363        let s = FactValue::String("hello".to_string());
364        let i = FactValue::Integer(42);
365        let f = FactValue::Float(3.14);
366        let b = FactValue::Boolean(true);
367
368        assert_eq!(s.as_string(), "hello");
369        assert_eq!(i.as_integer(), Some(42));
370        assert_eq!(f.as_float(), Some(3.14));
371        assert_eq!(b.as_boolean(), Some(true));
372    }
373
374    #[test]
375    fn test_comparisons() {
376        let a = FactValue::Integer(10);
377        let b = FactValue::Integer(20);
378
379        assert!(a.compare("<", &b));
380        assert!(b.compare(">", &a));
381        assert!(a.compare("<=", &a));
382        assert!(a.compare("!=", &b));
383    }
384
385    #[test]
386    fn test_string_operations() {
387        let text = FactValue::String("hello world".to_string());
388        let pattern = FactValue::String("world".to_string());
389        let prefix = FactValue::String("hello".to_string());
390
391        assert!(text.compare("contains", &pattern));
392        assert!(text.compare("startsWith", &prefix));
393    }
394
395    #[test]
396    fn test_wildcard_matching() {
397        let text = FactValue::String("hello world".to_string());
398
399        assert!(text.compare("matches", &FactValue::String("hello*".to_string())));
400        assert!(text.compare("matches", &FactValue::String("*world".to_string())));
401        assert!(text.compare("matches", &FactValue::String("hello?world".to_string())));
402        assert!(!text.compare("matches", &FactValue::String("hello?earth".to_string())));
403    }
404
405    #[test]
406    fn test_array_operations() {
407        let arr = FactValue::Array(vec![
408            FactValue::Integer(1),
409            FactValue::Integer(2),
410            FactValue::Integer(3),
411        ]);
412
413        let val = FactValue::Integer(2);
414        assert!(val.compare("in", &arr));
415
416        let val2 = FactValue::Integer(5);
417        assert!(!val2.compare("in", &arr));
418    }
419
420    #[test]
421    fn test_typed_facts() {
422        let mut facts = TypedFacts::new();
423        facts.set("age", 25i64);
424        facts.set("name", "John");
425        facts.set("score", 95.5);
426        facts.set("active", true);
427
428        assert_eq!(facts.get("age").unwrap().as_integer(), Some(25));
429        assert_eq!(facts.get("name").unwrap().as_string(), "John");
430        assert_eq!(facts.get("score").unwrap().as_float(), Some(95.5));
431        assert_eq!(facts.get("active").unwrap().as_boolean(), Some(true));
432    }
433
434    #[test]
435    fn test_evaluate_condition() {
436        let mut facts = TypedFacts::new();
437        facts.set("age", 25i64);
438        facts.set("name", "John Smith");
439
440        assert!(facts.evaluate_condition("age", ">", &FactValue::Integer(18)));
441        assert!(facts.evaluate_condition("age", "<=", &FactValue::Integer(30)));
442        assert!(facts.evaluate_condition("name", "contains", &FactValue::String("Smith".to_string())));
443        assert!(facts.evaluate_condition("name", "startsWith", &FactValue::String("John".to_string())));
444    }
445}