rust-rule-engine 1.20.1

A blazing-fast Rust rule engine with RETE algorithm, backward chaining inference, and GRL (Grule Rule Language) syntax. Features: forward/backward chaining, pattern matching, unification, O(1) rule indexing, TMS, expression evaluation, method calls, streaming with Redis state backend, watermarking, and custom functions. Production-ready for business rules, expert systems, real-time stream processing, and decision automation.
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
# Module Parsing Guide - How the Parser Reads & Distinguishes Modules

## 📖 Overview

The GRL parser uses a **3-step process** to read and organize rules into modules:

1. **Parse Module Definitions** - Find all `defmodule` blocks
2. **Register Modules** - Create ModuleManager with exports/imports
3. **Extract Module Context** - Assign each rule to its module

---

## Step 1: Parse Module Definitions

### What the Parser Looks For

```grl
defmodule MODULE_NAME {
  export: all
  import: SOURCE_MODULE (rules * (templates *))
}
```

### Regex Pattern Used

```rust
static DEFMODULE_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r#"defmodule\s+([A-Z_]\w*)\s*\{([^}]*)\}"#)
});
```

**This regex captures**:
- `defmodule` keyword
- `MODULE_NAME` (Group 1) - Must start with uppercase or underscore
- `{...}` content (Group 2) - Everything inside braces

### Example Parsing

```grl
defmodule SENSORS {
  export: all
}

defmodule CONTROL {
  import: SENSORS (rules * (templates temperature))
  export: all
}
```

**Parser Output**:
```
Match 1:
  - Group 1: "SENSORS"
  - Group 2: "export: all"

Match 2:
  - Group 1: "CONTROL"
  - Group 2: "import: SENSORS (rules * (templates temperature))\n  export: all"
```

---

## Step 2: Register Modules in ModuleManager

### Process

```rust
fn parse_and_register_module(&self, module_def: &str, manager: &mut ModuleManager) -> Result<()> {
    // Extract module name
    if let Some(captures) = DEFMODULE_REGEX.captures(module_def) {
        let module_name = captures.get(1).unwrap().as_str();  // e.g., "SENSORS"
        let module_body = captures.get(2).unwrap().as_str();  // e.g., "export: all"

        // 1. Create module in manager
        manager.create_module(&module_name)?;
        
        // 2. Parse export directive
        if let Some(export_type) = self.extract_directive(module_body, "export:") {
            let exports = if export_type.trim() == "all" {
                ExportList::All
            } else if export_type.trim() == "none" {
                ExportList::None
            }
            module.set_exports(exports);
        }
        
        // 3. Parse import directives
        for import_line in module_body.lines() {
            if import_line.trim().starts_with("import:") {
                self.parse_import_spec(&module_name, &import_spec, manager)?;
            }
        }
    }
}
```

### What Gets Registered

For this GRL:
```grl
defmodule SENSORS {
  export: all
}

defmodule CONTROL {
  import: SENSORS (rules * (templates temperature))
  export: all
}
```

**ModuleManager State After Registration**:
```
SENSORS
  ├── export: all
  └── imports: []

CONTROL
  ├── export: all
  └── imports: [
        {
          from_module: "SENSORS",
          rules: "*",
          templates: "temperature"
        }
      ]
```

---

## Step 3: Extract Module Context from Comments

### Key Algorithm: `extract_module_from_context()`

This is the **magic** - it assigns rules to modules based on comment markers:

```rust
fn extract_module_from_context(&self, grl_text: &str, rule_name: &str) -> String {
    // Step 1: Find the rule in the file
    if let Some(rule_pos) = grl_text.find(&format!("rule \"{}\"", rule_name)) {
        
        // Step 2: Look backward from rule position to find ;; MODULE: comment
        let before = &grl_text[..rule_pos];
        if let Some(module_pos) = before.rfind(";; MODULE:") {
            
            // Step 3: Extract module name from the comment line
            let after_module_marker = &before[module_pos + 10..];
            if let Some(end_of_line) = after_module_marker.find('\n') {
                let module_line = &after_module_marker[..end_of_line].trim();
                
                // Extract first word (e.g., "SENSORS" from "SENSORS - Temperature Monitoring")
                if let Some(first_word) = module_line.split_whitespace().next() {
                    return first_word.to_string();
                }
            }
        }
    }
    
    // If no comment found, default to MAIN
    "MAIN".to_string()
}
```

### How It Works - Step by Step

```grl
defmodule SENSORS {
  export: all
}

;; ============================================
;; MODULE: SENSORS
;; ============================================

rule "CheckTemperature" salience 100 {
  when temperature.value > 28
  then println("High temp");
}

;; ============================================
;; MODULE: CONTROL
;; ============================================

rule "ActivateCooling" salience 80 {
  when temperature.value > 28
  then hvac.state = "ON";
}
```

### Parsing Process for Each Rule

**For Rule "CheckTemperature":**

1. **Find rule position** in text
   ```
   Position = where 'rule "CheckTemperature"' appears
   ```

2. **Look backward** from that position to find `;; MODULE:`
   ```
   Text before rule:
   "defmodule SENSORS {...}
   
   ;; ============================================
   ;; MODULE: SENSORS        ← FOUND!
   ;; ============================================
   "
   ```

3. **Extract module name** from the comment
   ```
   Line: "MODULE: SENSORS"
   After "MODULE: ": "SENSORS"
   First word: "SENSORS" ← ASSIGNED MODULE
   ```

4. **Result**: `rule_modules.insert("CheckTemperature", "SENSORS")`

---

**For Rule "ActivateCooling":**

1. **Find rule position**
2. **Look backward** from that position to find `;; MODULE:`
   ```
   Text before rule:
   "...
   ;; ============================================
   ;; MODULE: CONTROL        ← FOUND THIS TIME!
   ;; ============================================
   "
   ```

3. **Extract**: "CONTROL"
4. **Result**: `rule_modules.insert("ActivateCooling", "CONTROL")`

---

## Full Parsing Workflow

```rust
pub fn parse_with_modules(grl_text: &str) -> Result<ParsedGRL> {
    // ========== STEP 1: Parse Module Definitions ==========
    // Find all: defmodule NAME { ... }
    for module_match in DEFMODULE_SPLIT_REGEX.find_iter(grl_text) {
        parse_and_register_module(module_def, &mut manager);  // Register in ModuleManager
    }
    
    // ========== STEP 2: Clean Text ==========
    // Remove all defmodule blocks to avoid interference with rule parsing
    let rules_text = DEFMODULE_SPLIT_REGEX.replace_all(grl_text, "");
    
    // ========== STEP 3: Parse Rules ==========
    let rules = parse_multiple_rules(&rules_text);
    
    // ========== STEP 4: Extract Module Context ==========
    // For each rule, find which module it belongs to
    for rule in rules {
        let module_name = extract_module_from_context(grl_text, &rule.name);
        
        // Track: rule_name → module_name
        result.rule_modules.insert(rule.name.clone(), module_name.clone());
        
        // Add rule to module
        manager.get_module_mut(&module_name)?.add_rule(&rule.name);
        
        result.rules.push(rule);
    }
    
    return ParsedGRL {
        rules: Vec<Rule>,           // All parsed rules
        module_manager: ModuleManager,  // Modules with imports/exports
        rule_modules: HashMap<String, String>,  // rule_name → module_name
    };
}
```

---

## Real-World Example

### Input GRL File

```grl
;; ============================================
;; MODULE: SENSORS
;; ============================================

defmodule SENSORS {
  export: all
}

rule "SensorCheckTemperature" salience 100 {
  when temperature.value > 28
  then println("High temp");
}

rule "SensorCheckHumidity" salience 90 {
  when humidity.value > 70
  then println("High humidity");
}

;; ============================================
;; MODULE: CONTROL
;; ============================================

defmodule CONTROL {
  import: SENSORS (rules * (templates temperature))
  export: all
}

rule "ControlActivateCooling" salience 80 {
  when temperature.value > 28 && hvac.state == "OFF"
  then hvac.state = "ON";
}
```

### Parsing Steps

**STEP 1 - Parse Module Definitions:**
```
Found: defmodule SENSORS { export: all }
Found: defmodule CONTROL { import: SENSORS ..., export: all }
```

**STEP 2 - Register Modules:**
```
ModuleManager created with:
  - SENSORS: export all, imports: []
  - CONTROL: export all, imports: [SENSORS]
```

**STEP 3 - Parse Rules (after removing defmodule blocks):**
```
Found: rule "SensorCheckTemperature" { ... }
Found: rule "SensorCheckHumidity" { ... }
Found: rule "ControlActivateCooling" { ... }
```

**STEP 4 - Extract Module Context:**

For `SensorCheckTemperature`:
```
Search backward from rule position...
Found: ";; MODULE: SENSORS"
Extract: "SENSORS"
Assign: SensorCheckTemperature → SENSORS
```

For `SensorCheckHumidity`:
```
Search backward from rule position...
Found: ";; MODULE: SENSORS"  (closest one going backward)
Extract: "SENSORS"
Assign: SensorCheckHumidity → SENSORS
```

For `ControlActivateCooling`:
```
Search backward from rule position...
Found: ";; MODULE: CONTROL"
Extract: "CONTROL"
Assign: ControlActivateCooling → CONTROL
```

### Final Output

```rust
ParsedGRL {
    rules: [
        Rule { name: "SensorCheckTemperature", ... },
        Rule { name: "SensorCheckHumidity", ... },
        Rule { name: "ControlActivateCooling", ... },
    ],
    
    module_manager: ModuleManager {
        modules: {
            "SENSORS": Module { 
                rules: ["SensorCheckTemperature", "SensorCheckHumidity"],
                exports: All,
                imports: []
            },
            "CONTROL": Module {
                rules: ["ControlActivateCooling"],
                exports: All,
                imports: [SENSORS]
            },
            "MAIN": Module {  // Auto-created
                rules: [],
                exports: All,
                imports: []
            }
        }
    },
    
    rule_modules: {
        "SensorCheckTemperature" → "SENSORS",
        "SensorCheckHumidity" → "SENSORS",
        "ControlActivateCooling" → "CONTROL",
    }
}
```

---

## Key Details

### Comment Format Requirements

The parser looks for **exactly**: `;; MODULE: NAME`

```grl
;; ============================================
;; MODULE: SENSORS          ← Parser extracts "SENSORS" (first word after "MODULE:")
;; ============================================
```

**Valid formats** (parser extracts first word):
- `;; MODULE: SENSORS` → "SENSORS"
- `;; MODULE: SENSORS - Temperature monitoring` → "SENSORS"
- `;; MODULE: CONTROL (Decision Making)` → "CONTROL"

**Invalid formats** (won't work):
- `; MODULE: SENSORS` (single semicolon)
- `MODULE: SENSORS` (no semicolons)
- `// MODULE: SENSORS` (C-style comment)
- `MODULE SENSORS` (missing colon)

### Module Name Requirements

From regex: `([A-Z_]\w*)`

- ✅ Must start with **uppercase letter** or underscore
- ✅ Can contain letters, numbers, underscores
- ❌ Cannot start with lowercase
- ❌ Cannot start with numbers

Valid:
- `SENSORS`
- `_PRIVATE`
- `CONTROL_V2`
- `A`

Invalid:
- `sensors` (lowercase)
- `1SENSORS` (starts with number)
- `control-v2` (hyphens not allowed)

### Default Module

If a rule has **no `;; MODULE:` comment** above it, it's assigned to **MAIN**:

```grl
defmodule SENSORS { export: all }

rule "CheckTemperature" { ... }  ;; → SENSORS (has comment above)

rule "RandomRule" { ... }        ;; → MAIN (no comment, not in any module section)
```

---

## Summary Table

| Step | Operation | Input | Output |
|------|-----------|-------|--------|
| 1 | Find defmodule blocks | GRL text | Module definitions |
| 2 | Register modules | Module definitions | ModuleManager |
| 3 | Parse rules | Cleaned GRL (no defmodule) | Rule objects |
| 4 | Extract context | Original GRL + rules | rule_modules HashMap |

---

## Debugging - How to Verify

```rust
use rust_rule_engine::parser::grl::GRLParser;
use std::fs;

let grl = fs::read_to_string("smart_home.grl")?;
let parsed = GRLParser::parse_with_modules(&grl)?;

// Check which module each rule is in
for (rule_name, module_name) in &parsed.rule_modules {
    println!("Rule '{}' belongs to module '{}'", rule_name, module_name);
}

// Check module structure
for module_name in parsed.module_manager.list_modules() {
    let module = parsed.module_manager.get_module(&module_name)?;
    println!("Module: {}", module_name);
    println!("  Rules: {:?}", module.get_rules());
    println!("  Imports: {:?}", module.get_imports());
}
```

---

## Common Issues & Solutions

### Issue 1: Rule Not Assigned to Module

**Problem**: Rule shows as "MAIN" instead of expected module

**Cause**: Missing or wrong comment format

**Solution**: Add correct comment
```grl
;; ============================================
;; MODULE: CONTROL              ← Correct format
;; ============================================

rule "MyRule" { ... }
```

### Issue 2: Module Name Extracted Incorrectly

**Problem**: Module shows as different name than expected

**Cause**: Parser takes first word after "MODULE:"

**Solution**: Make sure first word after "MODULE:" is the actual module name
```grl
;; Good
;; MODULE: SENSORS - Temperature

;; Bad  
;; MODULE: MY_SENSOR_DATA - This extracts "MY_SENSOR_DATA" only
```

### Issue 3: Rules Not in ModuleManager

**Problem**: Rule parsed but not added to module

**Cause**: Rule comments in wrong location

**Solution**: Ensure module section comment appears BEFORE the rules

```grl
;; ============================================
;; MODULE: SENSORS
;; ============================================
rule "Rule1" { ... }  ← Gets SENSORS
rule "Rule2" { ... }  ← Gets SENSORS

;; ============================================
;; MODULE: CONTROL
;; ============================================
rule "Rule3" { ... }  ← Gets CONTROL
```

---

## Performance Notes

- **Regex compilation**: Regexes are pre-compiled with `Lazy` (compiled once at startup)
- **Module parsing**: ~O(n) where n = number of module definitions
- **Context extraction**: ~O(n*m) where n = rules, m = average search distance backward
- **For typical files**: < 1ms parsing time

---

**Key Takeaway**: 
The parser uses **comment markers** (`; MODULE: NAME`) to determine which rules belong to which modules. The `;; MODULE: XXX` comment is a **context marker** that tells the parser "all rules after this belong to the XXX module until the next module marker."