Skip to main content

persistence_and_hooks/
persistence_and_hooks.rs

1//! Persistence, an input router, and lifecycle hooks.
2//!
3//! Run with `cargo run --example persistence_and_hooks`.
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use clips_bindings::{Environment, Error, FactChange, FactEventKind, HookKind, Router, SaveScope};
9
10/// Feeds CLIPS a scripted answer instead of reading the terminal.
11struct ScriptedInput {
12    remaining: Vec<u8>,
13    unread: Vec<u8>,
14}
15
16impl ScriptedInput {
17    fn new(text: &str) -> Self {
18        // CLIPS reads a character at a time, so the script is consumed from the
19        // front.
20        Self {
21            remaining: text.bytes().rev().collect(),
22            unread: Vec::new(),
23        }
24    }
25}
26
27impl Router for ScriptedInput {
28    fn query(&mut self, logical_name: &str) -> bool {
29        logical_name == "stdin"
30    }
31
32    fn read(&mut self, _logical_name: &str) -> Option<u8> {
33        self.unread.pop().or_else(|| self.remaining.pop())
34    }
35
36    fn unread(&mut self, _logical_name: &str, character: u8) -> bool {
37        self.unread.push(character);
38        true
39    }
40}
41
42fn main() -> Result<(), Error> {
43    let mut environment = Environment::new()?;
44    environment.build("(deftemplate reading (slot sensor) (slot celsius))")?;
45
46    // Lifecycle hooks: watch what reset and the fact list do.
47    let events = Rc::new(RefCell::new(Vec::new()));
48    let recorded = events.clone();
49    environment
50        .add_hook("on-reset", HookKind::Reset, 0, move || {
51            recorded.borrow_mut().push("reset".to_owned());
52        })
53        .expect("hook name is unused");
54
55    let recorded = events.clone();
56    environment
57        .add_fact_hook("on-assert", FactEventKind::Asserted, 0, move |change| {
58            if let FactChange::Asserted(fact) = change {
59                recorded
60                    .borrow_mut()
61                    .push(format!("asserted {} #{}", fact.relation, fact.index));
62            }
63        })
64        .expect("hook name is unused");
65
66    environment.assert_string("(reading (sensor boiler) (celsius 91))")?;
67    environment.assert_string("(reading (sensor cabin) (celsius 65))")?;
68
69    // Persistence: save to a file, clear, and load it back.
70    let path = std::env::temp_dir().join("clips-bindings-example-facts.clp");
71    let path = path.to_str().expect("temp path is UTF-8");
72    let saved = environment.save_facts(path, SaveScope::Local)?;
73    println!("saved {saved} facts");
74
75    environment.reset();
76    println!("after reset: {} facts", environment.fact_count());
77
78    let loaded = environment.load_facts(path)?;
79    println!("loaded {loaded} facts");
80    std::fs::remove_file(path).expect("temp file exists");
81
82    // Input routers: CLIPS reads from Rust rather than the terminal.
83    environment
84        .register_router("scripted", 40, ScriptedInput::new("42 "))
85        .expect("router name is unused");
86    let read = environment.eval("(read)")?;
87    println!("read from Rust: {:?}", read.as_i64());
88    drop(read);
89    environment
90        .remove_router("scripted")
91        .expect("router is registered");
92
93    println!("hook events: {:?}", events.borrow());
94    environment.remove_hook("on-reset").expect("hook exists");
95    environment.remove_hook("on-assert").expect("hook exists");
96    Ok(())
97}