Skip to main content

clips_bindings/
fact.rs

1//! Facts, fact builders, and fact modifiers.
2//!
3//! A `Fact` is a retained handle: it stays valid while held, and reports
4//! retraction through [`Fact::is_retracted`] rather than dangling.
5
6use std::ffi::{CStr, CString};
7use std::ptr::NonNull;
8
9use crate::error::{
10    AssertionError, Error, FactBuilderError, GetSlotError, PutSlotError, Result, RetractionError,
11};
12use crate::{Deftemplate, Environment, Instance, Multifield, Value, ffi};
13
14/// A fact, retained for as long as the handle lives.
15///
16/// Retracting a fact does not invalidate the handle: CLIPS keeps the record
17/// alive while it is retained, and [`Fact::is_retracted`] reports the change.
18pub struct Fact<'env> {
19    pub(crate) raw: NonNull<ffi::Fact>,
20    environment: &'env Environment,
21}
22
23impl<'env> Fact<'env> {
24    pub(crate) fn retained(environment: &'env Environment, raw: *mut ffi::Fact) -> Option<Self> {
25        NonNull::new(raw).map(|raw| {
26            unsafe { ffi::RetainFact(raw.as_ptr()) };
27            Self { raw, environment }
28        })
29    }
30    pub(crate) fn from_result(
31        environment: &'env Environment,
32        raw: *mut ffi::Fact,
33        code: u32,
34    ) -> Result<Self> {
35        Self::retained(environment, raw).ok_or(Error::Assertion(AssertionError::from(code)))
36    }
37    /// The fact index, the number CLIPS prints as `f-<n>`.
38    ///
39    /// Indices are never reused, so one identifies a fact for the lifetime of
40    /// the environment.
41    pub fn index(&self) -> i64 {
42        unsafe { ffi::FactIndex(self.raw.as_ptr()) }
43    }
44
45    /// Whether the fact has been retracted. The handle remains usable.
46    pub fn is_retracted(&self) -> bool {
47        unsafe { ffi::FactIsDeleted(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
48    }
49
50    /// Retracts the fact, which may activate or deactivate rules.
51    pub fn retract(&mut self) -> Result<()> {
52        match unsafe { ffi::Retract(self.raw.as_ptr()) } {
53            0 => Ok(()),
54            code => Err(Error::Retraction(RetractionError::from(code))),
55        }
56    }
57
58    /// The fact rendered as CLIPS prints it.
59    ///
60    /// With `ignore_defaults`, slots still holding their default value are
61    /// omitted. Empty if CLIPS could not allocate the string builder.
62    pub fn pretty_print(&self, ignore_defaults: bool) -> String {
63        unsafe {
64            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
65            if builder.is_null() {
66                return String::new();
67            }
68            ffi::FactPPForm(self.raw.as_ptr(), builder, ignore_defaults);
69            let output = CStr::from_ptr((*builder).contents)
70                .to_string_lossy()
71                .into_owned();
72            ffi::SBDispose(builder);
73            output
74        }
75    }
76    /// The fact's relation name, that is, its deftemplate name.
77    pub fn relation(&self) -> String {
78        let lexeme = unsafe { ffi::FactRelation(self.raw.as_ptr()) };
79        if lexeme.is_null() {
80            return String::new();
81        }
82        unsafe { CStr::from_ptr((*lexeme).contents) }
83            .to_string_lossy()
84            .into_owned()
85    }
86    /// The deftemplate this fact was asserted against.
87    pub fn template(&self) -> Option<Deftemplate<'env>> {
88        NonNull::new(unsafe { ffi::FactDeftemplate(self.raw.as_ptr()) }).map(|raw| Deftemplate {
89            raw,
90            _environment: self.environment,
91        })
92    }
93    /// The fact's slot names, in template order. Empty for implied facts, which
94    /// have no named slots.
95    pub fn slot_names(&self) -> Multifield<'env> {
96        let mut raw = ffi::CLIPSValue {
97            value: std::ptr::null_mut(),
98        };
99        unsafe { ffi::FactSlotNames(self.raw.as_ptr(), &mut raw) };
100        Multifield::from_value(Value::retaining(self.environment, raw))
101    }
102    /// Starts a batched modification.
103    ///
104    /// CLIPS implements a modification as a retract and re-assert, so the
105    /// result is a new fact with a new index.
106    pub fn modifier(&self) -> Result<FactModifier<'env>> {
107        FactModifier::new(self)
108    }
109
110    /// Reads a slot by name. The returned value is retained independently of
111    /// the fact.
112    pub fn slot(&self, name: &str) -> Result<Value<'env>> {
113        let name = CString::new(name)?;
114        let mut raw = ffi::CLIPSValue {
115            value: std::ptr::null_mut(),
116        };
117        match unsafe { ffi::GetFactSlot(self.raw.as_ptr(), name.as_ptr(), &mut raw) } {
118            0 => {
119                unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
120                Ok(Value::from_retained_raw(self.environment, raw))
121            }
122            code => Err(Error::GetSlot(GetSlotError::from(code))),
123        }
124    }
125}
126impl Drop for Fact<'_> {
127    fn drop(&mut self) {
128        unsafe { ffi::ReleaseFact(self.raw.as_ptr()) }
129    }
130}
131
132/// Iterates every fact in the environment, in index order.
133pub struct Facts<'env> {
134    environment: &'env Environment,
135    next: *mut ffi::Fact,
136}
137impl<'env> Facts<'env> {
138    pub(crate) fn new(environment: &'env Environment) -> Self {
139        Self {
140            environment,
141            next: std::ptr::null_mut(),
142        }
143    }
144}
145impl<'env> Iterator for Facts<'env> {
146    type Item = Fact<'env>;
147    fn next(&mut self) -> Option<Self::Item> {
148        self.next = unsafe { ffi::GetNextFact(self.environment.raw.as_ptr(), self.next) };
149        Fact::retained(self.environment, self.next)
150    }
151}
152
153/// Iterator over the facts asserted against one deftemplate.
154pub struct FactsInTemplate<'env> {
155    environment: &'env Environment,
156    template: NonNull<ffi::Deftemplate>,
157    next: *mut ffi::Fact,
158}
159impl<'env> Iterator for FactsInTemplate<'env> {
160    type Item = Fact<'env>;
161    fn next(&mut self) -> Option<Self::Item> {
162        self.next = unsafe { ffi::GetNextFactInTemplate(self.template.as_ptr(), self.next) };
163        Fact::retained(self.environment, self.next)
164    }
165}
166
167impl Environment {
168    /// Looks a fact up by its fact index. Returns `None` once the fact has been
169    /// retracted, since CLIPS never reuses an index.
170    pub fn find_fact(&self, index: i64) -> Option<Fact<'_>> {
171        Fact::retained(self, unsafe {
172            ffi::FindIndexedFact(self.raw.as_ptr(), index)
173        })
174    }
175    /// Iterates the facts belonging to one deftemplate.
176    pub fn facts_in_template<'env>(
177        &'env self,
178        template: &Deftemplate<'env>,
179    ) -> FactsInTemplate<'env> {
180        FactsInTemplate {
181            environment: self,
182            template: template.raw,
183            next: std::ptr::null_mut(),
184        }
185    }
186    /// Whether the fact list changed since this flag was last cleared.
187    pub fn fact_list_changed(&self) -> bool {
188        unsafe { ffi::GetFactListChanged(self.raw.as_ptr()) }
189    }
190    /// Sets or clears the fact-list-changed flag.
191    pub fn set_fact_list_changed(&self, changed: bool) {
192        unsafe { ffi::SetFactListChanged(self.raw.as_ptr(), changed) }
193    }
194
195    /// Retracts every fact.
196    ///
197    /// Unlike [`Environment::reset`] this leaves deffacts unasserted, and
198    /// unlike retracting one at a time it cannot be interrupted part-way by a
199    /// rule-network error.
200    pub fn retract_all_facts(&mut self) -> Result<()> {
201        match unsafe { ffi::RetractAllFacts(self.raw.as_ptr()) } {
202            0 => Ok(()),
203            code => Err(Error::Retraction(RetractionError::from(code))),
204        }
205    }
206}
207
208/// Builds a fact slot by slot, then asserts it.
209///
210/// Unlike assembling and parsing assertion text, slot values are passed as
211/// real CLIPS values, so nothing has to be escaped or re-parsed.
212pub struct FactBuilder<'env> {
213    raw: NonNull<ffi::FactBuilder>,
214    environment: &'env Environment,
215    asserted: bool,
216}
217impl<'env> FactBuilder<'env> {
218    pub(crate) fn new(environment: &'env Environment, template: &str) -> Result<Self> {
219        let template = CString::new(template)?;
220        NonNull::new(unsafe { ffi::CreateFactBuilder(environment.raw.as_ptr(), template.as_ptr()) })
221            .map(|raw| Self {
222                raw,
223                environment,
224                asserted: false,
225            })
226            .ok_or(Error::FactBuilder(FactBuilderError::from(unsafe {
227                ffi::FBError(environment.raw.as_ptr())
228            })))
229    }
230    fn put(
231        &mut self,
232        slot: &str,
233        operation: impl FnOnce(*const std::ffi::c_char) -> u32,
234    ) -> Result<&mut Self> {
235        let slot = CString::new(slot)?;
236        match operation(slot.as_ptr()) {
237            0 => Ok(self),
238            code => Err(Error::PutSlot(PutSlotError::from(code))),
239        }
240    }
241    /// Sets an integer slot.
242    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
243        let raw = self.raw.as_ptr();
244        self.put(slot, |slot| unsafe {
245            ffi::FBPutSlotInteger(raw, slot, value)
246        })
247    }
248    /// Sets a float slot.
249    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
250        let raw = self.raw.as_ptr();
251        self.put(slot, |slot| unsafe {
252            ffi::FBPutSlotFloat(raw, slot, value)
253        })
254    }
255    /// Sets a symbol slot.
256    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
257        let value = CString::new(value)?;
258        let raw = self.raw.as_ptr();
259        self.put(slot, |slot| unsafe {
260            ffi::FBPutSlotSymbol(raw, slot, value.as_ptr())
261        })
262    }
263    /// Sets a string slot.
264    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
265        let value = CString::new(value)?;
266        let raw = self.raw.as_ptr();
267        self.put(slot, |slot| unsafe {
268            ffi::FBPutSlotString(raw, slot, value.as_ptr())
269        })
270    }
271    /// Sets an instance-name slot.
272    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
273        let value = CString::new(value)?;
274        let raw = self.raw.as_ptr();
275        self.put(slot, |slot| unsafe {
276            ffi::FBPutSlotInstanceName(raw, slot, value.as_ptr())
277        })
278    }
279    /// Sets a slot to a fact address.
280    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
281        let raw = self.raw.as_ptr();
282        self.put(slot, |slot| unsafe {
283            ffi::FBPutSlotFact(raw, slot, value.raw.as_ptr())
284        })
285    }
286    /// Sets a slot to an instance address.
287    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
288        let raw = self.raw.as_ptr();
289        self.put(slot, |slot| unsafe {
290            ffi::FBPutSlotInstance(raw, slot, value.raw.as_ptr())
291        })
292    }
293    /// Sets a multifield slot.
294    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
295        let raw = self.raw.as_ptr();
296        self.put(slot, |slot| unsafe {
297            ffi::FBPutSlotMultifield(raw, slot, value.raw())
298        })
299    }
300    /// Assigns an already existing CLIPS value.
301    ///
302    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
303    /// environment, since CLIPS atoms are interned per environment.
304    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
305        let mut cv = self.environment.check_value(value)?;
306        let raw = self.raw.as_ptr();
307        self.put(slot, |slot| unsafe { ffi::FBPutSlot(raw, slot, &mut cv) })
308    }
309    /// Asserts the fact and returns a retained handle to it.
310    ///
311    /// The builder is reusable afterwards: CLIPS resets its slots, so another
312    /// fact of the same template can be built without recreating it.
313    pub fn assert(&mut self) -> Result<Fact<'env>> {
314        let raw = unsafe { ffi::FBAssert(self.raw.as_ptr()) };
315        self.asserted = !raw.is_null();
316        Fact::from_result(self.environment, raw, unsafe {
317            ffi::FBError(self.environment.raw.as_ptr())
318        })
319    }
320}
321impl Drop for FactBuilder<'_> {
322    fn drop(&mut self) {
323        unsafe {
324            if !self.asserted {
325                ffi::FBAbort(self.raw.as_ptr())
326            }
327            ffi::FBDispose(self.raw.as_ptr())
328        }
329    }
330}
331
332/// Collects slot changes and applies them as a single modification.
333///
334/// Aborts on drop unless [`FactModifier::modify`] was called, so an abandoned
335/// modifier leaves the fact untouched.
336pub struct FactModifier<'env> {
337    raw: NonNull<ffi::FactModifier>,
338    environment: &'env Environment,
339}
340impl<'env> FactModifier<'env> {
341    fn new(fact: &Fact<'env>) -> Result<Self> {
342        NonNull::new(unsafe {
343            ffi::CreateFactModifier(fact.environment.raw.as_ptr(), fact.raw.as_ptr())
344        })
345        .map(|raw| Self {
346            raw,
347            environment: fact.environment,
348        })
349        .ok_or_else(|| {
350            Error::FactModifier(crate::error::FactModifierError::from(unsafe {
351                ffi::FMError(fact.environment.raw.as_ptr())
352            }))
353        })
354    }
355    fn put(
356        &mut self,
357        slot: &str,
358        operation: impl FnOnce(*const std::ffi::c_char) -> u32,
359    ) -> Result<&mut Self> {
360        let slot = CString::new(slot)?;
361        match operation(slot.as_ptr()) {
362            0 => Ok(self),
363            code => Err(Error::PutSlot(PutSlotError::from(code))),
364        }
365    }
366    /// Sets an integer slot.
367    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
368        let raw = self.raw.as_ptr();
369        self.put(slot, |slot| unsafe {
370            ffi::FMPutSlotInteger(raw, slot, value)
371        })
372    }
373    /// Sets a float slot.
374    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
375        let raw = self.raw.as_ptr();
376        self.put(slot, |slot| unsafe {
377            ffi::FMPutSlotFloat(raw, slot, value)
378        })
379    }
380    /// Sets a symbol slot.
381    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
382        let value = CString::new(value)?;
383        let raw = self.raw.as_ptr();
384        self.put(slot, |slot| unsafe {
385            ffi::FMPutSlotSymbol(raw, slot, value.as_ptr())
386        })
387    }
388    /// Sets a string slot.
389    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
390        let value = CString::new(value)?;
391        let raw = self.raw.as_ptr();
392        self.put(slot, |slot| unsafe {
393            ffi::FMPutSlotString(raw, slot, value.as_ptr())
394        })
395    }
396    /// Sets an instance-name slot.
397    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
398        let value = CString::new(value)?;
399        let raw = self.raw.as_ptr();
400        self.put(slot, |slot| unsafe {
401            ffi::FMPutSlotInstanceName(raw, slot, value.as_ptr())
402        })
403    }
404    /// Sets a slot to a fact address.
405    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
406        let raw = self.raw.as_ptr();
407        self.put(slot, |slot| unsafe {
408            ffi::FMPutSlotFact(raw, slot, value.raw.as_ptr())
409        })
410    }
411    /// Sets a slot to an instance address.
412    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
413        let raw = self.raw.as_ptr();
414        self.put(slot, |slot| unsafe {
415            ffi::FMPutSlotInstance(raw, slot, value.raw.as_ptr())
416        })
417    }
418    /// Sets a multifield slot.
419    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
420        let raw = self.raw.as_ptr();
421        self.put(slot, |slot| unsafe {
422            ffi::FMPutSlotMultifield(raw, slot, value.raw())
423        })
424    }
425    /// Assigns an already existing CLIPS value.
426    ///
427    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
428    /// environment, since CLIPS atoms are interned per environment.
429    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
430        let mut cv = self.environment.check_value(value)?;
431        let raw = self.raw.as_ptr();
432        self.put(slot, |slot| unsafe { ffi::FMPutSlot(raw, slot, &mut cv) })
433    }
434    /// Applies the collected changes and returns the resulting fact.
435    ///
436    /// CLIPS retracts the original and asserts a replacement, so the returned
437    /// fact has a new index and the original reports itself retracted. Slots
438    /// left unset keep their previous values.
439    pub fn modify(&mut self) -> Result<Fact<'env>> {
440        let raw = unsafe { ffi::FMModify(self.raw.as_ptr()) };
441        Fact::retained(self.environment, raw).ok_or_else(|| {
442            Error::FactModifier(crate::error::FactModifierError::from(unsafe {
443                ffi::FMError(self.environment.raw.as_ptr())
444            }))
445        })
446    }
447
448    /// Discards the collected changes, leaving the fact untouched.
449    pub fn abort(&mut self) {
450        unsafe { ffi::FMAbort(self.raw.as_ptr()) }
451    }
452}
453impl Drop for FactModifier<'_> {
454    fn drop(&mut self) {
455        unsafe {
456            ffi::FMAbort(self.raw.as_ptr());
457            ffi::FMDispose(self.raw.as_ptr())
458        }
459    }
460}