Skip to main content

rust_rule_engine/
lib.rs

1//! # Rust Rule Engine v1.19.2 - API Documentation Edition
2//!
3//! A high-performance rule engine for Rust with **RETE-UL algorithm**, **Array Membership (`in`) operator**,
4//! **String Methods (startsWith, endsWith)**, **Plugin System**, and **GRL (Grule Rule Language)** support.
5//! Features forward/backward chaining, stream processing, and production-ready performance.
6//!
7//! ## What's New in v1.19.2
8//!
9//! - **📚 Complete API Documentation**: All public APIs now have comprehensive documentation
10//! - **🔍 Missing Docs Lint**: Enabled `#![warn(missing_docs)]` to ensure API documentation quality
11//! - **📖 Enhanced RuleEngineBuilder Docs**: Detailed documentation with examples for builder pattern
12//! - **✨ Zero Breaking Changes**: Pure documentation improvement with no API changes
13//!
14//! ## Features
15//!
16//! - **🔌 Plugin System**: Modular plugin architecture with lifecycle management
17//! - **🛠️ Built-in Plugin Suite**: 44+ actions & 33+ functions for common operations  
18//! - **🔥 GRL Support**: Full Grule-compatible syntax
19//! - **🎯 Method Calls**: `$Object.method(args)` and property access
20//! - **📊 Knowledge Base**: Centralized rule management with salience
21//! - **💾 Working Memory**: Facts system for complex object interactions
22//! - **⚡ High Performance**: Optimized execution with cycle detection
23//! - **🔄 Arithmetic**: Complex calculations in conditions and actions
24//! - **🛡️ Type Safety**: Rust's type system ensures runtime safety
25//!
26//! ## Quick Start with Plugins
27//!
28//! ```rust
29//! use rust_rule_engine::*;
30//!
31//! fn main() -> Result<()> {
32//!     // Create Knowledge Base and Engine
33//!     let kb = KnowledgeBase::new("Demo");
34//!     let mut engine = RustRuleEngine::new(kb);
35//!     let mut facts = Facts::new();
36//!     
37//!     // Set up data
38//!     facts.set("user.age", Value::Number(25.0));
39//!     facts.set("user.premium", Value::Boolean(false));
40//!     
41//!     // Define GRL rule
42//!     let rule = r#"
43//!     rule "PremiumUpgrade" salience 10 {
44//!         when
45//!             user.age >= 18 && user.premium == false
46//!         then
47//!             user.premium = true;
48//!             user.discount = 0.1;
49//!     }
50//!     "#;
51//!     
52//!     // Parse and add rule to knowledge base
53//!     let rules = GRLParser::parse_rules(rule)?;
54//!     for r in rules {
55//!         engine.knowledge_base().add_rule(r)?;
56//!     }
57//!     
58//!     // Execute with facts
59//!     let result = engine.execute(&facts)?;
60//!     println!("User premium status: {:?}", facts.get("user.premium"));
61//!     
62//!     Ok(())
63//! }
64//! ```
65//!
66//! Built-in Plugin Suite provides comprehensive functionality for common operations:
67//!
68//! - **String Utilities**: 8 actions, 5 functions for text manipulation
69//! - **Math Operations**: 10 actions, 6 functions for calculations  
70//! - **Date/Time**: 8 actions, 7 functions for temporal operations
71//! - Actions: CurrentDate, CurrentTime, FormatDate, ParseDate, AddDays, AddHours, DateDiff, IsWeekend
72//! - Functions: now, today, dayOfWeek, dayOfYear, year, month, day
73//!
74//! ### Validation (8 actions, 6 functions)
75//! - Actions: ValidateEmail, ValidatePhone, ValidateUrl, ValidateRegex, ValidateRange, ValidateLength, ValidateNotEmpty, ValidateNumeric
76//! - Functions: isEmail, isPhone, isUrl, isNumeric, isEmpty, inRange
77//!
78//! ### Collections (10 actions, 9 functions)
79//! - Actions: ArrayLength, ArrayPush, ArrayPop, ArraySort, ArrayFilter, ArrayMap, ArrayFind, ObjectKeys, ObjectValues, ObjectMerge
80//! - Functions: length, contains, first, last, reverse, join, slice, keys, values
81//!
82//!   // Create engine
83//!   let mut engine = RustRuleEngine::new(kb);
84//!
85//!   // Create facts
86//!   let facts = Facts::new();
87//!   let user = FactHelper::create_user("john", 25, "john@email.com", "US", false);
88//!   facts.add_value("User", user)?;
89//!
90//!   // Execute rules
91//!   let result = engine.execute(&facts)?;
92//!   println!("Rules fired: {}", result.rules_fired);
93//!
94//!   Ok(())
95//!   }
96//! ```
97
98#![warn(missing_docs)]
99#![warn(clippy::all)]
100
101/// Backward chaining (goal-driven reasoning) - requires 'backward-chaining' feature
102#[cfg(feature = "backward-chaining")]
103#[allow(missing_docs)]
104pub mod backward;
105/// Rule execution engine and related components
106#[allow(missing_docs)]
107pub mod engine;
108/// Error types and result handling
109pub mod errors;
110/// Expression evaluation (arithmetic operations)
111#[allow(missing_docs)]
112pub mod expression;
113/// Rule parsing and language support
114#[allow(missing_docs)]
115pub mod parser;
116/// Built-in plugin system for extended functionality
117#[allow(missing_docs)]
118pub mod plugins;
119/// RETE module for rule evaluation
120#[allow(missing_docs)]
121pub mod rete;
122/// Streaming rule engine for real-time event processing
123#[cfg(feature = "streaming")]
124#[allow(missing_docs)]
125pub mod streaming;
126/// Core type definitions for values, operators, and actions
127pub mod types;
128
129// Re-export core types for easy access
130pub use errors::{Result, RuleEngineError};
131pub use types::{ActionType, LogicalOperator, Operator, Value};
132
133// Re-export Grule-style components
134pub use engine::engine::{EngineConfig, GruleExecutionResult, RustRuleEngine};
135pub use engine::facts::{FactHelper, Facts};
136pub use engine::knowledge_base::KnowledgeBase;
137pub use engine::rule::{Condition, ConditionGroup, Rule};
138
139// Re-export parsers
140pub use parser::grl::GRLParser;
141
142/// Builder pattern for creating a RustRuleEngine with various configurations.
143///
144/// Provides a fluent interface for configuring and building rule engines with
145/// rules loaded from files or inline GRL strings.
146///
147/// # Examples
148///
149/// ```rust
150/// use rust_rule_engine::RuleEngineBuilder;
151///
152/// // Build engine with inline rules
153/// let engine = RuleEngineBuilder::new()
154///     .with_inline_grl(r#"
155///         rule "VIP Check" {
156///             when user.points > 1000
157///             then user.vip = true;
158///         }
159///     "#)?
160///     .build();
161/// # Ok::<(), Box<dyn std::error::Error>>(())
162/// ```
163pub struct RuleEngineBuilder {
164    kb: KnowledgeBase,
165    config: EngineConfig,
166}
167
168impl RuleEngineBuilder {
169    /// Create a new RuleEngineBuilder with default configuration.
170    ///
171    /// Creates an empty knowledge base named "DefaultKB" and default engine configuration.
172    pub fn new() -> Self {
173        Self {
174            kb: KnowledgeBase::new("DefaultKB"),
175            config: EngineConfig::default(),
176        }
177    }
178
179    /// Add rules from a .grl file.
180    ///
181    /// Reads and parses GRL rules from the specified file path.
182    ///
183    /// # Errors
184    ///
185    /// Returns an error if the file cannot be read or if the GRL syntax is invalid.
186    pub fn with_rule_file<P: AsRef<std::path::Path>>(self, path: P) -> Result<Self> {
187        let content = std::fs::read_to_string(path)?;
188        let rules = GRLParser::parse_rules(&content)?;
189
190        for rule in rules {
191            self.kb.add_rule(rule)?;
192        }
193
194        Ok(self)
195    }
196
197    /// Add rules from inline GRL string.
198    ///
199    /// Parses GRL rules directly from a string.
200    ///
201    /// # Errors
202    ///
203    /// Returns an error if the GRL syntax is invalid.
204    pub fn with_inline_grl(self, grl_content: &str) -> Result<Self> {
205        let rules = GRLParser::parse_rules(grl_content)?;
206
207        for rule in rules {
208            self.kb.add_rule(rule)?;
209        }
210
211        Ok(self)
212    }
213
214    /// Set engine configuration.
215    ///
216    /// Overrides the default engine configuration with custom settings.
217    pub fn with_config(mut self, config: EngineConfig) -> Self {
218        self.config = config;
219        self
220    }
221
222    /// Build the RustRuleEngine.
223    ///
224    /// Consumes the builder and creates a configured rule engine instance.
225    pub fn build(self) -> RustRuleEngine {
226        RustRuleEngine::with_config(self.kb, self.config)
227    }
228}
229
230impl Default for RuleEngineBuilder {
231    fn default() -> Self {
232        Self::new()
233    }
234}