1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! # Rust Rule Engine v1.20.0 - Performance Optimization Release
//!
//! A high-performance rule engine for Rust with **RETE-UL algorithm**, **Array Membership (`in`) operator**,
//! **String Methods (startsWith, endsWith)**, **Plugin System**, and **GRL (Grule Rule Language)** support.
//! Features forward/backward chaining, stream processing, and production-ready performance.
//!
//! ## What's New in v1.20.0
//!
//! - **⚡ Zero-Copy String Operations**: New `Value::as_string_ref()` reduces allocations in hot paths by 2x
//! - **🚀 Optimized Rule Iteration**: Index-based rule access eliminates `get_rules().clone()` overhead (41-683x faster)
//! - **💾 Memory Efficiency**: `Facts::with_value()` callback API reduces cloning by 40% in rule evaluation
//! - **📊 RETE Performance**: `FactValue::as_str()` with `Cow<str>` optimizes comparison and hashing
//! - **🔬 Comprehensive Benchmarks**: New `clone_optimization_benchmark` measures all optimized paths
//! - **✅ Zero Breaking Changes**: All 443 tests passing, backward compatible API additions only
//!
//! ### Performance Improvements
//!
//! This release focuses on eliminating unnecessary `.clone()` calls in critical execution paths:
//!
//! - **String Operators**: `Contains`, `StartsWith`, `EndsWith`, `Matches` now use zero-copy references
//! - **KnowledgeBase Operations**: Rule counting and lookup operations are 100-600x faster
//! - **Facts Access**: New callback-based API avoids cloning values during rule evaluation
//! - **RETE Memoization**: Optimized fact hashing reduces memory allocations by 60%
//!
//! Fixed critical unwraps in:
//! - Date parsing (`.and_hms_opt()` now properly propagates errors)
//! - String operations (`find`, `strip_prefix` use safe patterns)
//! - Iterator operations (clear invariant documentation)
//! - Character access (handles empty strings gracefully)
//!
//! ```rust
//! // Before v1.19.3 - Could panic
//! // naive_date.and_hms_opt(0, 0, 0).unwrap()
//!
//! // v1.19.3 - Returns Result with helpful error message
//! use rust_rule_engine::parser::grl::GRLParser;
//!
//! let result = GRLParser::parse_rules("malformed GRL...");
//! match result {
//! Ok(rules) => println!("Parsed {} rules", rules.len()),
//! Err(e) => println!("Parse error: {}", e), // Descriptive message, no panic
//! }
//! ```
//!
//! ## Features
//!
//! - **🔌 Plugin System**: Modular plugin architecture with lifecycle management
//! - **🛠️ Built-in Plugin Suite**: 44+ actions & 33+ functions for common operations
//! - **🔥 GRL Support**: Full Grule-compatible syntax
//! - **🎯 Method Calls**: `$Object.method(args)` and property access
//! - **📊 Knowledge Base**: Centralized rule management with salience
//! - **💾 Working Memory**: Facts system for complex object interactions
//! - **⚡ High Performance**: Optimized execution with cycle detection
//! - **🔄 Arithmetic**: Complex calculations in conditions and actions
//! - **🛡️ Type Safety**: Rust's type system ensures runtime safety
//!
//! ## Quick Start with Plugins
//!
//! ```rust
//! use rust_rule_engine::*;
//!
//! fn main() -> Result<()> {
//! // Create Knowledge Base and Engine
//! let kb = KnowledgeBase::new("Demo");
//! let mut engine = RustRuleEngine::new(kb);
//! let mut facts = Facts::new();
//!
//! // Set up data
//! facts.set("user.age", Value::Number(25.0));
//! facts.set("user.premium", Value::Boolean(false));
//!
//! // Define GRL rule
//! let rule = r#"
//! rule "PremiumUpgrade" salience 10 {
//! when
//! user.age >= 18 && user.premium == false
//! then
//! user.premium = true;
//! user.discount = 0.1;
//! }
//! "#;
//!
//! // Parse and add rule to knowledge base
//! let rules = GRLParser::parse_rules(rule)?;
//! for r in rules {
//! engine.knowledge_base().add_rule(r)?;
//! }
//!
//! // Execute with facts
//! let result = engine.execute(&facts)?;
//! println!("User premium status: {:?}", facts.get("user.premium"));
//!
//! Ok(())
//! }
//! ```
//!
//! Built-in Plugin Suite provides comprehensive functionality for common operations:
//!
//! - **String Utilities**: 8 actions, 5 functions for text manipulation
//! - **Math Operations**: 10 actions, 6 functions for calculations
//! - **Date/Time**: 8 actions, 7 functions for temporal operations
//! - Actions: CurrentDate, CurrentTime, FormatDate, ParseDate, AddDays, AddHours, DateDiff, IsWeekend
//! - Functions: now, today, dayOfWeek, dayOfYear, year, month, day
//!
//! ### Validation (8 actions, 6 functions)
//! - Actions: ValidateEmail, ValidatePhone, ValidateUrl, ValidateRegex, ValidateRange, ValidateLength, ValidateNotEmpty, ValidateNumeric
//! - Functions: isEmail, isPhone, isUrl, isNumeric, isEmpty, inRange
//!
//! ### Collections (10 actions, 9 functions)
//! - Actions: ArrayLength, ArrayPush, ArrayPop, ArraySort, ArrayFilter, ArrayMap, ArrayFind, ObjectKeys, ObjectValues, ObjectMerge
//! - Functions: length, contains, first, last, reverse, join, slice, keys, values
//!
//! // Create engine
//! let mut engine = RustRuleEngine::new(kb);
//!
//! // Create facts
//! let facts = Facts::new();
//! let user = FactHelper::create_user("john", 25, "john@email.com", "US", false);
//! facts.add_value("User", user)?;
//!
//! // Execute rules
//! let result = engine.execute(&facts)?;
//! println!("Rules fired: {}", result.rules_fired);
//!
//! Ok(())
//! }
//! ```
/// Backward chaining (goal-driven reasoning) - requires 'backward-chaining' feature
/// Rule execution engine and related components
/// Error types and result handling
/// Expression evaluation (arithmetic operations)
/// Rule parsing and language support
/// Built-in plugin system for extended functionality
/// RETE module for rule evaluation
/// Streaming rule engine for real-time event processing
/// Core type definitions for values, operators, and actions
// Re-export core types for easy access
pub use ;
pub use ;
// Re-export Grule-style components
pub use ;
pub use ;
pub use KnowledgeBase;
pub use ;
// Re-export parsers
pub use GRLParser;
/// Builder pattern for creating a RustRuleEngine with various configurations.
///
/// Provides a fluent interface for configuring and building rule engines with
/// rules loaded from files or inline GRL strings.
///
/// # Examples
///
/// ```rust
/// use rust_rule_engine::RuleEngineBuilder;
///
/// // Build engine with inline rules
/// let engine = RuleEngineBuilder::new()
/// .with_inline_grl(r#"
/// rule "VIP Check" {
/// when user.points > 1000
/// then user.vip = true;
/// }
/// "#)?
/// .build();
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```