Skip to main content

rust_extensions/
rust_extensions.rs

1//! Extending CLIPS with a Rust function and capturing its output in Rust.
2//!
3//! Run with `cargo run --example rust_extensions`.
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use clips_bindings::{Environment, Error, Router, UdfReturn, UdfSignature, UdfType, UdfValue};
9
10/// Collects everything CLIPS prints instead of letting it reach the terminal.
11struct Capture {
12    lines: Rc<RefCell<Vec<String>>>,
13}
14
15impl Router for Capture {
16    fn query(&mut self, logical_name: &str) -> bool {
17        logical_name == "stdout"
18    }
19
20    fn write(&mut self, _logical_name: &str, text: &str) {
21        self.lines.borrow_mut().push(text.to_owned());
22    }
23}
24
25fn main() -> Result<(), Error> {
26    let mut environment = Environment::new()?;
27
28    let lines = Rc::new(RefCell::new(Vec::new()));
29    environment
30        .register_router(
31            "capture",
32            40,
33            Capture {
34                lines: lines.clone(),
35            },
36        )
37        .expect("router name is unused");
38
39    // A Rust function CLIPS can call like any built-in.
40    let signature = UdfSignature::builder(&[UdfType::Multifield])
41        .unbounded(1)
42        .default_arguments(&[UdfType::Integer])
43        .build();
44    environment
45        .add_udf("running-total", signature, |arguments| {
46            let mut total = 0;
47            let mut totals = Vec::with_capacity(arguments.len());
48            for argument in arguments {
49                let UdfValue::Integer(value) = argument else {
50                    return Err("running-total expects integers".into());
51                };
52                if *value < 0 {
53                    return Err("running-total does not accept negatives".into());
54                }
55                total += value;
56                totals.push(UdfReturn::Integer(total));
57            }
58            Ok(UdfReturn::Multifield(totals))
59        })
60        .expect("UDF name is unused");
61
62    environment.eval("(printout stdout (running-total 1 2 3 4) crlf)")?;
63
64    // Errors raised inside the callback are kept as typed Rust values and
65    // retrieved by registration name. The failed result is dropped before the
66    // environment is borrowed again.
67    let failed = environment.eval("(running-total -1)").is_err();
68    println!("bad call failed: {failed}");
69    println!(
70        "callback error: {:?}",
71        environment.take_udf_error("running-total")
72    );
73
74    environment
75        .remove_udf("running-total")
76        .expect("UDF is registered");
77    environment
78        .remove_router("capture")
79        .expect("router is registered");
80
81    println!("captured: {:?}", lines.borrow());
82    Ok(())
83}