Safe, idiomatic Rust bindings for the CLIPS expert system.
This repository is a Cargo workspace containing two crates:
clips-sys: Low-level, unsafe FFI bindings generated viabindgento the CLIPS C API.clips: A safe, idiomatic Rust wrapper aroundclips-sys, providing memory-safe handles, lifetime-checked builders, and closures for user-defined functions (UDFs).
- Automatic C compilation and FFI binding generation via
bindgen. - Idiomatic builder APIs (
FactBuilder,FactModifier,MultifieldBuilder) checked at compile time. - Automatic memory management via reference-counted handles (
Environment,Fact,Multifield). - Safe registration of Rust closures as CLIPS user-defined functions (
Environment::add_udf). - Compile-time thread isolation (
Environmentand its handles are!Sendand!Sync; each thread must instantiate its ownEnvironment). - Tested against CLIPS 6.4.2.
Because clips-sys compiles the CLIPS C source and generates bindings at build time, you need:
- A C compiler (
gccorclang) libclang(required bybindgen)
You also need to populate the clips_source directory with the CLIPS core C source files before building:
wget -O clips_642.zip [https://sourceforge.net/projects/clipsrules/files/CLIPS/6.4.2/clips_core_source_642.zip/download](https://sourceforge.net/projects/clipsrules/files/CLIPS/6.4.2/clips_core_source_642.zip/download)
unzip clips_642.zip -d clips_temp
mkdir -p clips_source
mv clips_temp/clips_core_source_642/core/* clips_source/
rm -rf clips_temp clips_642.zipAdd clips to your Cargo.toml:
[dependencies]
clips = "0.1.0" # Or { path = "../rust-clips/clips" } for local developmentuse clips::{ClipsError, ClipsValue, Environment, Type};
fn main() -> Result<(), ClipsError> {
let mut env = Environment::new()?;
// Register a Rust closure as a CLIPS user-defined function
env.add_udf(
"double",
vec![Type::INTEGER | Type::VOID],
1,
1,
vec![vec![Type::INTEGER]],
|_env, ctx| {
if let Some(ClipsValue::Integer(n)) = ctx.get_next_argument(Type::INTEGER) {
ClipsValue::Integer(n * 2)
} else {
ClipsValue::Void()
}
},
)?;
// Define templates and rules
env.load_from_str(
r#"
(deftemplate person (slot name) (slot age))
(defrule print-double-age
(person (name ?name) (age ?age))
=>
(printout t ?name " doubled age: " (double ?age) crlf))
"#,
)?;
// Build and assert a fact
let alice = env
.fact_builder("person")?
.put_symbol("name", "Alice")?
.put_int("age", 30)?
.assert()?;
// Modify an existing fact
let alice = env
.fact_modifier(&alice)?
.put_int("age", 31)?
.modify()?;
// Run the inference engine (-1 = no firing limit)
env.run(-1);
// Explicitly retract the fact from the knowledge base
env.retract_fact(alice)?;
Ok(())
}cargo test