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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! COOL class metadata and message-handler inspection.

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

use crate::{Defclass, Environment, SlotDefaultType, ffi};

/// Which stage of a message send a handler runs in.
///
/// A send runs every applicable handler in this order: `around` handlers wrap
/// everything, then `before`, then the most specific `primary`, then `after`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HandlerType {
    /// Wraps the whole send; must call `call-next-handler` to continue it.
    Around,
    /// Runs before the primary handler.
    Before,
    /// Does the work and produces the send's return value.
    Primary,
    /// Runs after the primary handler.
    After,
}

impl HandlerType {
    fn as_str(self) -> &'static str {
        match self {
            Self::Around => "around",
            Self::Before => "before",
            Self::Primary => "primary",
            Self::After => "after",
        }
    }
}

/// Why a class or message-handler operation failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClassError {
    /// A name contained a NUL byte.
    InteriorNul,
    /// No defclass of that name exists.
    ClassNotFound(String),
    /// The class has no handler of that name and type.
    HandlerNotFound {
        /// The class searched.
        class: String,
        /// The handler name searched for.
        name: String,
        /// The handler type searched for.
        kind: HandlerType,
    },
    /// CLIPS refuses to undefine the class, typically because instances of it
    /// exist or another class inherits from it.
    ClassNotDeletable(String),
    /// CLIPS refuses to undefine the handler, typically because it is running.
    HandlerNotDeletable {
        /// The class the handler belongs to.
        class: String,
        /// The handler's name.
        name: String,
        /// The handler's type.
        kind: HandlerType,
    },
    /// CLIPS reported the construct as deletable but then refused the
    /// undefinition.
    UndefineRejected,
}

impl std::fmt::Display for ClassError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "CLIPS class error: {self:?}")
    }
}

impl std::error::Error for ClassError {}

/// A message-handler index tied to an immutable borrow of its class.
pub struct MessageHandler<'class> {
    class: NonNull<ffi::Defclass>,
    index: u32,
    marker: PhantomData<&'class Environment>,
}

impl MessageHandler<'_> {
    /// The message this handler responds to.
    pub fn name(&self) -> &str {
        unsafe { CStr::from_ptr(ffi::DefmessageHandlerName(self.class.as_ptr(), self.index)) }
            .to_str()
            .unwrap_or("")
    }

    /// Which stage of a send this handler runs in.
    ///
    /// # Panics
    ///
    /// Panics if CLIPS reports a handler type outside the four documented ones,
    /// which would mean this crate's model of COOL is wrong.
    pub fn handler_type(&self) -> HandlerType {
        match unsafe {
            CStr::from_ptr(ffi::DefmessageHandlerType(self.class.as_ptr(), self.index)).to_bytes()
        } {
            b"around" => HandlerType::Around,
            b"before" => HandlerType::Before,
            b"primary" => HandlerType::Primary,
            b"after" => HandlerType::After,
            other => panic!("CLIPS returned unknown message-handler type {other:?}"),
        }
    }

    /// Returns `None` for system handlers, which have no source pretty-print form.
    pub fn pretty_print(&self) -> Option<&str> {
        let text = unsafe { ffi::DefmessageHandlerPPForm(self.class.as_ptr(), self.index) };
        (!text.is_null())
            .then(|| unsafe { CStr::from_ptr(text) }.to_str().ok())
            .flatten()
    }

    /// Whether the handler can currently be undefined.
    pub fn is_deletable(&self) -> bool {
        unsafe { ffi::DefmessageHandlerIsDeletable(self.class.as_ptr(), self.index) }
    }

    /// Whether CLIPS traces this handler as it runs.
    pub fn watch(&self) -> bool {
        unsafe { ffi::DefmessageHandlerGetWatch(self.class.as_ptr(), self.index) }
    }

    /// Enables or disables tracing of this handler.
    pub fn set_watch(&mut self, enabled: bool) {
        unsafe { ffi::DefmessageHandlerSetWatch(self.class.as_ptr(), self.index, enabled) }
    }
}

/// Iterates a class's own message handlers, excluding inherited ones.
pub struct MessageHandlers<'class> {
    class: NonNull<ffi::Defclass>,
    current: u32,
    marker: PhantomData<&'class Environment>,
}

impl<'class> Iterator for MessageHandlers<'class> {
    type Item = MessageHandler<'class>;

    fn next(&mut self) -> Option<Self::Item> {
        self.current = unsafe { ffi::GetNextDefmessageHandler(self.class.as_ptr(), self.current) };
        (self.current != 0).then_some(MessageHandler {
            class: self.class,
            index: self.current,
            marker: PhantomData,
        })
    }
}

/// Whether CLIPS creates slot accessor handlers a defclass does not declare.
///
/// The CLIPS name is misleading: despite "defaults", this does not affect slot
/// *default values*, which are supplied the same way under both modes. In
/// 6.4.2 it controls only the `create-accessor` facet, so the observable
/// difference is whether `get-`/`put-` message handlers are generated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum ClassDefaultsMode {
    /// Readable slots get a `get-` handler, writable ones also a `put-`
    /// handler, unless the slot declares otherwise.
    Convenience = 0,
    /// Only explicitly declared handlers are created.
    Conservation = 1,
}

impl ClassDefaultsMode {
    fn from_code(code: u32) -> Self {
        match code {
            1 => Self::Conservation,
            _ => Self::Convenience,
        }
    }
}

impl Defclass<'_> {
    /// Whether the class is abstract, meaning it cannot have direct instances.
    pub fn is_abstract(&self) -> bool {
        unsafe { ffi::ClassAbstractP(self.raw()) }
    }

    /// Prints the handlers a `send` of `message` would run, in execution order,
    /// to the `logical_name` output stream.
    ///
    /// CLIPS only offers this as printed text, so capture it with a
    /// [`crate::Router`] registered for `logical_name`. Nothing is printed if
    /// no handler applies.
    pub fn preview_send(&self, logical_name: &str, message: &str) -> crate::Result<()> {
        let logical_name = std::ffi::CString::new(logical_name)?;
        let message = std::ffi::CString::new(message)?;
        unsafe { ffi::PreviewSend(self.raw(), logical_name.as_ptr(), message.as_ptr()) };
        Ok(())
    }

    /// Whether instances of the class take part in rule pattern matching.
    pub fn is_reactive(&self) -> bool {
        unsafe { ffi::ClassReactiveP(self.raw()) }
    }

    /// Returns slot names, optionally including inherited slots.
    pub fn slots(&self, inherit: bool) -> Vec<String> {
        let mut output = null_value();
        unsafe { ffi::ClassSlots(self.raw(), &mut output, inherit) };
        unsafe { lexeme_multifield(&output) }
    }

    /// Returns superclass names, nearest first when `inherit` is false and the
    /// full precedence chain when it is true.
    pub fn superclasses(&self, inherit: bool) -> Vec<String> {
        let mut output = null_value();
        unsafe { ffi::ClassSuperclasses(self.raw(), &mut output, inherit) };
        unsafe { lexeme_multifield(&output) }
    }

    /// Returns subclass names, optionally walking the full descendant tree.
    pub fn subclasses(&self, inherit: bool) -> Vec<String> {
        let mut output = null_value();
        unsafe { ffi::ClassSubclasses(self.raw(), &mut output, inherit) };
        unsafe { lexeme_multifield(&output) }
    }

    /// Whether the class defines or inherits a slot of this name.
    pub fn has_slot(&self, name: &str, inherit: bool) -> Result<bool, ClassError> {
        let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
        Ok(unsafe { ffi::SlotExistP(self.raw(), name.as_ptr(), inherit) })
    }

    /// Borrows a slot for constraint and access inspection.
    ///
    /// Returns `None` when the class has no such slot, including inherited ones.
    pub fn slot(&self, name: &str) -> Result<Option<ClassSlot<'_>>, ClassError> {
        if !self.has_slot(name, true)? {
            return Ok(None);
        }
        let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
        Ok(Some(ClassSlot {
            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
            name: c_name,
            marker: PhantomData,
        }))
    }

    /// Whether `self` is a superclass of `other`, that is, whether `other`
    /// inherits from it.
    ///
    /// Both handles borrow the same environment, so no cross-environment
    /// comparison is expressible.
    pub fn is_superclass_of(&self, other: &Defclass<'_>) -> bool {
        unsafe { ffi::SuperclassP(self.raw(), other.raw()) }
    }

    /// Whether `self` is a subclass of `other`.
    pub fn is_subclass_of(&self, other: &Defclass<'_>) -> bool {
        unsafe { ffi::SubclassP(self.raw(), other.raw()) }
    }

    /// The class precedence list, most specific first, as CLIPS resolves it.
    pub fn precedence_list(&self) -> Vec<String> {
        let mut names = vec![
            unsafe { CStr::from_ptr(ffi::DefclassName(self.raw())) }
                .to_string_lossy()
                .into_owned(),
        ];
        names.extend(self.superclasses(true));
        names
    }

    /// Iterates the handlers defined on this class itself.
    ///
    /// Inherited handlers are not included; walk
    /// [`Defclass::precedence_list`] to see those.
    pub fn message_handlers(&self) -> MessageHandlers<'_> {
        MessageHandlers {
            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
            current: 0,
            marker: PhantomData,
        }
    }

    /// Looks up one of this class's own handlers by message name and type.
    pub fn find_message_handler(
        &self,
        name: &str,
        kind: HandlerType,
    ) -> Result<Option<MessageHandler<'_>>, ClassError> {
        let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
        let kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
        let index = unsafe { ffi::FindDefmessageHandler(self.raw(), name.as_ptr(), kind.as_ptr()) };
        Ok((index != 0).then_some(MessageHandler {
            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
            index,
            marker: PhantomData,
        }))
    }
}

impl Environment {
    /// Whether accessor handlers are generated for classes defined from now on.
    pub fn class_defaults_mode(&self) -> ClassDefaultsMode {
        ClassDefaultsMode::from_code(unsafe { ffi::GetClassDefaultsMode(self.raw.as_ptr()) })
    }

    /// Sets the mode for classes defined afterwards and returns the previous
    /// mode. Existing classes keep the mode they were defined under.
    pub fn set_class_defaults_mode(&mut self, mode: ClassDefaultsMode) -> ClassDefaultsMode {
        ClassDefaultsMode::from_code(unsafe {
            ffi::SetClassDefaultsMode(self.raw.as_ptr(), mode as u32)
        })
    }

    /// Undefines a class after resolving it in this environment.
    pub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError> {
        let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
        let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_name.as_ptr()) })
            .ok_or_else(|| ClassError::ClassNotFound(name.to_owned()))?;
        if !unsafe { ffi::DefclassIsDeletable(class.as_ptr()) } {
            return Err(ClassError::ClassNotDeletable(name.to_owned()));
        }
        unsafe { ffi::Undefclass(class.as_ptr(), self.raw.as_ptr()) }
            .then_some(())
            .ok_or(ClassError::UndefineRejected)
    }

    /// Resolves the handler immediately before deletion, so no handler index is
    /// retained across a mutation of the class's handler array.
    pub fn undefine_message_handler(
        &mut self,
        class_name: &str,
        handler_name: &str,
        kind: HandlerType,
    ) -> Result<(), ClassError> {
        let c_class = CString::new(class_name).map_err(|_| ClassError::InteriorNul)?;
        let c_handler = CString::new(handler_name).map_err(|_| ClassError::InteriorNul)?;
        let c_kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
        let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_class.as_ptr()) })
            .ok_or_else(|| ClassError::ClassNotFound(class_name.to_owned()))?;
        let index = unsafe {
            ffi::FindDefmessageHandler(class.as_ptr(), c_handler.as_ptr(), c_kind.as_ptr())
        };
        if index == 0 {
            return Err(ClassError::HandlerNotFound {
                class: class_name.to_owned(),
                name: handler_name.to_owned(),
                kind,
            });
        }
        if !unsafe { ffi::DefmessageHandlerIsDeletable(class.as_ptr(), index) } {
            return Err(ClassError::HandlerNotDeletable {
                class: class_name.to_owned(),
                name: handler_name.to_owned(),
                kind,
            });
        }
        unsafe { ffi::UndefmessageHandler(class.as_ptr(), index, self.raw.as_ptr()) }
            .then_some(())
            .ok_or(ClassError::UndefineRejected)
    }
}

/// A named slot borrowed from a class, used to inspect its facets and
/// constraints.
///
/// Slot queries name the slot on every call, so no index into the class's slot
/// array is ever retained across a mutation.
pub struct ClassSlot<'class> {
    class: NonNull<ffi::Defclass>,
    name: CString,
    marker: PhantomData<&'class Environment>,
}

impl ClassSlot<'_> {
    /// The classes a slot's definition comes from, most specific first.
    pub fn sources(&self) -> Vec<String> {
        self.query(ffi::SlotSources)
    }
    /// The slot's facets as CLIPS's own abbreviations, in its documented order:
    /// field type, storage, propagation, access, sharing, pattern match,
    /// visibility, create-accessor, override message, and source, for example
    /// `SGL STC INH R SHR RCT EXC PUB R NIL`.
    ///
    /// Unlike [`ClassSlot::is_public`], this query does follow inheritance.
    pub fn facets(&self) -> Vec<String> {
        self.query(ffi::SlotFacets)
    }
    /// The allowed primitive types, or an empty vector when unconstrained.
    pub fn allowed_types(&self) -> Vec<String> {
        self.query(ffi::SlotTypes)
    }
    /// The allowed classes, or an empty vector when unconstrained.
    pub fn allowed_classes(&self) -> Vec<String> {
        self.query(ffi::SlotAllowedClasses)
    }
    /// The allowed values as their printed forms, or an empty vector when
    /// unconstrained.
    pub fn allowed_values(&self) -> Vec<String> {
        self.query(ffi::SlotAllowedValues)
    }
    /// The numeric range as `(low, high)` printed forms, when constrained.
    pub fn range(&self) -> Option<(String, String)> {
        let values = self.query_any(ffi::SlotRange);
        match values.as_slice() {
            [low, high] => Some((low.clone(), high.clone())),
            _ => None,
        }
    }
    /// The multislot cardinality as `(minimum, maximum)` printed forms. Single
    /// slots have no cardinality and return `None`.
    pub fn cardinality(&self) -> Option<(String, String)> {
        let values = self.query_any(ffi::SlotCardinality);
        match values.as_slice() {
            [low, high] => Some((low.clone(), high.clone())),
            _ => None,
        }
    }
    /// Whether the slot has a static default, a dynamic one, or none at all.
    ///
    /// Unlike the other queries here, CLIPS resolves this one without following
    /// inheritance, so an inherited slot reports [`SlotDefaultType::None`]. Ask
    /// the class named by [`ClassSlot::sources`] for the defining class's
    /// answer.
    pub fn default_type(&self, environment: &Environment) -> SlotDefaultType {
        match unsafe {
            ffi::SlotDefaultP(
                environment.raw.as_ptr(),
                self.class.as_ptr(),
                self.name.as_ptr(),
            )
        } {
            0 => SlotDefaultType::None,
            1 => SlotDefaultType::Static,
            _ => SlotDefaultType::Dynamic,
        }
    }
    /// The slot's default value as its printed form, when it has one.
    pub fn default_value(&self) -> Option<String> {
        let values = self.query_any(ffi::SlotDefaultValue);
        values.first().cloned()
    }
    /// Whether the slot can be written after the instance is created.
    pub fn is_writable(&self) -> bool {
        unsafe { ffi::SlotWritableP(self.class.as_ptr(), self.name.as_ptr()) }
    }
    /// Whether the slot can be set by `make-instance`.
    pub fn is_initable(&self) -> bool {
        unsafe { ffi::SlotInitableP(self.class.as_ptr(), self.name.as_ptr()) }
    }
    /// Whether subclasses may access the slot directly.
    ///
    /// Like [`ClassSlot::default_type`], CLIPS resolves this without following
    /// inheritance, so an inherited slot reports `false`. Ask the class named
    /// by [`ClassSlot::sources`] for the defining class's answer.
    pub fn is_public(&self) -> bool {
        unsafe { ffi::SlotPublicP(self.class.as_ptr(), self.name.as_ptr()) }
    }
    /// Whether handlers of this class may read the slot without a message.
    pub fn has_direct_access(&self) -> bool {
        unsafe { ffi::SlotDirectAccessP(self.class.as_ptr(), self.name.as_ptr()) }
    }

    /// Runs a lexeme-valued CLIPS slot query.
    fn query(
        &self,
        query: unsafe extern "C" fn(
            *mut ffi::Defclass,
            *const std::ffi::c_char,
            *mut ffi::CLIPSValue,
        ) -> bool,
    ) -> Vec<String> {
        let mut output = null_value();
        if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
            return Vec::new();
        }
        unsafe { lexeme_multifield(&output) }
    }

    /// Runs a slot query whose fields may be numbers as well as lexemes, and
    /// renders each field as text.
    fn query_any(
        &self,
        query: unsafe extern "C" fn(
            *mut ffi::Defclass,
            *const std::ffi::c_char,
            *mut ffi::CLIPSValue,
        ) -> bool,
    ) -> Vec<String> {
        let mut output = null_value();
        if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
            return Vec::new();
        }
        unsafe { printed_multifield(&output) }
    }
}

fn null_value() -> ffi::CLIPSValue {
    ffi::CLIPSValue {
        value: std::ptr::null_mut(),
    }
}

/// Renders every field of a multifield as text, including numeric fields, which
/// slot ranges, cardinalities, and defaults use.
/// Renders a CLIPS result as text fields. Single-valued results, which slot
/// defaults use, become a one-element vector.
unsafe fn printed_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
    if unsafe { value.value.is_null() } {
        return Vec::new();
    }
    if unsafe { (*value.header).type_ } != 4 {
        return vec![unsafe { printed_field(value) }];
    }
    let multifield = unsafe { &*value.multifield };
    (0..multifield.length)
        .map(|index| unsafe { printed_field(&*multifield.contents.as_ptr().add(index)) })
        .collect()
}

unsafe fn printed_field(cell: &ffi::CLIPSValue) -> String {
    match unsafe { (*cell.header).type_ } {
        0 => unsafe { (*cell.float).contents }.to_string(),
        1 => unsafe { (*cell.integer).contents }.to_string(),
        2 | 3 | 8 => unsafe { CStr::from_ptr((*cell.lexeme).contents) }
            .to_string_lossy()
            .into_owned(),
        other => format!("<type {other}>"),
    }
}

unsafe fn lexeme_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
    if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
        return Vec::new();
    }
    let multifield = unsafe { &*value.multifield };
    (0..multifield.length)
        .filter_map(|index| {
            let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
            let type_code = unsafe { (*cell.header).type_ };
            matches!(type_code, 2 | 3 | 8).then(|| {
                unsafe { CStr::from_ptr((*cell.lexeme).contents) }
                    .to_string_lossy()
                    .into_owned()
            })
        })
        .collect()
}