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
impl Environment
Sourcepub fn activations(&self) -> Activations<'_> ⓘ
pub fn activations(&self) -> Activations<'_> ⓘ
Iterates the agenda in firing order.
Sourcepub fn activation_count(&self) -> usize
pub fn activation_count(&self) -> usize
The number of activations on the agenda.
Sourcepub fn set_strategy(&mut self, strategy: Strategy) -> Strategy
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.
Sourcepub fn salience_evaluation(&self) -> SalienceEvaluation
pub fn salience_evaluation(&self) -> SalienceEvaluation
When rule saliences are evaluated.
Sourcepub fn set_salience_evaluation(
&mut self,
value: SalienceEvaluation,
) -> SalienceEvaluation
pub fn set_salience_evaluation( &mut self, value: SalienceEvaluation, ) -> SalienceEvaluation
Sets when saliences are evaluated and returns the previous setting.
Sourcepub fn refresh_agendas(&mut self)
pub fn refresh_agendas(&mut self)
Re-adds every module’s satisfied matches to its agenda, so matches that already fired can fire again.
Sourcepub fn reorder_agendas(&mut self)
pub fn reorder_agendas(&mut self)
Re-sorts every agenda, which is needed after changing saliences.
Sourcepub fn remove_all_activations(&mut self)
pub fn remove_all_activations(&mut self)
Removes every activation from every agenda.
Sourcepub fn agenda_changed(&self) -> bool
pub fn agenda_changed(&self) -> bool
Whether the agenda changed since this flag was last cleared.
Sourcepub fn set_agenda_changed(&self, changed: bool)
pub fn set_agenda_changed(&self, changed: bool)
Sets or clears the agenda-changed flag.
Sourcepub fn refresh_module_agenda(&mut self, module: &str) -> Result<(), ModuleError>
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.
Sourcepub fn reorder_module_agenda(&mut self, module: &str) -> Result<(), ModuleError>
pub fn reorder_module_agenda(&mut self, module: &str) -> Result<(), ModuleError>
Reorders one module’s agenda instead of every module’s.
Sourcepub fn clear_focus_stack(&mut self)
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
impl Environment
Sourcepub fn class_defaults_mode(&self) -> ClassDefaultsMode
pub fn class_defaults_mode(&self) -> ClassDefaultsMode
Whether accessor handlers are generated for classes defined from now on.
Sourcepub fn set_class_defaults_mode(
&mut self,
mode: ClassDefaultsMode,
) -> ClassDefaultsMode
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.
Sourcepub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError>
pub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError>
Undefines a class after resolving it in this environment.
Sourcepub fn undefine_message_handler(
&mut self,
class_name: &str,
handler_name: &str,
kind: HandlerType,
) -> Result<(), ClassError>
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
impl Environment
Sourcepub fn find_deftemplate(&self, name: &str) -> Result<Option<Deftemplate<'_>>>
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?
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
impl Environment
Source§impl Environment
impl Environment
Source§impl Environment
impl Environment
Source§impl Environment
impl Environment
Sourcepub fn find_deffunction(&self, name: &str) -> Result<Option<Deffunction<'_>>>
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
impl Environment
Sourcepub fn find_defgeneric(&self, name: &str) -> Result<Option<Defgeneric<'_>>>
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
impl Environment
Sourcepub fn find_defclass(&self, name: &str) -> Result<Option<Defclass<'_>>>
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?
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
impl Environment
Sourcepub fn find_definstances(&self, name: &str) -> Result<Option<Definstances<'_>>>
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
impl Environment
Source§impl Environment
impl Environment
Sourcepub fn deftemplates(&self) -> Deftemplates<'_>
pub fn deftemplates(&self) -> Deftemplates<'_>
Iterates every deftemplate, including the implied templates CLIPS creates for ordered facts.
Sourcepub fn defglobals(&self) -> Defglobals<'_>
pub fn defglobals(&self) -> Defglobals<'_>
Iterates every defglobal.
Sourcepub fn deffunctions(&self) -> Deffunctions<'_>
pub fn deffunctions(&self) -> Deffunctions<'_>
Iterates every deffunction.
Sourcepub fn defgenerics(&self) -> Defgenerics<'_>
pub fn defgenerics(&self) -> Defgenerics<'_>
Iterates every defgeneric.
Sourcepub fn defclasses(&self) -> Defclasses<'_>
pub fn defclasses(&self) -> Defclasses<'_>
Iterates every defclass, including the built-in classes such as USER and OBJECT.
Sourcepub fn definstances(&self) -> DefinstancesIter<'_>
pub fn definstances(&self) -> DefinstancesIter<'_>
Iterates every definstances construct.
Sourcepub fn defmodules(&self) -> Defmodules<'_>
pub fn defmodules(&self) -> Defmodules<'_>
Iterates every defmodule, starting with MAIN.
Source§impl Environment
impl Environment
Sourcepub fn undefine_deftemplate(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_defrule(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_deffacts(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_defglobal(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_deffunction(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_defgeneric(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_defclass(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn undefine_definstances(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn set_rule_breakpoint(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn remove_rule_breakpoint(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn refresh_rule(&mut self, name: &str) -> Result<bool>
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.
Sourcepub fn remove_all_breakpoints(&mut self)
pub fn remove_all_breakpoints(&mut self)
Removes every breakpoint in the environment.
Sourcepub fn breakpoint_rule_names(&self) -> Vec<String>
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
impl Environment
Sourcepub fn insert_data<T: Any>(&mut self, value: T) -> Option<T>
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.
Sourcepub fn data<T: Any>(&self) -> Option<&T>
pub fn data<T: Any>(&self) -> Option<&T>
Borrows the value of type T attached to this environment.
Sourcepub fn data_mut<T: Any>(&mut self) -> Option<&mut T>
pub fn data_mut<T: Any>(&mut self) -> Option<&mut T>
Mutably borrows the value of type T attached to this environment.
Sourcepub fn remove_data<T: Any>(&mut self) -> Option<T>
pub fn remove_data<T: Any>(&mut self) -> Option<T>
Detaches and returns the value of type T.
Source§impl Environment
impl Environment
Sourcepub fn new() -> Result<Self>
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?
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
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}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}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}Sourcepub fn clear(&mut self) -> Result<()>
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.
Sourcepub fn reset(&mut self)
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?
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}Sourcepub fn run(&mut self, limit: Option<u64>) -> u64
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?
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}Sourcepub fn halt_execution(&self) -> bool
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.
Sourcepub fn set_halt_execution(&mut self, halt: bool)
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.
Sourcepub fn halt_rules(&self) -> bool
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.
Sourcepub fn set_halt_rules(&mut self, halt: bool)
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.
Sourcepub fn beta_memory_resizing(&self) -> bool
pub fn beta_memory_resizing(&self) -> bool
Whether the rule network resizes its beta memories dynamically.
Sourcepub fn set_beta_memory_resizing(&mut self, resize: bool) -> bool
pub fn set_beta_memory_resizing(&mut self, resize: bool) -> bool
Sets beta-memory resizing and returns the previous setting.
Sourcepub fn write(&self, text: &str) -> Result<()>
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.
Sourcepub fn write_to(&self, logical_name: &str, text: &str) -> Result<()>
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.
Sourcepub fn build(&mut self, construct: &str) -> Result<()>
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?
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}Sourcepub fn load_str(&mut self, source: &str) -> Result<()>
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?
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
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}Sourcepub fn eval(&mut self, expression: &str) -> Result<Value<'_>>
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?
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
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}Sourcepub fn create_integer(&self, value: i64) -> Value<'_>
pub fn create_integer(&self, value: i64) -> Value<'_>
Creates a retained CLIPS integer.
Sourcepub fn create_float(&self, value: f64) -> Value<'_>
pub fn create_float(&self, value: f64) -> Value<'_>
Creates a retained CLIPS float.
Sourcepub fn create_boolean(&self, value: bool) -> Value<'_>
pub fn create_boolean(&self, value: bool) -> Value<'_>
Creates the retained CLIPS TRUE or FALSE symbol.
Sourcepub fn create_symbol(&self, value: &str) -> Result<Value<'_>>
pub fn create_symbol(&self, value: &str) -> Result<Value<'_>>
Creates a retained CLIPS symbol.
Sourcepub fn create_string(&self, value: &str) -> Result<Value<'_>>
pub fn create_string(&self, value: &str) -> Result<Value<'_>>
Creates a retained CLIPS string.
Sourcepub fn create_instance_name(&self, value: &str) -> Result<Value<'_>>
pub fn create_instance_name(&self, value: &str) -> Result<Value<'_>>
Creates a retained CLIPS instance name.
Sourcepub fn string_to_multifield(&self, source: &str) -> Result<Multifield<'_>>
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.
Sourcepub fn assert_string(&self, source: &str) -> Result<Fact<'_>>
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?
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}Sourcepub fn fact_builder(&self, template: &str) -> Result<FactBuilder<'_>>
pub fn fact_builder(&self, template: &str) -> Result<FactBuilder<'_>>
Starts building a fact of the named deftemplate.
Examples found in repository?
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}Sourcepub fn fact_count(&self) -> usize
pub fn fact_count(&self) -> usize
The number of facts currently asserted.
Examples found in repository?
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}Sourcepub fn instance_builder(&self, class: &str) -> Result<InstanceBuilder<'_>>
pub fn instance_builder(&self, class: &str) -> Result<InstanceBuilder<'_>>
Starts building an instance of the named defclass.
Sourcepub fn multifield_builder(
&self,
capacity: usize,
) -> Result<MultifieldBuilder<'_>>
pub fn multifield_builder( &self, capacity: usize, ) -> Result<MultifieldBuilder<'_>>
Starts building a multifield. capacity is a hint; the builder grows
as needed.
Sourcepub fn function_call(&self, capacity: usize) -> Result<FunctionCall<'_>>
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.
Sourcepub fn register_router<R: Router>(
&mut self,
name: &str,
priority: i32,
router: R,
) -> Result<(), RouterError>
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?
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
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}Sourcepub fn remove_router(&mut self, name: &str) -> Result<(), RouterError>
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?
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
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}Sourcepub fn activate_router(&mut self, name: &str) -> Result<(), RouterError>
pub fn activate_router(&mut self, name: &str) -> Result<(), RouterError>
Re-enables a deactivated router.
Sourcepub fn deactivate_router(&mut self, name: &str) -> Result<(), RouterError>
pub fn deactivate_router(&mut self, name: &str) -> Result<(), RouterError>
Stops CLIPS dispatching to a router without unregistering it.
Sourcepub 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,
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?
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}Sourcepub fn remove_udf(&mut self, name: &str) -> Result<(), UdfRegistrationError>
pub fn remove_udf(&mut self, name: &str) -> Result<(), UdfRegistrationError>
Unregisters a user-defined function and drops its callback.
Examples found in repository?
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}Sourcepub fn take_udf_error(&self, name: &str) -> Option<UdfCallbackError>
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?
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}Sourcepub fn add_hook<F>(
&mut self,
name: &str,
kind: HookKind,
priority: i32,
callback: F,
) -> Result<(), HookError>where
F: FnMut() + 'static,
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?
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}Sourcepub fn add_veto_hook<F>(
&mut self,
name: &str,
kind: ReadyHookKind,
priority: i32,
callback: F,
) -> Result<(), HookError>
pub fn add_veto_hook<F>( &mut self, name: &str, kind: ReadyHookKind, priority: i32, callback: F, ) -> Result<(), HookError>
Registers a veto hook. Returning false from callback refuses the
operation.
Sourcepub fn add_clear_ready_hook<F>(
&mut self,
name: &str,
priority: i32,
callback: F,
) -> Result<(), HookError>
pub fn add_clear_ready_hook<F>( &mut self, name: &str, priority: i32, callback: F, ) -> Result<(), HookError>
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.
Sourcepub fn add_rule_fire_hook<F>(
&mut self,
name: &str,
phase: RuleFirePhase,
priority: i32,
callback: F,
) -> Result<(), HookError>
pub fn add_rule_fire_hook<F>( &mut self, name: &str, phase: RuleFirePhase, priority: i32, callback: F, ) -> Result<(), HookError>
Registers a hook called with the rule name each time a rule fires.
Examples found in repository?
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}Sourcepub fn add_fact_hook<F>(
&mut self,
name: &str,
kind: FactEventKind,
priority: i32,
callback: F,
) -> Result<(), HookError>where
F: FnMut(&FactChange) + 'static,
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?
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}Sourcepub fn add_save_hook<F>(
&mut self,
name: &str,
priority: i32,
callback: F,
) -> Result<(), HookError>
pub fn add_save_hook<F>( &mut self, name: &str, priority: i32, callback: F, ) -> Result<(), HookError>
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.
Sourcepub fn set_parser_error_hook<F>(&mut self, callback: F)where
F: FnMut(&ParserDiagnostic) + 'static,
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.
Sourcepub fn clear_parser_error_hook(&mut self)
pub fn clear_parser_error_hook(&mut self)
Removes the parser-error callback, if one is installed.
Sourcepub fn remove_hook(&mut self, name: &str) -> Result<(), HookError>
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?
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
impl Environment
Sourcepub fn find_fact(&self, index: i64) -> Option<Fact<'_>>
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.
Sourcepub fn facts_in_template<'env>(
&'env self,
template: &Deftemplate<'env>,
) -> FactsInTemplate<'env> ⓘ
pub fn facts_in_template<'env>( &'env self, template: &Deftemplate<'env>, ) -> FactsInTemplate<'env> ⓘ
Iterates the facts belonging to one deftemplate.
Examples found in repository?
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}Sourcepub fn fact_list_changed(&self) -> bool
pub fn fact_list_changed(&self) -> bool
Whether the fact list changed since this flag was last cleared.
Sourcepub fn set_fact_list_changed(&self, changed: bool)
pub fn set_fact_list_changed(&self, changed: bool)
Sets or clears the fact-list-changed flag.
Sourcepub fn retract_all_facts(&mut self) -> Result<()>
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
impl Environment
Sourcepub fn undefine_defmethod(&mut self, generic: &str, index: u16) -> Result<bool>
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.
Sourcepub fn defmethod_restrictions(
&self,
generic: &str,
index: u16,
) -> Result<Option<Value<'_>>>
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.
Sourcepub fn defmethod_description(
&self,
generic: &str,
index: u16,
) -> Result<Option<String>>
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.
Sourcepub fn defglobal_value(&self, name: &str) -> Result<Option<Value<'_>>>
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".
Sourcepub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool>
pub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool>
Sets a defglobal to an integer, returning whether the global exists.
Sourcepub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool>
pub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool>
Sets a defglobal to a float, returning whether the global exists.
Sourcepub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool>
pub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool>
Sets a defglobal to a symbol, returning whether the global exists.
Sourcepub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool>
pub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool>
Sets a defglobal to a string, returning whether the global exists.
Sourcepub fn set_defglobal_instance_name(
&mut self,
name: &str,
value: &str,
) -> Result<bool>
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.
Sourcepub fn set_defglobal_value(&self, name: &str, value: &Value<'_>) -> Result<bool>
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.
Sourcepub fn reset_globals(&self) -> bool
pub fn reset_globals(&self) -> bool
Whether reset restores defglobals to their initial values.
Sourcepub fn set_reset_globals(&mut self, enabled: bool) -> bool
pub fn set_reset_globals(&mut self, enabled: bool) -> bool
Sets the reset behaviour for defglobals and returns the previous value.
Sourcepub fn globals_changed(&self) -> bool
pub fn globals_changed(&self) -> bool
Whether any defglobal changed since this flag was last cleared.
Sourcepub fn set_globals_changed(&self, changed: bool)
pub fn set_globals_changed(&self, changed: bool)
Sets or clears the globals-changed flag.
Source§impl Environment
impl Environment
Sourcepub fn make_instance(&self, source: &str) -> Result<Instance<'_>>
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?
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}Sourcepub fn find_instance<'env>(
&'env self,
name: &str,
module: Option<&Defmodule<'env>>,
search_imports: bool,
) -> Result<Option<Instance<'env>>>
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.
Sourcepub fn instances_in_class<'env>(
&'env self,
class: &Defclass<'env>,
) -> InstancesInClass<'env> ⓘ
pub fn instances_in_class<'env>( &'env self, class: &Defclass<'env>, ) -> InstancesInClass<'env> ⓘ
Iterates the direct instances of class, excluding its subclasses.
Sourcepub fn unmake_all_instances(&mut self) -> Result<()>
pub fn unmake_all_instances(&mut self) -> Result<()>
Deletes every instance in every module.
Sourcepub fn instance_count(&self) -> u64
pub fn instance_count(&self) -> u64
The number of instances in every module, which is what
Environment::instances would yield.
Sourcepub fn instances_changed(&self) -> bool
pub fn instances_changed(&self) -> bool
Whether the instance list changed since this flag was last cleared.
Sourcepub fn set_instances_changed(&self, changed: bool)
pub fn set_instances_changed(&self, changed: bool)
Sets or clears the instances-changed flag.
Source§impl Environment
impl Environment
Sourcepub fn current_module(&self) -> Defmodule<'_>
pub fn current_module(&self) -> Defmodule<'_>
Returns the module used for unqualified construct lookup and definition.
Sourcepub fn set_current_module(
&mut self,
name: &str,
) -> Result<Defmodule<'_>, ModuleError>
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.
Sourcepub fn module_count(&self) -> usize
pub fn module_count(&self) -> usize
The number of defmodules, which is at least one because CLIPS always
has MAIN.
Sourcepub fn focus(&mut self, name: &str) -> Result<(), ModuleError>
pub fn focus(&mut self, name: &str) -> Result<(), ModuleError>
Pushes a module onto the rule-engine focus stack.
Sourcepub fn pop_focus(&mut self) -> Option<Defmodule<'_>>
pub fn pop_focus(&mut self) -> Option<Defmodule<'_>>
Pops the top focus and returns its module, or None for an empty stack.
Sourcepub fn current_focus(&self) -> Option<Defmodule<'_>>
pub fn current_focus(&self) -> Option<Defmodule<'_>>
The module the rule engine is currently focused on, or None when the
focus stack is empty.
Sourcepub fn focus_changed(&self) -> bool
pub fn focus_changed(&self) -> bool
Whether the focus stack changed since this flag was last cleared.
Sourcepub fn set_focus_changed(&self, changed: bool)
pub fn set_focus_changed(&self, changed: bool)
Sets or clears the focus-changed flag.
Sourcepub fn module_names(&self) -> Vec<String>
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.
Sourcepub fn focus_stack(&self) -> FocusStack<'_> ⓘ
pub fn focus_stack(&self) -> FocusStack<'_> ⓘ
Iterates the focus stack from the module in focus downwards.
Source§impl Environment
impl Environment
Sourcepub fn save_constructs(&self, path: &str) -> Result<()>
pub fn save_constructs(&self, path: &str) -> Result<()>
Saves all construct definitions as CLIPS source text.
Sourcepub fn binary_save_constructs(&self, path: &str) -> Result<()>
pub fn binary_save_constructs(&self, path: &str) -> Result<()>
Saves construct definitions in CLIPS’ binary format.
Sourcepub fn binary_load_constructs(&mut self, path: &str) -> Result<()>
pub fn binary_load_constructs(&mut self, path: &str) -> Result<()>
Replaces the current construct set with a CLIPS binary image.
Sourcepub fn constructs_are_binary_loaded(&self) -> bool
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.
Sourcepub fn save_facts(&self, path: &str, scope: SaveScope) -> Result<usize>
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?
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}Sourcepub fn load_facts(&mut self, path: &str) -> Result<usize>
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?
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}Sourcepub fn load_facts_str(&mut self, source: &str) -> Result<usize>
pub fn load_facts_str(&mut self, source: &str) -> Result<usize>
Asserts facts from CLIPS text rather than a file.
Sourcepub fn binary_save_facts(&self, path: &str, scope: SaveScope) -> Result<usize>
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.
Sourcepub fn binary_load_facts(&mut self, path: &str) -> Result<usize>
pub fn binary_load_facts(&mut self, path: &str) -> Result<usize>
Asserts the facts in a binary file, returning how many were loaded.
Sourcepub fn save_instances(&self, path: &str, scope: SaveScope) -> Result<usize>
pub fn save_instances(&self, path: &str, scope: SaveScope) -> Result<usize>
Writes instances as make-instance text, returning how many were saved.
Sourcepub fn load_instances(&mut self, path: &str) -> Result<usize>
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.
Sourcepub fn load_instances_str(&mut self, source: &str) -> Result<usize>
pub fn load_instances_str(&mut self, source: &str) -> Result<usize>
Creates instances from CLIPS text rather than a file, with message passing.
Sourcepub fn restore_instances(&mut self, path: &str) -> Result<usize>
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.
Sourcepub fn restore_instances_str(&mut self, source: &str) -> Result<usize>
pub fn restore_instances_str(&mut self, source: &str) -> Result<usize>
Restores instances from CLIPS text rather than a file, without message passing.
Sourcepub fn binary_save_instances(
&self,
path: &str,
scope: SaveScope,
) -> Result<usize>
pub fn binary_save_instances( &self, path: &str, scope: SaveScope, ) -> Result<usize>
Writes instances in CLIPS’s binary format.
Sourcepub fn binary_load_instances(&mut self, path: &str) -> Result<usize>
pub fn binary_load_instances(&mut self, path: &str) -> Result<usize>
Creates instances from a binary file, without message passing.
Source§impl Environment
impl Environment
Sourcepub fn watch_state(&self, item: WatchItem) -> bool
pub fn watch_state(&self, item: WatchItem) -> bool
Returns the global state of a built-in watch category.
Sourcepub fn set_watch_state(&mut self, item: WatchItem, enabled: bool)
pub fn set_watch_state(&mut self, item: WatchItem, enabled: bool)
Changes the global state of a built-in watch category.
Sourcepub fn watch_states(&self) -> Vec<(WatchItem, bool)>
pub fn watch_states(&self) -> Vec<(WatchItem, bool)>
Every built-in watch category paired with its current state.
Sourcepub fn watch_named(&mut self, name: &str) -> Result<(), WatchError>
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.
Sourcepub fn unwatch_named(&mut self, name: &str) -> Result<(), WatchError>
pub fn unwatch_named(&mut self, name: &str) -> Result<(), WatchError>
Disables a watch item by its registered CLIPS name.
Sourcepub fn named_watch_state(&self, name: &str) -> Result<bool, WatchError>
pub fn named_watch_state(&self, name: &str) -> Result<bool, WatchError>
Returns the state of a watch item registered under name.
Sourcepub fn compilations_watch(&self) -> bool
pub fn compilations_watch(&self) -> bool
Whether construct compilations are currently traced.
Sourcepub fn set_compilations_watch(&mut self, enabled: bool)
pub fn set_compilations_watch(&mut self, enabled: bool)
Enables or disables tracing of construct compilation.
Sourcepub fn print_while_loading(&self) -> bool
pub fn print_while_loading(&self) -> bool
Whether constructs are printed as they are loaded.
Sourcepub fn set_print_while_loading(&mut self, enabled: bool)
pub fn set_print_while_loading(&mut self, enabled: bool)
Enables or disables echoing constructs as they load.
Sourcepub fn load_in_progress(&self) -> bool
pub fn load_in_progress(&self) -> bool
Whether CLIPS currently considers a load operation in progress.
Sourcepub fn set_load_in_progress(&mut self, in_progress: bool)
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.
Sourcepub fn executing_construct(&self) -> bool
pub fn executing_construct(&self) -> bool
Whether CLIPS is currently executing a construct.
Sourcepub fn set_executing_construct(&mut self, executing: bool)
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.
Sourcepub fn memory_used(&self) -> i64
pub fn memory_used(&self) -> i64
Bytes CLIPS currently has allocated.
Sourcepub fn memory_requests(&self) -> i64
pub fn memory_requests(&self) -> i64
Allocation requests CLIPS has made since the environment was created.
Sourcepub fn release_memory(&mut self, amount: i64) -> i64
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.
Sourcepub fn conserve_memory(&self) -> bool
pub fn conserve_memory(&self) -> bool
Whether CLIPS returns freed memory immediately instead of pooling it.
Sourcepub fn set_conserve_memory(&mut self, enabled: bool) -> bool
pub fn set_conserve_memory(&mut self, enabled: bool) -> bool
Sets the conserve-memory behaviour and returns the previous value.
Sourcepub fn profile_percent_threshold(&self) -> f64
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.
Sourcepub fn set_profile_percent_threshold(&mut self, threshold: f64) -> f64
pub fn set_profile_percent_threshold(&mut self, threshold: f64) -> f64
Sets the profile reporting threshold and returns the previous value.
Sourcepub fn dribble_on(&mut self, path: &str) -> Result<bool, WatchError>
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.
Sourcepub fn dribble_active(&self) -> bool
pub fn dribble_active(&self) -> bool
Whether router output is currently being copied to a dribble file.
Sourcepub fn dribble_off(&mut self) -> bool
pub fn dribble_off(&mut self) -> bool
Stops dribbling and closes the file. Returns false when no dribble
file was open.
Sourcepub fn dribble_to(
&mut self,
path: &str,
) -> Result<Option<Dribble<'_>>, WatchError>
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.
Sourcepub fn set_periodic_functions_enabled(&mut self, enabled: bool) -> bool
pub fn set_periodic_functions_enabled(&mut self, enabled: bool) -> bool
Whether periodic hooks run during execution.
Returns the previous setting.
Sourcepub fn set_yield_function_enabled(&mut self, enabled: bool) -> bool
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.