rust-rule-engine 0.14.1

A high-performance rule engine for Rust with RETE-UL algorithm (2-24x faster), CLIPS-inspired features (Template System, Defglobal, Deffacts, Test CE, Conflict Resolution), GRL support, and ~98% Drools compatibility
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
# CLIPS Features Analysis & Learning Opportunities

## Overview

**CLIPS (C Language Integrated Production System)** is a powerful rule-based programming language developed by NASA in the 1980s. It's one of the most widely used production system tools, known for its robustness and extensive features.

---

## 🌟 CLIPS Key Strengths

### 1. **Object-Oriented Extensions (COOL)**

CLIPS Object-Oriented Language provides:
- Classes and instances
- Inheritance (single and multiple)
- Message passing
- Encapsulation
- Dynamic binding

**Status in Rust Engine**: ❌ Not implemented

**Example CLIPS**:
```clips
(defclass PERSON
  (is-a USER)
  (slot name)
  (slot age)
  (multislot hobbies))

(defmessage-handler PERSON birthday ()
  (bind ?self:age (+ ?self:age 1)))
```

**Learning Opportunity**: Implement OOP support for complex domain modeling.

---

### 2. **Deftemplate (Structured Facts)**

CLIPS uses structured facts with templates:

```clips
(deftemplate person
  (slot name)
  (slot age (type INTEGER))
  (slot salary (type FLOAT)))

(assert (person (name "John") (age 30) (salary 50000.0)))
```

**Status in Rust Engine**: ⚠️ Partial (TypedFacts, but no templates)

**What we're missing**:
- Schema definition
- Type validation
- Default values
- Constraints

**Learning Opportunity**: Add template/schema system for fact validation.

---

### 3. **Deffacts (Initial Facts)**

Define initial facts that are loaded automatically:

```clips
(deffacts initial-data
  (person (name "John") (age 30))
  (person (name "Jane") (age 25))
  (config (debug-mode TRUE)))
```

**Status in Rust Engine**: ❌ Not implemented

**Learning Opportunity**: Auto-loading initial facts from config.

---

### 4. **Deffunction & Defgeneric (Functions)**

CLIPS has built-in function definition system:

```clips
; Simple function
(deffunction calculate-discount (?amount ?rate)
  (* ?amount ?rate))

; Generic functions with polymorphism
(defgeneric greet)

(defmethod greet ((?person PERSON))
  (format t "Hello %s!" ?person:name))
```

**Status in Rust Engine**: ✅ Similar (Plugin functions, but not as elegant)

**Learning Opportunity**: Better function definition syntax in GRL.

---

### 5. **Defmodule (Module System)**

CLIPS has sophisticated module system for organizing rules:

```clips
(defmodule VALIDATION
  (export deftemplate person)
  (export deffunction validate-age))

(defmodule PROCESSING
  (import VALIDATION deftemplate person))
```

**Status in Rust Engine**: ⚠️ Partial (Agenda groups, but no real modules)

**Learning Opportunity**: True module system with imports/exports.

---

### 6. **Defglobal (Global Variables)**

Global variables that persist across rule firings:

```clips
(defglobal
  ?*debug* = TRUE
  ?*max-iterations* = 1000
  ?*discount-rate* = 0.15)
```

**Status in Rust Engine**: ❌ Not implemented (facts are temporary)

**Learning Opportunity**: Persistent global state management.

---

### 7. **Advanced Pattern Matching**

#### a) Pattern CE (Conditional Elements)

```clips
; Test CE
(defrule example
  (test (> (+ 2 2) 3))
  =>
  (printout t "Math works!"))

; OR CE
(defrule multiple-conditions
  (or (status "urgent")
      (priority high))
  =>
  (process-immediately))
```

**Status in Rust Engine**: ⚠️ Partial (has OR, but no test CE)

#### b) Logical Dependencies

```clips
(defrule derive-adult
  (person (name ?name) (age ?age&:(>= ?age 18)))
  =>
  (assert (adult ?name)))  ; Logically dependent

; If person fact retracted, adult fact auto-retracted!
```

**Status in Rust Engine**: ❌ Not implemented (Truth Maintenance)

**Learning Opportunity**: Truth Maintenance System (TMS).

---

### 8. **Certainty Factors / Fuzzy Logic**

CLIPS supports certainty factors for uncertain reasoning:

```clips
(defrule diagnose-flu
  (symptom fever ?cf1)
  (symptom cough ?cf2)
  =>
  (assert (disease flu (cf (combine-cf ?cf1 ?cf2)))))
```

**Status in Rust Engine**: ❌ Not implemented

**Learning Opportunity**: Probabilistic reasoning support.

---

### 9. **Conflict Resolution Strategies**

CLIPS has multiple conflict resolution strategies:

1. **Depth** (default): Prefer recently activated rules
2. **Breadth**: FIFO order
3. **Simplicity**: Prefer rules with fewer conditions
4. **Complexity**: Prefer rules with more conditions
5. **LEX**: Lexicographic ordering
6. **MEA**: Most specific rules first
7. **Random**: Random selection

**Status in Rust Engine**: ⚠️ Basic (Salience only)

**Learning Opportunity**: Multiple conflict resolution strategies.

---

### 10. **Watch & Debugging Facilities**

Extensive debugging support:

```clips
(watch facts)          ; Watch fact assertions
(watch rules)          ; Watch rule firings
(watch activations)    ; Watch agenda changes
(watch compilations)   ; Watch rule compilation

(matches rule-name)    ; Show what matches a rule
(agenda)               ; Show current agenda
```

**Status in Rust Engine**: ⚠️ Partial (Analytics, but not interactive)

**Learning Opportunity**: Interactive debugging mode.

---

### 11. **Backward Chaining**

CLIPS supports both forward and backward chaining:

```clips
(defrule backward-chain-goal
  (goal (find ?x))
  =>
  ; Backward chaining to find facts
  )
```

**Status in Rust Engine**: ❌ Not implemented (Forward chaining only)

**Learning Opportunity**: Backward chaining for goal-driven reasoning.

---

### 12. **External Function Integration**

Easy C/C++ integration:

```c
// C function
int my_function(void *env) {
    return EnvGetArgument(env, 1);
}

// Register in CLIPS
EnvDefineFunction(env, "my-function", 'i', my_function, "my-function");
```

**Status in Rust Engine**: ✅ Good (Plugin system, FFI possible)

---

### 13. **Incremental Reset**

CLIPS can save/restore state:

```clips
(save state.bin)       ; Save current state
(load state.bin)       ; Restore state
(bsave rules.dat)      ; Save compiled rules
(bload rules.dat)      ; Load compiled rules
```

**Status in Rust Engine**: ❌ Not implemented

**Learning Opportunity**: Serialization/deserialization of engine state.

---

## 📊 Feature Comparison Table

| Feature | CLIPS | Drools | Rust Native | Rust RETE | Priority |
|---------|-------|--------|-------------|-----------|----------|
| **Pattern Matching** |
| Basic Patterns ||||| - |
| Variable Binding ||||| Done |
| Multi-field Variables ||||| 🔴 High |
| Test CE ||||| 🟡 Medium |
| **Object-Oriented** |
| Classes ||||| 🔴 High |
| Inheritance ||||| 🟡 Medium |
| Message Passing ||||| 🟢 Low |
| **Data Structures** |
| Templates/Schemas |||| ⚠️ | 🔴 High |
| Deffacts ||||| 🟡 Medium |
| Defglobal ||||| 🟡 Medium |
| **Functions** |
| Deffunction ||||| 🟡 Medium |
| Generic Functions ||||| 🟢 Low |
| **Organization** |
| Modules ||| ⚠️ | ⚠️ | 🔴 High |
| Import/Export ||||| 🟡 Medium |
| **Advanced Reasoning** |
| Truth Maintenance ||||| 🟡 Medium |
| Backward Chaining ||||| 🟡 Medium |
| Certainty Factors ||||| 🟢 Low |
| **Conflict Resolution** |
| Multiple Strategies || ⚠️ ||| 🟡 Medium |
| Depth/Breadth ||||| 🟡 Medium |
| **Debugging** |
| Watch Facilities ||| ⚠️ || 🟡 Medium |
| Interactive Debugging ||||| 🟡 Medium |
| Matches Command ||||| 🟡 Medium |
| **Persistence** |
| Save/Load State ||||| 🟡 Medium |
| Binary Compilation ||||| 🟢 Low |

---

## 🎯 Top 10 Features to Learn from CLIPS

### Priority 1: HIGH 🔴

#### 1. **Template System (Deftemplate)**

Add schema definition for structured facts:

```rust
// Proposed syntax
template! {
    Person {
        name: String,
        age: i64,
        salary: f64,
        hobbies: Vec<String>,
    }
}

// Usage
let person = Person::new()
    .name("John")
    .age(30)
    .salary(50000.0)?; // Validates types!
```

**Benefits**:
- Type safety at compile time
- Schema validation
- Auto-complete in IDEs
- Better error messages

#### 2. **Module System**

Organize rules into modules:

```rust
module! {
    name: "Validation",
    exports: [Person, validate_age],
    rules: [
        "CheckAge",
        "ValidateEmail",
    ]
}

module! {
    name: "Processing",
    imports: [Validation::Person],
    rules: [
        "ProcessOrder",
    ]
}
```

**Benefits**:
- Better code organization
- Namespace isolation
- Reusable rule sets
- Clear dependencies

#### 3. **Multi-field Variables**

Pattern matching with arrays:

```rust
// Current: Can't match array elements individually
// Proposed:
rule "ProcessTags" {
    when
        Product.tags contains $tag
    then
        Tag.count[$tag] += 1;
}
```

**Benefits**:
- More expressive patterns
- Array/collection manipulation
- Better for complex data

### Priority 2: MEDIUM 🟡

#### 4. **Truth Maintenance System (TMS)**

Automatic dependency tracking:

```rust
rule "DeriveAdult" {
    when
        Person.age >= 18
    then
        assert_logical!(Person.is_adult = true);
        // If age changes to < 18, is_adult auto-retracts!
    }
}
```

**Benefits**:
- Automatic consistency
- No manual cleanup
- Complex reasoning support

#### 5. **Global Variables (Defglobal)**

Persistent state across firings:

```rust
globals! {
    DEBUG: bool = true,
    MAX_ITERATIONS: i32 = 1000,
    DISCOUNT_RATE: f64 = 0.15,
}

rule "UseGlobal" {
    when
        Order.amount > 100
    then
        Order.discount = DISCOUNT_RATE;
}
```

**Benefits**:
- Configuration management
- Shared state
- Constants

#### 6. **Initial Facts (Deffacts)**

Auto-load facts on startup:

```rust
deffacts! {
    name: "InitialConfig",
    facts: [
        Config { debug_mode: true },
        User { role: "admin", permissions: ["all"] },
    ]
}
```

**Benefits**:
- Bootstrap data
- Default configuration
- Test fixtures

#### 7. **Conflict Resolution Strategies**

Multiple agenda ordering strategies:

```rust
engine.set_conflict_resolution(ConflictStrategy::Depth);
// Or: Breadth, Simplicity, Complexity, LEX, MEA, Random
```

**Benefits**:
- Fine-grained control
- Different use cases
- Optimization opportunities

#### 8. **Test CE (Conditional Element)**

Arbitrary computations in patterns:

```rust
rule "ComplexCheck" {
    when
        Order.amount > 0 &&
        test(calculate_discount(Order.amount) > 10.0)
    then
        Order.has_discount = true;
}
```

**Benefits**:
- Complex computations
- More expressive
- Function calls in conditions

#### 9. **Interactive Debugging**

REPL-style debugging:

```rust
> engine.watch(WatchMode::Facts);
> engine.watch(WatchMode::Rules);
> engine.matches("RuleName");  // Show what matches
> engine.agenda();             // Show current agenda
> engine.step();               // Fire one rule
```

**Benefits**:
- Better debugging
- Understanding rule behavior
- Development speed

#### 10. **Backward Chaining**

Goal-driven reasoning:

```rust
rule "FindParent" backward {
    when
        goal: find(Person.parent = ?p)
    then
        // Backward chain to find parent
}
```

**Benefits**:
- Goal-directed search
- Efficient for some problems
- Complete reasoning

### Priority 3: LOW 🟢

- Generic functions (polymorphism)
- Certainty factors
- Binary compilation
- Message passing

---

## 🚀 Implementation Roadmap

### Phase 1: Essential CLIPS Features (Next Release)

**1. Template System**
```rust
// Add to src/rete/template.rs
pub struct Template {
    name: String,
    fields: HashMap<String, FieldType>,
    constraints: Vec<Constraint>,
}
```

**2. Module System**
```rust
// Add to src/engine/module.rs
pub struct Module {
    name: String,
    rules: Vec<Rule>,
    exports: Vec<String>,
    imports: HashMap<String, String>,
}
```

**3. Multi-field Variables**
```rust
// Extend pattern matching in src/rete/pattern.rs
pub enum PatternConstraint {
    // ... existing
    ArrayMatch { field: String, variable: Variable, operator: String },
}
```

### Phase 2: Advanced Features

**4. Truth Maintenance System**
```rust
// Add to src/rete/tms.rs
pub struct TruthMaintenanceSystem {
    dependencies: HashMap<FactHandle, Vec<FactHandle>>,
    justifications: HashMap<FactHandle, Justification>,
}
```

**5. Global Variables**
```rust
// Add to src/engine/globals.rs
pub struct GlobalStore {
    variables: HashMap<String, Value>,
    constants: HashMap<String, Value>,
}
```

### Phase 3: Developer Experience

**6. Interactive Debugger**
```rust
// Add to src/engine/debugger.rs
pub struct InteractiveDebugger {
    engine: RustRuleEngine,
    watch_modes: HashSet<WatchMode>,
    breakpoints: Vec<String>,
}
```

---

## 💡 Quick Wins (Easy to Implement)

### 1. Deffacts (Initial Facts)

**Effort**: Low
**Impact**: Medium

```rust
// Add to GRL syntax
deffacts "InitialData" {
    Person { name: "John", age: 30 }
    Config { debug: true }
}
```

Implementation: ~200 lines in grl_loader.rs

### 2. Defglobal (Global Variables)

**Effort**: Low
**Impact**: Medium

```rust
// Add global store to engine
pub struct GlobalStore {
    vars: HashMap<String, Value>,
}

// Access in rules
rule "UseGlobal" {
    when
        Order.amount > GLOBAL.min_amount
    then
        // ...
}
```

Implementation: ~150 lines

### 3. Test CE

**Effort**: Medium
**Impact**: High

```rust
rule "ComplexTest" {
    when
        Order.amount > 0 &&
        test(is_weekend() || is_holiday())
    then
        Order.expedite = false;
}
```

Implementation: ~300 lines in condition evaluator

---

## 📈 Expected Impact

| Feature | Dev Effort | User Impact | ROI |
|---------|-----------|-------------|-----|
| Template System | High | High | ⭐⭐⭐⭐⭐ |
| Module System | High | High | ⭐⭐⭐⭐⭐ |
| Deffacts | Low | Medium | ⭐⭐⭐⭐ |
| Defglobal | Low | Medium | ⭐⭐⭐⭐ |
| Test CE | Medium | High | ⭐⭐⭐⭐⭐ |
| Multi-field Vars | High | Medium | ⭐⭐⭐ |
| TMS | Very High | Medium | ⭐⭐ |
| Backward Chain | Very High | Low | ⭐⭐ |

---

## 🎯 Recommendations

### For Next Release (v0.10.0)

Implement these 3 features:

1. **Template System** (type-safe facts)
2. **Defglobal** (global variables)
3. **Test CE** (arbitrary conditions)

**Estimated effort**: 2-3 weeks
**User value**: High
**Drools compatibility**: Improved to ~97%

### Example Combined Usage

```rust
// templates.grl
template Person {
    name: String,
    age: Integer,
    salary: Float,
}

// globals.grl
defglobal {
    MIN_AGE: 18,
    MAX_DISCOUNT: 0.25,
}

// rules.grl
rule "AdultWithDiscount" {
    when
        Person.age >= MIN_AGE &&
        test(is_eligible_for_discount(Person.salary))
    then
        Person.discount = MAX_DISCOUNT;
}
```

---

## 🏆 CLIPS vs Our Engine: Current Score

| Category | CLIPS | Rust Engine | Gap |
|----------|-------|-------------|-----|
| Pattern Matching | 95% | 90% | -5% |
| OOP | 100% | 10% | -90% |
| Functions | 90% | 70% | -20% |
| Organization | 100% | 40% | -60% |
| Debugging | 100% | 60% | -40% |
| Performance | 70% | 95% | +25% ⭐ |
| Type Safety | 60% | 95% | +35% ⭐ |
| Modern API | 40% | 90% | +50% ⭐ |

**Overall**: CLIPS has more features, but we have better performance and type safety!

---

## 🎓 Key Takeaways

**What CLIPS does better**:
1. ✅ Comprehensive feature set (30+ years of development)
2. ✅ Excellent documentation and examples
3. ✅ Mature debugging tools
4. ✅ Module system
5. ✅ Template system
6. ✅ OOP support

**What we do better**:
1. ⚡ Performance (RETE-UL is faster)
2. 🦀 Type safety (Rust!)
3. 🔌 Plugin system
4. 📊 Modern analytics
5. 🌐 REST API integration
6. 🎯 Better GRL syntax

**Conclusion**: Learn from CLIPS's organizational features (templates, modules, globals) while keeping our performance and type safety advantages!

---

## 📚 References

- [CLIPS Official Site]http://www.clipsrules.net/
- [CLIPS User Guide]http://clipsrules.sourceforge.net/documentation/v630/ug.pdf
- [CLIPS vs Drools Comparison]https://www.researchgate.net/publication/220919862_A_Comparison_of_CLIPS_Jess_and_Drools

---

**Last Updated**: 2025-10-31
**Next Steps**: Implement template system and defglobal for v0.10.0