clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Facts, fact builders, and fact modifiers.
//!
//! A `Fact` is a retained handle: it stays valid while held, and reports
//! retraction through [`Fact::is_retracted`] rather than dangling.

use std::ffi::{CStr, CString};
use std::ptr::NonNull;

use crate::error::{
    AssertionError, Error, FactBuilderError, GetSlotError, PutSlotError, Result, RetractionError,
};
use crate::{Deftemplate, Environment, Instance, Multifield, Value, ffi};

/// A fact, retained for as long as the handle lives.
///
/// Retracting a fact does not invalidate the handle: CLIPS keeps the record
/// alive while it is retained, and [`Fact::is_retracted`] reports the change.
pub struct Fact<'env> {
    pub(crate) raw: NonNull<ffi::Fact>,
    environment: &'env Environment,
}

impl<'env> Fact<'env> {
    pub(crate) fn retained(environment: &'env Environment, raw: *mut ffi::Fact) -> Option<Self> {
        NonNull::new(raw).map(|raw| {
            unsafe { ffi::RetainFact(raw.as_ptr()) };
            Self { raw, environment }
        })
    }
    pub(crate) fn from_result(
        environment: &'env Environment,
        raw: *mut ffi::Fact,
        code: u32,
    ) -> Result<Self> {
        Self::retained(environment, raw).ok_or(Error::Assertion(AssertionError::from(code)))
    }
    /// The fact index, the number CLIPS prints as `f-<n>`.
    ///
    /// Indices are never reused, so one identifies a fact for the lifetime of
    /// the environment.
    pub fn index(&self) -> i64 {
        unsafe { ffi::FactIndex(self.raw.as_ptr()) }
    }

    /// Whether the fact has been retracted. The handle remains usable.
    pub fn is_retracted(&self) -> bool {
        unsafe { ffi::FactIsDeleted(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
    }

    /// Retracts the fact, which may activate or deactivate rules.
    pub fn retract(&mut self) -> Result<()> {
        match unsafe { ffi::Retract(self.raw.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::Retraction(RetractionError::from(code))),
        }
    }

    /// The fact rendered as CLIPS prints it.
    ///
    /// With `ignore_defaults`, slots still holding their default value are
    /// omitted. Empty if CLIPS could not allocate the string builder.
    pub fn pretty_print(&self, ignore_defaults: bool) -> String {
        unsafe {
            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
            if builder.is_null() {
                return String::new();
            }
            ffi::FactPPForm(self.raw.as_ptr(), builder, ignore_defaults);
            let output = CStr::from_ptr((*builder).contents)
                .to_string_lossy()
                .into_owned();
            ffi::SBDispose(builder);
            output
        }
    }
    /// The fact's relation name, that is, its deftemplate name.
    pub fn relation(&self) -> String {
        let lexeme = unsafe { ffi::FactRelation(self.raw.as_ptr()) };
        if lexeme.is_null() {
            return String::new();
        }
        unsafe { CStr::from_ptr((*lexeme).contents) }
            .to_string_lossy()
            .into_owned()
    }
    /// The deftemplate this fact was asserted against.
    pub fn template(&self) -> Option<Deftemplate<'env>> {
        NonNull::new(unsafe { ffi::FactDeftemplate(self.raw.as_ptr()) }).map(|raw| Deftemplate {
            raw,
            _environment: self.environment,
        })
    }
    /// The fact's slot names, in template order. Empty for implied facts, which
    /// have no named slots.
    pub fn slot_names(&self) -> Multifield<'env> {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe { ffi::FactSlotNames(self.raw.as_ptr(), &mut raw) };
        Multifield::from_value(Value::retaining(self.environment, raw))
    }
    /// Starts a batched modification.
    ///
    /// CLIPS implements a modification as a retract and re-assert, so the
    /// result is a new fact with a new index.
    pub fn modifier(&self) -> Result<FactModifier<'env>> {
        FactModifier::new(self)
    }

    /// Reads a slot by name. The returned value is retained independently of
    /// the fact.
    pub fn slot(&self, name: &str) -> Result<Value<'env>> {
        let name = CString::new(name)?;
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        match unsafe { ffi::GetFactSlot(self.raw.as_ptr(), name.as_ptr(), &mut raw) } {
            0 => {
                unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
                Ok(Value::from_retained_raw(self.environment, raw))
            }
            code => Err(Error::GetSlot(GetSlotError::from(code))),
        }
    }
}
impl Drop for Fact<'_> {
    fn drop(&mut self) {
        unsafe { ffi::ReleaseFact(self.raw.as_ptr()) }
    }
}

/// Iterates every fact in the environment, in index order.
pub struct Facts<'env> {
    environment: &'env Environment,
    next: *mut ffi::Fact,
}
impl<'env> Facts<'env> {
    pub(crate) fn new(environment: &'env Environment) -> Self {
        Self {
            environment,
            next: std::ptr::null_mut(),
        }
    }
}
impl<'env> Iterator for Facts<'env> {
    type Item = Fact<'env>;
    fn next(&mut self) -> Option<Self::Item> {
        self.next = unsafe { ffi::GetNextFact(self.environment.raw.as_ptr(), self.next) };
        Fact::retained(self.environment, self.next)
    }
}

/// Iterator over the facts asserted against one deftemplate.
pub struct FactsInTemplate<'env> {
    environment: &'env Environment,
    template: NonNull<ffi::Deftemplate>,
    next: *mut ffi::Fact,
}
impl<'env> Iterator for FactsInTemplate<'env> {
    type Item = Fact<'env>;
    fn next(&mut self) -> Option<Self::Item> {
        self.next = unsafe { ffi::GetNextFactInTemplate(self.template.as_ptr(), self.next) };
        Fact::retained(self.environment, self.next)
    }
}

impl Environment {
    /// Looks a fact up by its fact index. Returns `None` once the fact has been
    /// retracted, since CLIPS never reuses an index.
    pub fn find_fact(&self, index: i64) -> Option<Fact<'_>> {
        Fact::retained(self, unsafe {
            ffi::FindIndexedFact(self.raw.as_ptr(), index)
        })
    }
    /// Iterates the facts belonging to one deftemplate.
    pub fn facts_in_template<'env>(
        &'env self,
        template: &Deftemplate<'env>,
    ) -> FactsInTemplate<'env> {
        FactsInTemplate {
            environment: self,
            template: template.raw,
            next: std::ptr::null_mut(),
        }
    }
    /// Whether the fact list changed since this flag was last cleared.
    pub fn fact_list_changed(&self) -> bool {
        unsafe { ffi::GetFactListChanged(self.raw.as_ptr()) }
    }
    /// Sets or clears the fact-list-changed flag.
    pub fn set_fact_list_changed(&self, changed: bool) {
        unsafe { ffi::SetFactListChanged(self.raw.as_ptr(), changed) }
    }

    /// 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.
    pub fn retract_all_facts(&mut self) -> Result<()> {
        match unsafe { ffi::RetractAllFacts(self.raw.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::Retraction(RetractionError::from(code))),
        }
    }
}

/// Builds a fact slot by slot, then asserts it.
///
/// Unlike assembling and parsing assertion text, slot values are passed as
/// real CLIPS values, so nothing has to be escaped or re-parsed.
pub struct FactBuilder<'env> {
    raw: NonNull<ffi::FactBuilder>,
    environment: &'env Environment,
    asserted: bool,
}
impl<'env> FactBuilder<'env> {
    pub(crate) fn new(environment: &'env Environment, template: &str) -> Result<Self> {
        let template = CString::new(template)?;
        NonNull::new(unsafe { ffi::CreateFactBuilder(environment.raw.as_ptr(), template.as_ptr()) })
            .map(|raw| Self {
                raw,
                environment,
                asserted: false,
            })
            .ok_or(Error::FactBuilder(FactBuilderError::from(unsafe {
                ffi::FBError(environment.raw.as_ptr())
            })))
    }
    fn put(
        &mut self,
        slot: &str,
        operation: impl FnOnce(*const std::ffi::c_char) -> u32,
    ) -> Result<&mut Self> {
        let slot = CString::new(slot)?;
        match operation(slot.as_ptr()) {
            0 => Ok(self),
            code => Err(Error::PutSlot(PutSlotError::from(code))),
        }
    }
    /// Sets an integer slot.
    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotInteger(raw, slot, value)
        })
    }
    /// Sets a float slot.
    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotFloat(raw, slot, value)
        })
    }
    /// Sets a symbol slot.
    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotSymbol(raw, slot, value.as_ptr())
        })
    }
    /// Sets a string slot.
    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotString(raw, slot, value.as_ptr())
        })
    }
    /// Sets an instance-name slot.
    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotInstanceName(raw, slot, value.as_ptr())
        })
    }
    /// Sets a slot to a fact address.
    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotFact(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a slot to an instance address.
    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotInstance(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a multifield slot.
    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FBPutSlotMultifield(raw, slot, value.raw())
        })
    }
    /// Assigns an already existing CLIPS value.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
    /// environment, since CLIPS atoms are interned per environment.
    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
        let mut cv = self.environment.check_value(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe { ffi::FBPutSlot(raw, slot, &mut cv) })
    }
    /// Asserts the fact and returns a retained handle to it.
    ///
    /// The builder is reusable afterwards: CLIPS resets its slots, so another
    /// fact of the same template can be built without recreating it.
    pub fn assert(&mut self) -> Result<Fact<'env>> {
        let raw = unsafe { ffi::FBAssert(self.raw.as_ptr()) };
        self.asserted = !raw.is_null();
        Fact::from_result(self.environment, raw, unsafe {
            ffi::FBError(self.environment.raw.as_ptr())
        })
    }
}
impl Drop for FactBuilder<'_> {
    fn drop(&mut self) {
        unsafe {
            if !self.asserted {
                ffi::FBAbort(self.raw.as_ptr())
            }
            ffi::FBDispose(self.raw.as_ptr())
        }
    }
}

/// Collects slot changes and applies them as a single modification.
///
/// Aborts on drop unless [`FactModifier::modify`] was called, so an abandoned
/// modifier leaves the fact untouched.
pub struct FactModifier<'env> {
    raw: NonNull<ffi::FactModifier>,
    environment: &'env Environment,
}
impl<'env> FactModifier<'env> {
    fn new(fact: &Fact<'env>) -> Result<Self> {
        NonNull::new(unsafe {
            ffi::CreateFactModifier(fact.environment.raw.as_ptr(), fact.raw.as_ptr())
        })
        .map(|raw| Self {
            raw,
            environment: fact.environment,
        })
        .ok_or_else(|| {
            Error::FactModifier(crate::error::FactModifierError::from(unsafe {
                ffi::FMError(fact.environment.raw.as_ptr())
            }))
        })
    }
    fn put(
        &mut self,
        slot: &str,
        operation: impl FnOnce(*const std::ffi::c_char) -> u32,
    ) -> Result<&mut Self> {
        let slot = CString::new(slot)?;
        match operation(slot.as_ptr()) {
            0 => Ok(self),
            code => Err(Error::PutSlot(PutSlotError::from(code))),
        }
    }
    /// Sets an integer slot.
    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotInteger(raw, slot, value)
        })
    }
    /// Sets a float slot.
    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotFloat(raw, slot, value)
        })
    }
    /// Sets a symbol slot.
    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotSymbol(raw, slot, value.as_ptr())
        })
    }
    /// Sets a string slot.
    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotString(raw, slot, value.as_ptr())
        })
    }
    /// Sets an instance-name slot.
    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotInstanceName(raw, slot, value.as_ptr())
        })
    }
    /// Sets a slot to a fact address.
    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotFact(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a slot to an instance address.
    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotInstance(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a multifield slot.
    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::FMPutSlotMultifield(raw, slot, value.raw())
        })
    }
    /// Assigns an already existing CLIPS value.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
    /// environment, since CLIPS atoms are interned per environment.
    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
        let mut cv = self.environment.check_value(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe { ffi::FMPutSlot(raw, slot, &mut cv) })
    }
    /// Applies the collected changes and returns the resulting fact.
    ///
    /// CLIPS retracts the original and asserts a replacement, so the returned
    /// fact has a new index and the original reports itself retracted. Slots
    /// left unset keep their previous values.
    pub fn modify(&mut self) -> Result<Fact<'env>> {
        let raw = unsafe { ffi::FMModify(self.raw.as_ptr()) };
        Fact::retained(self.environment, raw).ok_or_else(|| {
            Error::FactModifier(crate::error::FactModifierError::from(unsafe {
                ffi::FMError(self.environment.raw.as_ptr())
            }))
        })
    }

    /// Discards the collected changes, leaving the fact untouched.
    pub fn abort(&mut self) {
        unsafe { ffi::FMAbort(self.raw.as_ptr()) }
    }
}
impl Drop for FactModifier<'_> {
    fn drop(&mut self) {
        unsafe {
            ffi::FMAbort(self.raw.as_ptr());
            ffi::FMDispose(self.raw.as_ptr())
        }
    }
}