Skip to main content

rule_base/
rule_base.rs

1//! Loading a rule base, asserting facts, and running the engine.
2//!
3//! Run with `cargo run --example rule_base`.
4
5use clips_bindings::{Environment, Error, RuleFirePhase};
6
7fn main() -> Result<(), Error> {
8    let mut environment = Environment::new()?;
9
10    environment.load_str(
11        r#"
12        (deftemplate reading (slot sensor) (slot celsius))
13        (deftemplate alert (slot sensor) (slot level))
14
15        (defrule too-hot
16            (reading (sensor ?s) (celsius ?c&:(> ?c 80)))
17            =>
18            (assert (alert (sensor ?s) (level high))))
19
20        (defrule warm
21            (reading (sensor ?s) (celsius ?c&:(and (> ?c 60) (<= ?c 80))))
22            =>
23            (assert (alert (sensor ?s) (level warning))))
24        "#,
25    )?;
26
27    // Observe firings without touching CLIPS's own trace output.
28    environment
29        .add_rule_fire_hook("trace", RuleFirePhase::Before, 0, |rule| {
30            println!("firing {rule}");
31        })
32        .expect("rule-fire hook name is unused");
33
34    for (sensor, celsius) in [("boiler", 91), ("cabin", 65), ("cellar", 12)] {
35        environment
36            .fact_builder("reading")?
37            .symbol("sensor", sensor)?
38            .integer("celsius", celsius)?
39            .assert()?;
40    }
41
42    let fired = environment.run(None);
43    println!("{fired} rules fired");
44
45    let alerts = environment
46        .find_deftemplate("alert")?
47        .expect("alert exists");
48    for alert in environment.facts_in_template(&alerts) {
49        println!(
50            "alert: {} is {}",
51            alert.slot("sensor")?.as_str().unwrap_or("?"),
52            alert.slot("level")?.as_str().unwrap_or("?"),
53        );
54    }
55
56    Ok(())
57}