Skip to main content

Environment

Struct Environment 

Source
pub struct Environment { /* private fields */ }
Expand description

An owning, single-thread-affine CLIPS environment.

CLIPS does not synchronize access to an environment, and registered Rust callbacks may capture thread-affine state. Consequently an environment and every handle borrowed from it must remain on the thread that created it.

Implementations§

Source§

impl Environment

Source

pub fn activations(&self) -> Activations<'_> ⓘ

Iterates the agenda in firing order.

Source

pub fn activation_count(&self) -> usize

The number of activations on the agenda.

Source

pub fn strategy(&self) -> Strategy

The current conflict-resolution strategy.

Source

pub fn set_strategy(&mut self, strategy: Strategy) -> Strategy

Sets the conflict-resolution strategy and returns the previous one.

CLIPS reorders every agenda to match.

Source

pub fn salience_evaluation(&self) -> SalienceEvaluation

When rule saliences are evaluated.

Source

pub fn set_salience_evaluation( &mut self, value: SalienceEvaluation, ) -> SalienceEvaluation

Sets when saliences are evaluated and returns the previous setting.

Source

pub fn refresh_agendas(&mut self)

Re-adds every module’s satisfied matches to its agenda, so matches that already fired can fire again.

Source

pub fn reorder_agendas(&mut self)

Re-sorts every agenda, which is needed after changing saliences.

Source

pub fn remove_all_activations(&mut self)

Removes every activation from every agenda.

Source

pub fn agenda_changed(&self) -> bool

Whether the agenda changed since this flag was last cleared.

Source

pub fn set_agenda_changed(&self, changed: bool)

Sets or clears the agenda-changed flag.

Source

pub fn refresh_module_agenda(&mut self, module: &str) -> Result<(), ModuleError>

Refreshes one module’s agenda instead of every module’s.

Named rather than handle-based so a module from another environment can never be passed to CLIPS.

Source

pub fn reorder_module_agenda(&mut self, module: &str) -> Result<(), ModuleError>

Reorders one module’s agenda instead of every module’s.

Source

pub fn clear_focus_stack(&mut self)

Empties the focus stack, so a run fires nothing until a module is focused again.

Source§

impl Environment

Source

pub fn class_defaults_mode(&self) -> ClassDefaultsMode

Whether accessor handlers are generated for classes defined from now on.

Source

pub fn set_class_defaults_mode( &mut self, mode: ClassDefaultsMode, ) -> ClassDefaultsMode

Sets the mode for classes defined afterwards and returns the previous mode. Existing classes keep the mode they were defined under.

Source

pub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError>

Undefines a class after resolving it in this environment.

Source

pub fn undefine_message_handler( &mut self, class_name: &str, handler_name: &str, kind: HandlerType, ) -> Result<(), ClassError>

Resolves the handler immediately before deletion, so no handler index is retained across a mutation of the class’s handler array.

Source§

impl Environment

Source

pub fn find_deftemplate(&self, name: &str) -> Result<Option<Deftemplate<'_>>>

Looks up a Deftemplate by name.

None if no construct of that name is visible from the current module.

Examples found in repository?
examples/rule_base.rs (line 46)
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}
Source§

impl Environment

Source

pub fn find_defrule(&self, name: &str) -> Result<Option<Defrule<'_>>>

Looks up a Defrule by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_deffacts(&self, name: &str) -> Result<Option<Deffacts<'_>>>

Looks up a Deffacts by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_defglobal(&self, name: &str) -> Result<Option<Defglobal<'_>>>

Looks up a Defglobal by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_deffunction(&self, name: &str) -> Result<Option<Deffunction<'_>>>

Looks up a Deffunction by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_defgeneric(&self, name: &str) -> Result<Option<Defgeneric<'_>>>

Looks up a Defgeneric by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_defclass(&self, name: &str) -> Result<Option<Defclass<'_>>>

Looks up a Defclass by name.

None if no construct of that name is visible from the current module.

Examples found in repository?
examples/objects_and_messages.rs (line 43)
7fn main() -> Result<(), Error> {
8    let mut environment = Environment::new()?;
9
10    environment.load_str(
11        r#"
12        (defclass ACCOUNT (is-a USER)
13            (slot holder)
14            (slot balance (type INTEGER) (default 0)))
15
16        (defmessage-handler ACCOUNT deposit (?amount)
17            (bind ?self:balance (+ ?self:balance ?amount))
18            ?self:balance)
19
20        (defmessage-handler ACCOUNT describe ()
21            (str-cat (send ?self get-holder) ": " (send ?self get-balance)))
22        "#,
23    )?;
24
25    let account = environment.make_instance("(ada of ACCOUNT (holder Ada) (balance 100))")?;
26    println!(
27        "class: {}",
28        account.class().expect("instance has a class").name()
29    );
30
31    let balance = account.send("deposit")?.integer(250).send()?;
32    println!("after deposit: {:?}", balance.as_i64());
33    drop(balance);
34
35    // A direct slot write bypasses message passing entirely.
36    account.put_integer("balance", 1_000)?;
37
38    let description = account.send("describe")?.send()?;
39    println!("{}", description.as_str().unwrap_or(""));
40    drop(description);
41    drop(account);
42
43    let class = environment.find_defclass("ACCOUNT")?.expect("class exists");
44    for slot in class.slots(false) {
45        let descriptor = class.slot(&slot).expect("slot name has no NUL");
46        if let Some(descriptor) = descriptor {
47            println!(
48                "slot {slot}: types {:?} default {:?}",
49                descriptor.allowed_types(),
50                descriptor.default_value()
51            );
52        }
53    }
54
55    Ok(())
56}
Source§

impl Environment

Source

pub fn find_definstances(&self, name: &str) -> Result<Option<Definstances<'_>>>

Looks up a Definstances by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn find_defmodule(&self, name: &str) -> Result<Option<Defmodule<'_>>>

Looks up a Defmodule by name.

None if no construct of that name is visible from the current module.

Source§

impl Environment

Source

pub fn deftemplates(&self) -> Deftemplates<'_>

Iterates every deftemplate, including the implied templates CLIPS creates for ordered facts.

Source

pub fn defrules(&self) -> Defrules<'_>

Iterates every defrule.

Source

pub fn deffacts(&self) -> DeffactsIter<'_>

Iterates every deffacts.

Source

pub fn defglobals(&self) -> Defglobals<'_>

Iterates every defglobal.

Source

pub fn deffunctions(&self) -> Deffunctions<'_>

Iterates every deffunction.

Source

pub fn defgenerics(&self) -> Defgenerics<'_>

Iterates every defgeneric.

Source

pub fn defclasses(&self) -> Defclasses<'_>

Iterates every defclass, including the built-in classes such as USER and OBJECT.

Source

pub fn definstances(&self) -> DefinstancesIter<'_>

Iterates every definstances construct.

Source

pub fn defmodules(&self) -> Defmodules<'_>

Iterates every defmodule, starting with MAIN.

Source§

impl Environment

Source

pub fn undefine_deftemplate(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_defrule(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_deffacts(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_defglobal(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_deffunction(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_defgeneric(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_defclass(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn undefine_definstances(&mut self, name: &str) -> Result<bool>

Undefines the named construct, returning whether it was removed.

Ok(false) means no construct of that name exists, or CLIPS refused because it is in use; is_deletable on the corresponding handle distinguishes the two. Resolving the name here, under &mut self, is what makes this safe: no handle can outlive the construct it names.

Source

pub fn set_rule_breakpoint(&mut self, name: &str) -> Result<bool>

Sets a breakpoint on the named rule, returning whether the rule exists.

A run stops before firing a rule with a breakpoint.

Source

pub fn remove_rule_breakpoint(&mut self, name: &str) -> Result<bool>

Removes the named rule’s breakpoint.

Returns false if no such rule exists or it had no breakpoint.

Source

pub fn refresh_rule(&mut self, name: &str) -> Result<bool>

Re-adds the named rule’s satisfied matches to the agenda, so matches that already fired can fire again.

Returns whether the rule exists.

Source

pub fn remove_all_breakpoints(&mut self)

Removes every breakpoint in the environment.

Source

pub fn breakpoint_rule_names(&self) -> Vec<String>

The names of all rules that currently have a breakpoint.

CLIPS’s own listing writes to a router; this walks the rules instead so the result is owned data rather than captured output.

Source§

impl Environment

Source

pub fn insert_data<T: Any>(&mut self, value: T) -> Option<T>

Attaches a value to this environment, replacing and returning any previous value of the same type.

Source

pub fn data<T: Any>(&self) -> Option<&T>

Borrows the value of type T attached to this environment.

Source

pub fn data_mut<T: Any>(&mut self) -> Option<&mut T>

Mutably borrows the value of type T attached to this environment.

Source

pub fn remove_data<T: Any>(&mut self) -> Option<T>

Detaches and returns the value of type T.

Source§

impl Environment

Source

pub fn new() -> Result<Self>

Creates a CLIPS environment, destroyed when the value is dropped.

Environments are independent: constructs, facts, and interned atoms belong to exactly one, and mixing handles between them is refused with Error::ForeignEnvironment.

Examples found in repository?
examples/rule_base.rs (line 8)
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}
More examples
Hide additional examples
examples/objects_and_messages.rs (line 8)
7fn main() -> Result<(), Error> {
8    let mut environment = Environment::new()?;
9
10    environment.load_str(
11        r#"
12        (defclass ACCOUNT (is-a USER)
13            (slot holder)
14            (slot balance (type INTEGER) (default 0)))
15
16        (defmessage-handler ACCOUNT deposit (?amount)
17            (bind ?self:balance (+ ?self:balance ?amount))
18            ?self:balance)
19
20        (defmessage-handler ACCOUNT describe ()
21            (str-cat (send ?self get-holder) ": " (send ?self get-balance)))
22        "#,
23    )?;
24
25    let account = environment.make_instance("(ada of ACCOUNT (holder Ada) (balance 100))")?;
26    println!(
27        "class: {}",
28        account.class().expect("instance has a class").name()
29    );
30
31    let balance = account.send("deposit")?.integer(250).send()?;
32    println!("after deposit: {:?}", balance.as_i64());
33    drop(balance);
34
35    // A direct slot write bypasses message passing entirely.
36    account.put_integer("balance", 1_000)?;
37
38    let description = account.send("describe")?.send()?;
39    println!("{}", description.as_str().unwrap_or(""));
40    drop(description);
41    drop(account);
42
43    let class = environment.find_defclass("ACCOUNT")?.expect("class exists");
44    for slot in class.slots(false) {
45        let descriptor = class.slot(&slot).expect("slot name has no NUL");
46        if let Some(descriptor) = descriptor {
47            println!(
48                "slot {slot}: types {:?} default {:?}",
49                descriptor.allowed_types(),
50                descriptor.default_value()
51            );
52        }
53    }
54
55    Ok(())
56}
examples/rust_extensions.rs (line 26)
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}
examples/persistence_and_hooks.rs (line 43)
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}
Source

pub fn clear(&mut self) -> Result<()>

Removes every construct, fact, and instance.

Fails with Error::ClearRejected if a clear-ready hook vetoes it. Taking &mut self is what makes this safe: no handle into the environment can be alive across it.

Source

pub fn reset(&mut self)

Removes all facts and instances, then asserts the deffacts and creates the definstances. Constructs are kept.

Examples found in repository?
examples/persistence_and_hooks.rs (line 75)
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}
Source

pub fn run(&mut self, limit: Option<u64>) -> u64

Fires rules until the agenda empties, returning how many fired.

limit caps the number of firings; None means no limit.

Examples found in repository?
examples/rule_base.rs (line 42)
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}
Source

pub fn halt_execution(&self) -> bool

Whether evaluation is currently halted.

This is set when Environment::eval fails, and reads true until the next evaluation, which clears it. It does not report that a run was stopped by (halt): Environment::run clears the flag on entry and (halt) sets the separate rule-halt flag, so neither survives a run.

The flag exists so an embedding application can interrupt CLIPS from a signal handler or another thread of control. This crate cannot offer that: setting it takes &mut self and so cannot overlap a run, and CLIPS 6.4.2 hands Rust callbacks no environment to reach it through.

Source

pub fn set_halt_execution(&mut self, halt: bool)

Sets or clears the evaluation-halt flag.

Its only useful direction is clearing. Setting it does not stop the next Environment::run, which clears the flag on entry — see Environment::halt_execution for why no safe API can interrupt a run.

Source

pub fn halt_rules(&self) -> bool

Whether rule firing is halted, as (halt) sets during a run.

Environment::run clears this both on entry and on return, so outside a run it always reads false.

Source

pub fn set_halt_rules(&mut self, halt: bool)

Sets or clears the rule-halt flag.

Run overwrites it on entry, so this cannot stop the next run; it is bound for completeness against the CLIPS API rather than as a working interruption mechanism. CLIPS’s Halt function is deliberately not bound: it does exactly set_halt_rules(true) and so is equally inert, under a name that promises otherwise.

Source

pub fn beta_memory_resizing(&self) -> bool

Whether the rule network resizes its beta memories dynamically.

Source

pub fn set_beta_memory_resizing(&mut self, resize: bool) -> bool

Sets beta-memory resizing and returns the previous setting.

Source

pub fn write(&self, text: &str) -> Result<()>

Writes text to the stdout logical name, without a trailing newline.

Output reaches whichever crate::Router claims the name, so this is how Rust emits into the same stream CLIPS constructs print to.

Source

pub fn writeln(&self, text: &str) -> Result<()>

Writes text to stdout followed by a newline.

Source

pub fn write_to(&self, logical_name: &str, text: &str) -> Result<()>

Writes text to an arbitrary logical name, such as werror or a name a registered router claims.

Source

pub fn build(&mut self, construct: &str) -> Result<()>

Defines one construct from CLIPS source text, for example "(deftemplate person (slot name))".

CLIPS’s own diagnostics go to the werror logical name; register a Router for it to capture them.

Examples found in repository?
examples/persistence_and_hooks.rs (line 44)
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}
Source

pub fn load(&mut self, path: &str) -> Result<()>

Loads constructs from a file.

Source

pub fn load_str(&mut self, source: &str) -> Result<()>

Loads constructs from CLIPS source text.

CLIPS reports only success or failure here, with no error detail, so a failure is always LoadError::Parsing. Install a parser-error hook with Environment::set_parser_error_hook for the diagnostics.

Examples found in repository?
examples/rule_base.rs (lines 10-25)
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}
More examples
Hide additional examples
examples/objects_and_messages.rs (lines 10-23)
7fn main() -> Result<(), Error> {
8    let mut environment = Environment::new()?;
9
10    environment.load_str(
11        r#"
12        (defclass ACCOUNT (is-a USER)
13            (slot holder)
14            (slot balance (type INTEGER) (default 0)))
15
16        (defmessage-handler ACCOUNT deposit (?amount)
17            (bind ?self:balance (+ ?self:balance ?amount))
18            ?self:balance)
19
20        (defmessage-handler ACCOUNT describe ()
21            (str-cat (send ?self get-holder) ": " (send ?self get-balance)))
22        "#,
23    )?;
24
25    let account = environment.make_instance("(ada of ACCOUNT (holder Ada) (balance 100))")?;
26    println!(
27        "class: {}",
28        account.class().expect("instance has a class").name()
29    );
30
31    let balance = account.send("deposit")?.integer(250).send()?;
32    println!("after deposit: {:?}", balance.as_i64());
33    drop(balance);
34
35    // A direct slot write bypasses message passing entirely.
36    account.put_integer("balance", 1_000)?;
37
38    let description = account.send("describe")?.send()?;
39    println!("{}", description.as_str().unwrap_or(""));
40    drop(description);
41    drop(account);
42
43    let class = environment.find_defclass("ACCOUNT")?.expect("class exists");
44    for slot in class.slots(false) {
45        let descriptor = class.slot(&slot).expect("slot name has no NUL");
46        if let Some(descriptor) = descriptor {
47            println!(
48                "slot {slot}: types {:?} default {:?}",
49                descriptor.allowed_types(),
50                descriptor.default_value()
51            );
52        }
53    }
54
55    Ok(())
56}
Source

pub fn eval(&mut self, expression: &str) -> Result<Value<'_>>

Evaluates a CLIPS expression and returns its retained result.

This takes &mut self because an expression can assert, retract, or redefine anything, which would invalidate outstanding handles.

Examples found in repository?
examples/rust_extensions.rs (line 62)
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}
More examples
Hide additional examples
examples/persistence_and_hooks.rs (line 86)
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}
Source

pub fn create_integer(&self, value: i64) -> Value<'_>

Creates a retained CLIPS integer.

Source

pub fn create_float(&self, value: f64) -> Value<'_>

Creates a retained CLIPS float.

Source

pub fn create_boolean(&self, value: bool) -> Value<'_>

Creates the retained CLIPS TRUE or FALSE symbol.

Source

pub fn create_symbol(&self, value: &str) -> Result<Value<'_>>

Creates a retained CLIPS symbol.

Source

pub fn create_string(&self, value: &str) -> Result<Value<'_>>

Creates a retained CLIPS string.

Source

pub fn create_instance_name(&self, value: &str) -> Result<Value<'_>>

Creates a retained CLIPS instance name.

Source

pub fn string_to_multifield(&self, source: &str) -> Result<Multifield<'_>>

Parses source as a sequence of CLIPS fields and returns them as a retained multifield.

Source

pub fn assert_string(&self, source: &str) -> Result<Fact<'_>>

Asserts a fact from CLIPS text, for example "(person (name ada))".

Use Environment::fact_builder to avoid formatting and re-parsing slot values.

Examples found in repository?
examples/persistence_and_hooks.rs (line 66)
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}
Source

pub fn fact_builder(&self, template: &str) -> Result<FactBuilder<'_>>

Starts building a fact of the named deftemplate.

Examples found in repository?
examples/rule_base.rs (line 36)
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}
Source

pub fn facts(&self) -> Facts<'_> ⓘ

Iterates every fact in index order.

Source

pub fn fact_count(&self) -> usize

The number of facts currently asserted.

Examples found in repository?
examples/persistence_and_hooks.rs (line 76)
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}
Source

pub fn instance_builder(&self, class: &str) -> Result<InstanceBuilder<'_>>

Starts building an instance of the named defclass.

Source

pub fn instances(&self) -> Instances<'_> ⓘ

Iterates every instance in every module.

Source

pub fn multifield_builder( &self, capacity: usize, ) -> Result<MultifieldBuilder<'_>>

Starts building a multifield. capacity is a hint; the builder grows as needed.

Source

pub fn function_call(&self, capacity: usize) -> Result<FunctionCall<'_>>

Starts building a call to a CLIPS function. capacity is a hint for the number of arguments.

Source

pub fn register_router<R: Router>( &mut self, name: &str, priority: i32, router: R, ) -> Result<(), RouterError>

Registers a router, which is how Rust captures CLIPS output and supplies its input.

Higher priority wins when several routers claim the same logical name; CLIPS’s own console routers sit at priority 0 to 30. The router is owned by the environment and dropped when removed or when the environment is.

Examples found in repository?
examples/rust_extensions.rs (lines 30-36)
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}
More examples
Hide additional examples
examples/persistence_and_hooks.rs (line 84)
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}
Source

pub fn remove_router(&mut self, name: &str) -> Result<(), RouterError>

Unregisters a router and drops it.

If CLIPS refuses the removal the router is kept, so the registration and the owned callback never disagree.

Examples found in repository?
examples/rust_extensions.rs (line 78)
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}
More examples
Hide additional examples
examples/persistence_and_hooks.rs (line 90)
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}
Source

pub fn activate_router(&mut self, name: &str) -> Result<(), RouterError>

Re-enables a deactivated router.

Source

pub fn deactivate_router(&mut self, name: &str) -> Result<(), RouterError>

Stops CLIPS dispatching to a router without unregistering it.

Source

pub fn add_udf<F>( &mut self, name: &str, signature: UdfSignature, callback: F, ) -> Result<(), UdfRegistrationError>
where F: for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError> + 'static,

Registers a Rust function callable from CLIPS code under name.

The callback is owned by the environment. It runs inside CLIPS, so a panic is caught at the boundary rather than unwinding through C, and re-entering the same function is refused instead of aliasing its state; both become a UdfCallbackError retrievable with Environment::take_udf_error.

The callback is 'static but its arguments are borrowed for the call only, so fact, instance, and external addresses can be passed back as results but cannot be stored.

Examples found in repository?
examples/rust_extensions.rs (lines 45-59)
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}
Source

pub fn remove_udf(&mut self, name: &str) -> Result<(), UdfRegistrationError>

Unregisters a user-defined function and drops its callback.

Examples found in repository?
examples/rust_extensions.rs (line 75)
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}
Source

pub fn take_udf_error(&self, name: &str) -> Option<UdfCallbackError>

Takes the error a user-defined function last reported, clearing it.

CLIPS only learns that a UDF failed, not why, so the reason is kept here and retrieved by name after the call that triggered it.

Examples found in repository?
examples/rust_extensions.rs (line 71)
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}
Source

pub fn add_hook<F>( &mut self, name: &str, kind: HookKind, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut() + 'static,

Registers a lifecycle callback, run when CLIPS reaches the given point.

Lower priority runs earlier. Names must be unique: CLIPS would accept a duplicate but could not then remove it reliably, so one is refused. Not every kind can be unregistered before the environment is dropped; see HookKind::is_removable.

Examples found in repository?
examples/persistence_and_hooks.rs (lines 50-52)
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}
Source

pub fn add_veto_hook<F>( &mut self, name: &str, kind: ReadyHookKind, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut() -> bool + 'static,

Registers a veto hook. Returning false from callback refuses the operation.

Source

pub fn add_clear_ready_hook<F>( &mut self, name: &str, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut() -> bool + 'static,

Registers a veto hook for Environment::clear, which fails with Error::ClearRejected if the callback returns false.

Shorthand for Environment::add_veto_hook with ReadyHookKind::Clear.

Source

pub fn add_rule_fire_hook<F>( &mut self, name: &str, phase: RuleFirePhase, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut(&str) + 'static,

Registers a hook called with the rule name each time a rule fires.

Examples found in repository?
examples/rule_base.rs (lines 29-31)
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}
Source

pub fn add_fact_hook<F>( &mut self, name: &str, kind: FactEventKind, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut(&FactChange) + 'static,

Registers a hook called when a fact is asserted, retracted, or modified.

The callback receives a FactChange describing what happened. A modification arrives as two calls, one for the replaced fact and one for its replacement, matching how CLIPS reports it.

Examples found in repository?
examples/persistence_and_hooks.rs (lines 57-63)
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}
Source

pub fn add_save_hook<F>( &mut self, name: &str, priority: i32, callback: F, ) -> Result<(), HookError>
where F: FnMut(&str, &str) + 'static,

Registers a hook called for each module while constructs are saved.

The callback receives the module name and the logical name being written to, which is a router name rather than a file path.

Source

pub fn set_parser_error_hook<F>(&mut self, callback: F)
where F: FnMut(&ParserDiagnostic) + 'static,

Installs the parser-error callback, replacing any previous one.

CLIPS keeps exactly one such callback per environment, so this is a single slot rather than a named registry.

CLIPS installs its error-capture router only on the load path, so diagnostics are reported for Environment::load and Environment::load_str, not for Environment::build. Install the callback before the parsing you want it to observe.

Source

pub fn clear_parser_error_hook(&mut self)

Removes the parser-error callback, if one is installed.

Source

pub fn remove_hook(&mut self, name: &str) -> Result<(), HookError>

Unregisters a hook and drops its callback.

Some CLIPS hook lists have no removal entry point; a hook of such a kind stays registered until the environment is destroyed. See HookKind::is_removable.

Examples found in repository?
examples/persistence_and_hooks.rs (line 94)
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}
Source§

impl Environment

Source

pub fn find_fact(&self, index: i64) -> Option<Fact<'_>>

Looks a fact up by its fact index. Returns None once the fact has been retracted, since CLIPS never reuses an index.

Source

pub fn facts_in_template<'env>( &'env self, template: &Deftemplate<'env>, ) -> FactsInTemplate<'env> ⓘ

Iterates the facts belonging to one deftemplate.

Examples found in repository?
examples/rule_base.rs (line 48)
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}
Source

pub fn fact_list_changed(&self) -> bool

Whether the fact list changed since this flag was last cleared.

Source

pub fn set_fact_list_changed(&self, changed: bool)

Sets or clears the fact-list-changed flag.

Source

pub fn retract_all_facts(&mut self) -> Result<()>

Retracts every fact.

Unlike Environment::reset this leaves deffacts unasserted, and unlike retracting one at a time it cannot be interrupted part-way by a rule-network error.

Source§

impl Environment

Source

pub fn undefine_defmethod(&mut self, generic: &str, index: u16) -> Result<bool>

Undefines one method of a generic function, returning whether it was removed.

Both the generic and the index are resolved here, under &mut self, so no method handle can outlive the method it names.

Source

pub fn defmethod_restrictions( &self, generic: &str, index: u16, ) -> Result<Option<Value<'_>>>

A method’s restrictions as the raw CLIPS multifield.

Defmethod::restrictions decodes the same data into a structured form; this is for callers that want the untouched value.

Source

pub fn defmethod_description( &self, generic: &str, index: u16, ) -> Result<Option<String>>

CLIPS’s own textual summary of a method’s parameter restrictions.

None when the generic or method does not exist.

Source

pub fn defglobal_value(&self, name: &str) -> Result<Option<Value<'_>>>

A defglobal’s current value, retained. None if no such global exists.

The name is given without the ?* decoration, so ?*count* is "count".

Source

pub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool>

Sets a defglobal to an integer, returning whether the global exists.

Source

pub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool>

Sets a defglobal to a float, returning whether the global exists.

Source

pub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool>

Sets a defglobal to a symbol, returning whether the global exists.

Source

pub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool>

Sets a defglobal to a string, returning whether the global exists.

Source

pub fn set_defglobal_instance_name( &mut self, name: &str, value: &str, ) -> Result<bool>

Sets a defglobal to an instance name, returning whether the global exists.

Source

pub fn set_defglobal_value(&self, name: &str, value: &Value<'_>) -> Result<bool>

Sets a defglobal to an already existing CLIPS value, which is the only way to store a fact, instance, or multifield in a global.

Fails with crate::Error::ForeignEnvironment if value belongs to another environment.

Source

pub fn reset_globals(&self) -> bool

Whether reset restores defglobals to their initial values.

Source

pub fn set_reset_globals(&mut self, enabled: bool) -> bool

Sets the reset behaviour for defglobals and returns the previous value.

Source

pub fn globals_changed(&self) -> bool

Whether any defglobal changed since this flag was last cleared.

Source

pub fn set_globals_changed(&self, changed: bool)

Sets or clears the globals-changed flag.

Source§

impl Environment

Source

pub fn make_instance(&self, source: &str) -> Result<Instance<'_>>

Creates an instance from CLIPS make-instance syntax, for example ([ada] of PERSON (age 36)).

Examples found in repository?
examples/objects_and_messages.rs (line 25)
7fn main() -> Result<(), Error> {
8    let mut environment = Environment::new()?;
9
10    environment.load_str(
11        r#"
12        (defclass ACCOUNT (is-a USER)
13            (slot holder)
14            (slot balance (type INTEGER) (default 0)))
15
16        (defmessage-handler ACCOUNT deposit (?amount)
17            (bind ?self:balance (+ ?self:balance ?amount))
18            ?self:balance)
19
20        (defmessage-handler ACCOUNT describe ()
21            (str-cat (send ?self get-holder) ": " (send ?self get-balance)))
22        "#,
23    )?;
24
25    let account = environment.make_instance("(ada of ACCOUNT (holder Ada) (balance 100))")?;
26    println!(
27        "class: {}",
28        account.class().expect("instance has a class").name()
29    );
30
31    let balance = account.send("deposit")?.integer(250).send()?;
32    println!("after deposit: {:?}", balance.as_i64());
33    drop(balance);
34
35    // A direct slot write bypasses message passing entirely.
36    account.put_integer("balance", 1_000)?;
37
38    let description = account.send("describe")?.send()?;
39    println!("{}", description.as_str().unwrap_or(""));
40    drop(description);
41    drop(account);
42
43    let class = environment.find_defclass("ACCOUNT")?.expect("class exists");
44    for slot in class.slots(false) {
45        let descriptor = class.slot(&slot).expect("slot name has no NUL");
46        if let Some(descriptor) = descriptor {
47            println!(
48                "slot {slot}: types {:?} default {:?}",
49                descriptor.allowed_types(),
50                descriptor.default_value()
51            );
52        }
53    }
54
55    Ok(())
56}
Source

pub fn find_instance<'env>( &'env self, name: &str, module: Option<&Defmodule<'env>>, search_imports: bool, ) -> Result<Option<Instance<'env>>>

Looks an instance up by name.

module selects the module to search; None searches the current module. search_imports additionally searches the modules imported by it, which is what CLIPS itself does when resolving an instance name.

Source

pub fn instances_in_class<'env>( &'env self, class: &Defclass<'env>, ) -> InstancesInClass<'env> ⓘ

Iterates the direct instances of class, excluding its subclasses.

Source

pub fn unmake_all_instances(&mut self) -> Result<()>

Deletes every instance in every module.

Source

pub fn instance_count(&self) -> u64

The number of instances in every module, which is what Environment::instances would yield.

Source

pub fn instances_changed(&self) -> bool

Whether the instance list changed since this flag was last cleared.

Source

pub fn set_instances_changed(&self, changed: bool)

Sets or clears the instances-changed flag.

Source§

impl Environment

Source

pub fn current_module(&self) -> Defmodule<'_>

Returns the module used for unqualified construct lookup and definition.

Source

pub fn set_current_module( &mut self, name: &str, ) -> Result<Defmodule<'_>, ModuleError>

Sets the current module and returns the previous one.

This accepts a name rather than a Defmodule handle so a handle from a different environment can never be passed to CLIPS.

Source

pub fn module_count(&self) -> usize

The number of defmodules, which is at least one because CLIPS always has MAIN.

Source

pub fn focus(&mut self, name: &str) -> Result<(), ModuleError>

Pushes a module onto the rule-engine focus stack.

Source

pub fn pop_focus(&mut self) -> Option<Defmodule<'_>>

Pops the top focus and returns its module, or None for an empty stack.

Source

pub fn current_focus(&self) -> Option<Defmodule<'_>>

The module the rule engine is currently focused on, or None when the focus stack is empty.

Source

pub fn focus_changed(&self) -> bool

Whether the focus stack changed since this flag was last cleared.

Source

pub fn set_focus_changed(&self, changed: bool)

Sets or clears the focus-changed flag.

Source

pub fn module_names(&self) -> Vec<String>

The names of every defmodule, in definition order.

CLIPS returns this as a multifield of symbols; the names are copied so the result stays valid across later construct changes.

Source

pub fn focus_stack(&self) -> FocusStack<'_> ⓘ

Iterates the focus stack from the module in focus downwards.

Source§

impl Environment

Source

pub fn save_constructs(&self, path: &str) -> Result<()>

Saves all construct definitions as CLIPS source text.

Source

pub fn binary_save_constructs(&self, path: &str) -> Result<()>

Saves construct definitions in CLIPS’ binary format.

Source

pub fn binary_load_constructs(&mut self, path: &str) -> Result<()>

Replaces the current construct set with a CLIPS binary image.

Source

pub fn constructs_are_binary_loaded(&self) -> bool

Whether a binary construct image is currently loaded.

While it is, CLIPS refuses to define further constructs; clearing the environment releases the image.

Source

pub fn save_facts(&self, path: &str, scope: SaveScope) -> Result<usize>

Writes facts as assert text, returning how many were saved.

Examples found in repository?
examples/persistence_and_hooks.rs (line 72)
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}
Source

pub fn load_facts(&mut self, path: &str) -> Result<usize>

Asserts the facts in a file written by Environment::save_facts, returning how many were loaded.

The facts are added to whatever is already asserted; nothing is cleared first.

Examples found in repository?
examples/persistence_and_hooks.rs (line 78)
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}
Source

pub fn load_facts_str(&mut self, source: &str) -> Result<usize>

Asserts facts from CLIPS text rather than a file.

Source

pub fn binary_save_facts(&self, path: &str, scope: SaveScope) -> Result<usize>

Writes facts in CLIPS’s binary format, which loads faster than text but is not portable across CLIPS builds.

Source

pub fn binary_load_facts(&mut self, path: &str) -> Result<usize>

Asserts the facts in a binary file, returning how many were loaded.

Source

pub fn save_instances(&self, path: &str, scope: SaveScope) -> Result<usize>

Writes instances as make-instance text, returning how many were saved.

Source

pub fn load_instances(&mut self, path: &str) -> Result<usize>

Creates instances from a saved file through message passing, so init-slots and slot daemons run.

Use Environment::restore_instances to bypass message passing.

Source

pub fn load_instances_str(&mut self, source: &str) -> Result<usize>

Creates instances from CLIPS text rather than a file, with message passing.

Source

pub fn restore_instances(&mut self, path: &str) -> Result<usize>

Creates instances from a saved file without message passing, so slots are written directly and no handler runs.

This restores the saved state exactly, where Environment::load_instances would let handlers alter it.

Source

pub fn restore_instances_str(&mut self, source: &str) -> Result<usize>

Restores instances from CLIPS text rather than a file, without message passing.

Source

pub fn binary_save_instances( &self, path: &str, scope: SaveScope, ) -> Result<usize>

Writes instances in CLIPS’s binary format.

Source

pub fn binary_load_instances(&mut self, path: &str) -> Result<usize>

Creates instances from a binary file, without message passing.

Source§

impl Environment

Source

pub fn watch(&mut self, item: WatchItem)

Enables a built-in watch category.

Source

pub fn unwatch(&mut self, item: WatchItem)

Disables a built-in watch category.

Source

pub fn watch_state(&self, item: WatchItem) -> bool

Returns the global state of a built-in watch category.

Source

pub fn set_watch_state(&mut self, item: WatchItem, enabled: bool)

Changes the global state of a built-in watch category.

Source

pub fn watch_states(&self) -> Vec<(WatchItem, bool)>

Every built-in watch category paired with its current state.

Source

pub fn watch_named(&mut self, name: &str) -> Result<(), WatchError>

Enables a watch item by its registered CLIPS name.

This also supports watch items registered by CLIPS extensions.

Source

pub fn unwatch_named(&mut self, name: &str) -> Result<(), WatchError>

Disables a watch item by its registered CLIPS name.

Source

pub fn named_watch_state(&self, name: &str) -> Result<bool, WatchError>

Returns the state of a watch item registered under name.

Source

pub fn compilations_watch(&self) -> bool

Whether construct compilations are currently traced.

Source

pub fn set_compilations_watch(&mut self, enabled: bool)

Enables or disables tracing of construct compilation.

Source

pub fn print_while_loading(&self) -> bool

Whether constructs are printed as they are loaded.

Source

pub fn set_print_while_loading(&mut self, enabled: bool)

Enables or disables echoing constructs as they load.

Source

pub fn load_in_progress(&self) -> bool

Whether CLIPS currently considers a load operation in progress.

Source

pub fn set_load_in_progress(&mut self, in_progress: bool)

Sets the load-in-progress flag, which changes how CLIPS reports parse errors. Setting it by hand is rarely correct.

Source

pub fn executing_construct(&self) -> bool

Whether CLIPS is currently executing a construct.

Source

pub fn set_executing_construct(&mut self, executing: bool)

Sets the executing-construct flag. Setting it by hand is rarely correct; CLIPS maintains it during execution.

Source

pub fn memory_used(&self) -> i64

Bytes CLIPS currently has allocated.

Source

pub fn memory_requests(&self) -> i64

Allocation requests CLIPS has made since the environment was created.

Source

pub fn release_memory(&mut self, amount: i64) -> i64

Frees pooled memory, returning the number of bytes released. A negative amount releases everything CLIPS can.

Source

pub fn conserve_memory(&self) -> bool

Whether CLIPS returns freed memory immediately instead of pooling it.

Source

pub fn set_conserve_memory(&mut self, enabled: bool) -> bool

Sets the conserve-memory behaviour and returns the previous value.

Source

pub fn profile_percent_threshold(&self) -> f64

The percentage below which profiled constructs are omitted from reports.

CLIPS exposes profile collection and reporting only as its profile and profile-info commands; run them with Environment::eval and capture the report with a crate::Router.

Source

pub fn set_profile_percent_threshold(&mut self, threshold: f64) -> f64

Sets the profile reporting threshold and returns the previous value.

Source

pub fn dribble_on(&mut self, path: &str) -> Result<bool, WatchError>

Starts copying router output to path.

Returns false if CLIPS could not open the file or dribbling is already active.

Source

pub fn dribble_active(&self) -> bool

Whether router output is currently being copied to a dribble file.

Source

pub fn dribble_off(&mut self) -> bool

Stops dribbling and closes the file. Returns false when no dribble file was open.

Source

pub fn dribble_to( &mut self, path: &str, ) -> Result<Option<Dribble<'_>>, WatchError>

Starts dribbling to path and stops it again when the guard is dropped.

Source

pub fn set_periodic_functions_enabled(&mut self, enabled: bool) -> bool

Whether periodic hooks run during execution.

Returns the previous setting.

Source

pub fn set_yield_function_enabled(&mut self, enabled: bool) -> bool

Whether CLIPS calls its yield-time function during execution.

Returns the previous setting. The function itself cannot be installed from Rust: CLIPS 6.4.2 keeps it in a private struct field with no public setter, so only the enable flag is bound.

Trait Implementations§

Source§

impl Default for Environment

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for Environment

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.