Skip to main content

clips_bindings/
class.rs

1//! COOL class metadata and message-handler inspection.
2
3use std::ffi::{CStr, CString};
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::{Defclass, Environment, SlotDefaultType, ffi};
8
9/// Which stage of a message send a handler runs in.
10///
11/// A send runs every applicable handler in this order: `around` handlers wrap
12/// everything, then `before`, then the most specific `primary`, then `after`.
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum HandlerType {
15    /// Wraps the whole send; must call `call-next-handler` to continue it.
16    Around,
17    /// Runs before the primary handler.
18    Before,
19    /// Does the work and produces the send's return value.
20    Primary,
21    /// Runs after the primary handler.
22    After,
23}
24
25impl HandlerType {
26    fn as_str(self) -> &'static str {
27        match self {
28            Self::Around => "around",
29            Self::Before => "before",
30            Self::Primary => "primary",
31            Self::After => "after",
32        }
33    }
34}
35
36/// Why a class or message-handler operation failed.
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub enum ClassError {
39    /// A name contained a NUL byte.
40    InteriorNul,
41    /// No defclass of that name exists.
42    ClassNotFound(String),
43    /// The class has no handler of that name and type.
44    HandlerNotFound {
45        /// The class searched.
46        class: String,
47        /// The handler name searched for.
48        name: String,
49        /// The handler type searched for.
50        kind: HandlerType,
51    },
52    /// CLIPS refuses to undefine the class, typically because instances of it
53    /// exist or another class inherits from it.
54    ClassNotDeletable(String),
55    /// CLIPS refuses to undefine the handler, typically because it is running.
56    HandlerNotDeletable {
57        /// The class the handler belongs to.
58        class: String,
59        /// The handler's name.
60        name: String,
61        /// The handler's type.
62        kind: HandlerType,
63    },
64    /// CLIPS reported the construct as deletable but then refused the
65    /// undefinition.
66    UndefineRejected,
67}
68
69impl std::fmt::Display for ClassError {
70    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(formatter, "CLIPS class error: {self:?}")
72    }
73}
74
75impl std::error::Error for ClassError {}
76
77/// A message-handler index tied to an immutable borrow of its class.
78pub struct MessageHandler<'class> {
79    class: NonNull<ffi::Defclass>,
80    index: u32,
81    marker: PhantomData<&'class Environment>,
82}
83
84impl MessageHandler<'_> {
85    /// The message this handler responds to.
86    pub fn name(&self) -> &str {
87        unsafe { CStr::from_ptr(ffi::DefmessageHandlerName(self.class.as_ptr(), self.index)) }
88            .to_str()
89            .unwrap_or("")
90    }
91
92    /// Which stage of a send this handler runs in.
93    ///
94    /// # Panics
95    ///
96    /// Panics if CLIPS reports a handler type outside the four documented ones,
97    /// which would mean this crate's model of COOL is wrong.
98    pub fn handler_type(&self) -> HandlerType {
99        match unsafe {
100            CStr::from_ptr(ffi::DefmessageHandlerType(self.class.as_ptr(), self.index)).to_bytes()
101        } {
102            b"around" => HandlerType::Around,
103            b"before" => HandlerType::Before,
104            b"primary" => HandlerType::Primary,
105            b"after" => HandlerType::After,
106            other => panic!("CLIPS returned unknown message-handler type {other:?}"),
107        }
108    }
109
110    /// Returns `None` for system handlers, which have no source pretty-print form.
111    pub fn pretty_print(&self) -> Option<&str> {
112        let text = unsafe { ffi::DefmessageHandlerPPForm(self.class.as_ptr(), self.index) };
113        (!text.is_null())
114            .then(|| unsafe { CStr::from_ptr(text) }.to_str().ok())
115            .flatten()
116    }
117
118    /// Whether the handler can currently be undefined.
119    pub fn is_deletable(&self) -> bool {
120        unsafe { ffi::DefmessageHandlerIsDeletable(self.class.as_ptr(), self.index) }
121    }
122
123    /// Whether CLIPS traces this handler as it runs.
124    pub fn watch(&self) -> bool {
125        unsafe { ffi::DefmessageHandlerGetWatch(self.class.as_ptr(), self.index) }
126    }
127
128    /// Enables or disables tracing of this handler.
129    pub fn set_watch(&mut self, enabled: bool) {
130        unsafe { ffi::DefmessageHandlerSetWatch(self.class.as_ptr(), self.index, enabled) }
131    }
132}
133
134/// Iterates a class's own message handlers, excluding inherited ones.
135pub struct MessageHandlers<'class> {
136    class: NonNull<ffi::Defclass>,
137    current: u32,
138    marker: PhantomData<&'class Environment>,
139}
140
141impl<'class> Iterator for MessageHandlers<'class> {
142    type Item = MessageHandler<'class>;
143
144    fn next(&mut self) -> Option<Self::Item> {
145        self.current = unsafe { ffi::GetNextDefmessageHandler(self.class.as_ptr(), self.current) };
146        (self.current != 0).then_some(MessageHandler {
147            class: self.class,
148            index: self.current,
149            marker: PhantomData,
150        })
151    }
152}
153
154/// Whether CLIPS creates slot accessor handlers a defclass does not declare.
155///
156/// The CLIPS name is misleading: despite "defaults", this does not affect slot
157/// *default values*, which are supplied the same way under both modes. In
158/// 6.4.2 it controls only the `create-accessor` facet, so the observable
159/// difference is whether `get-`/`put-` message handlers are generated.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161#[repr(u32)]
162pub enum ClassDefaultsMode {
163    /// Readable slots get a `get-` handler, writable ones also a `put-`
164    /// handler, unless the slot declares otherwise.
165    Convenience = 0,
166    /// Only explicitly declared handlers are created.
167    Conservation = 1,
168}
169
170impl ClassDefaultsMode {
171    fn from_code(code: u32) -> Self {
172        match code {
173            1 => Self::Conservation,
174            _ => Self::Convenience,
175        }
176    }
177}
178
179impl Defclass<'_> {
180    /// Whether the class is abstract, meaning it cannot have direct instances.
181    pub fn is_abstract(&self) -> bool {
182        unsafe { ffi::ClassAbstractP(self.raw()) }
183    }
184
185    /// Prints the handlers a `send` of `message` would run, in execution order,
186    /// to the `logical_name` output stream.
187    ///
188    /// CLIPS only offers this as printed text, so capture it with a
189    /// [`crate::Router`] registered for `logical_name`. Nothing is printed if
190    /// no handler applies.
191    pub fn preview_send(&self, logical_name: &str, message: &str) -> crate::Result<()> {
192        let logical_name = std::ffi::CString::new(logical_name)?;
193        let message = std::ffi::CString::new(message)?;
194        unsafe { ffi::PreviewSend(self.raw(), logical_name.as_ptr(), message.as_ptr()) };
195        Ok(())
196    }
197
198    /// Whether instances of the class take part in rule pattern matching.
199    pub fn is_reactive(&self) -> bool {
200        unsafe { ffi::ClassReactiveP(self.raw()) }
201    }
202
203    /// Returns slot names, optionally including inherited slots.
204    pub fn slots(&self, inherit: bool) -> Vec<String> {
205        let mut output = null_value();
206        unsafe { ffi::ClassSlots(self.raw(), &mut output, inherit) };
207        unsafe { lexeme_multifield(&output) }
208    }
209
210    /// Returns superclass names, nearest first when `inherit` is false and the
211    /// full precedence chain when it is true.
212    pub fn superclasses(&self, inherit: bool) -> Vec<String> {
213        let mut output = null_value();
214        unsafe { ffi::ClassSuperclasses(self.raw(), &mut output, inherit) };
215        unsafe { lexeme_multifield(&output) }
216    }
217
218    /// Returns subclass names, optionally walking the full descendant tree.
219    pub fn subclasses(&self, inherit: bool) -> Vec<String> {
220        let mut output = null_value();
221        unsafe { ffi::ClassSubclasses(self.raw(), &mut output, inherit) };
222        unsafe { lexeme_multifield(&output) }
223    }
224
225    /// Whether the class defines or inherits a slot of this name.
226    pub fn has_slot(&self, name: &str, inherit: bool) -> Result<bool, ClassError> {
227        let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
228        Ok(unsafe { ffi::SlotExistP(self.raw(), name.as_ptr(), inherit) })
229    }
230
231    /// Borrows a slot for constraint and access inspection.
232    ///
233    /// Returns `None` when the class has no such slot, including inherited ones.
234    pub fn slot(&self, name: &str) -> Result<Option<ClassSlot<'_>>, ClassError> {
235        if !self.has_slot(name, true)? {
236            return Ok(None);
237        }
238        let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
239        Ok(Some(ClassSlot {
240            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
241            name: c_name,
242            marker: PhantomData,
243        }))
244    }
245
246    /// Whether `self` is a superclass of `other`, that is, whether `other`
247    /// inherits from it.
248    ///
249    /// Both handles borrow the same environment, so no cross-environment
250    /// comparison is expressible.
251    pub fn is_superclass_of(&self, other: &Defclass<'_>) -> bool {
252        unsafe { ffi::SuperclassP(self.raw(), other.raw()) }
253    }
254
255    /// Whether `self` is a subclass of `other`.
256    pub fn is_subclass_of(&self, other: &Defclass<'_>) -> bool {
257        unsafe { ffi::SubclassP(self.raw(), other.raw()) }
258    }
259
260    /// The class precedence list, most specific first, as CLIPS resolves it.
261    pub fn precedence_list(&self) -> Vec<String> {
262        let mut names = vec![
263            unsafe { CStr::from_ptr(ffi::DefclassName(self.raw())) }
264                .to_string_lossy()
265                .into_owned(),
266        ];
267        names.extend(self.superclasses(true));
268        names
269    }
270
271    /// Iterates the handlers defined on this class itself.
272    ///
273    /// Inherited handlers are not included; walk
274    /// [`Defclass::precedence_list`] to see those.
275    pub fn message_handlers(&self) -> MessageHandlers<'_> {
276        MessageHandlers {
277            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
278            current: 0,
279            marker: PhantomData,
280        }
281    }
282
283    /// Looks up one of this class's own handlers by message name and type.
284    pub fn find_message_handler(
285        &self,
286        name: &str,
287        kind: HandlerType,
288    ) -> Result<Option<MessageHandler<'_>>, ClassError> {
289        let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
290        let kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
291        let index = unsafe { ffi::FindDefmessageHandler(self.raw(), name.as_ptr(), kind.as_ptr()) };
292        Ok((index != 0).then_some(MessageHandler {
293            class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
294            index,
295            marker: PhantomData,
296        }))
297    }
298}
299
300impl Environment {
301    /// Whether accessor handlers are generated for classes defined from now on.
302    pub fn class_defaults_mode(&self) -> ClassDefaultsMode {
303        ClassDefaultsMode::from_code(unsafe { ffi::GetClassDefaultsMode(self.raw.as_ptr()) })
304    }
305
306    /// Sets the mode for classes defined afterwards and returns the previous
307    /// mode. Existing classes keep the mode they were defined under.
308    pub fn set_class_defaults_mode(&mut self, mode: ClassDefaultsMode) -> ClassDefaultsMode {
309        ClassDefaultsMode::from_code(unsafe {
310            ffi::SetClassDefaultsMode(self.raw.as_ptr(), mode as u32)
311        })
312    }
313
314    /// Undefines a class after resolving it in this environment.
315    pub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError> {
316        let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
317        let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_name.as_ptr()) })
318            .ok_or_else(|| ClassError::ClassNotFound(name.to_owned()))?;
319        if !unsafe { ffi::DefclassIsDeletable(class.as_ptr()) } {
320            return Err(ClassError::ClassNotDeletable(name.to_owned()));
321        }
322        unsafe { ffi::Undefclass(class.as_ptr(), self.raw.as_ptr()) }
323            .then_some(())
324            .ok_or(ClassError::UndefineRejected)
325    }
326
327    /// Resolves the handler immediately before deletion, so no handler index is
328    /// retained across a mutation of the class's handler array.
329    pub fn undefine_message_handler(
330        &mut self,
331        class_name: &str,
332        handler_name: &str,
333        kind: HandlerType,
334    ) -> Result<(), ClassError> {
335        let c_class = CString::new(class_name).map_err(|_| ClassError::InteriorNul)?;
336        let c_handler = CString::new(handler_name).map_err(|_| ClassError::InteriorNul)?;
337        let c_kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
338        let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_class.as_ptr()) })
339            .ok_or_else(|| ClassError::ClassNotFound(class_name.to_owned()))?;
340        let index = unsafe {
341            ffi::FindDefmessageHandler(class.as_ptr(), c_handler.as_ptr(), c_kind.as_ptr())
342        };
343        if index == 0 {
344            return Err(ClassError::HandlerNotFound {
345                class: class_name.to_owned(),
346                name: handler_name.to_owned(),
347                kind,
348            });
349        }
350        if !unsafe { ffi::DefmessageHandlerIsDeletable(class.as_ptr(), index) } {
351            return Err(ClassError::HandlerNotDeletable {
352                class: class_name.to_owned(),
353                name: handler_name.to_owned(),
354                kind,
355            });
356        }
357        unsafe { ffi::UndefmessageHandler(class.as_ptr(), index, self.raw.as_ptr()) }
358            .then_some(())
359            .ok_or(ClassError::UndefineRejected)
360    }
361}
362
363/// A named slot borrowed from a class, used to inspect its facets and
364/// constraints.
365///
366/// Slot queries name the slot on every call, so no index into the class's slot
367/// array is ever retained across a mutation.
368pub struct ClassSlot<'class> {
369    class: NonNull<ffi::Defclass>,
370    name: CString,
371    marker: PhantomData<&'class Environment>,
372}
373
374impl ClassSlot<'_> {
375    /// The classes a slot's definition comes from, most specific first.
376    pub fn sources(&self) -> Vec<String> {
377        self.query(ffi::SlotSources)
378    }
379    /// The slot's facets as CLIPS's own abbreviations, in its documented order:
380    /// field type, storage, propagation, access, sharing, pattern match,
381    /// visibility, create-accessor, override message, and source, for example
382    /// `SGL STC INH R SHR RCT EXC PUB R NIL`.
383    ///
384    /// Unlike [`ClassSlot::is_public`], this query does follow inheritance.
385    pub fn facets(&self) -> Vec<String> {
386        self.query(ffi::SlotFacets)
387    }
388    /// The allowed primitive types, or an empty vector when unconstrained.
389    pub fn allowed_types(&self) -> Vec<String> {
390        self.query(ffi::SlotTypes)
391    }
392    /// The allowed classes, or an empty vector when unconstrained.
393    pub fn allowed_classes(&self) -> Vec<String> {
394        self.query(ffi::SlotAllowedClasses)
395    }
396    /// The allowed values as their printed forms, or an empty vector when
397    /// unconstrained.
398    pub fn allowed_values(&self) -> Vec<String> {
399        self.query(ffi::SlotAllowedValues)
400    }
401    /// The numeric range as `(low, high)` printed forms, when constrained.
402    pub fn range(&self) -> Option<(String, String)> {
403        let values = self.query_any(ffi::SlotRange);
404        match values.as_slice() {
405            [low, high] => Some((low.clone(), high.clone())),
406            _ => None,
407        }
408    }
409    /// The multislot cardinality as `(minimum, maximum)` printed forms. Single
410    /// slots have no cardinality and return `None`.
411    pub fn cardinality(&self) -> Option<(String, String)> {
412        let values = self.query_any(ffi::SlotCardinality);
413        match values.as_slice() {
414            [low, high] => Some((low.clone(), high.clone())),
415            _ => None,
416        }
417    }
418    /// Whether the slot has a static default, a dynamic one, or none at all.
419    ///
420    /// Unlike the other queries here, CLIPS resolves this one without following
421    /// inheritance, so an inherited slot reports [`SlotDefaultType::None`]. Ask
422    /// the class named by [`ClassSlot::sources`] for the defining class's
423    /// answer.
424    pub fn default_type(&self, environment: &Environment) -> SlotDefaultType {
425        match unsafe {
426            ffi::SlotDefaultP(
427                environment.raw.as_ptr(),
428                self.class.as_ptr(),
429                self.name.as_ptr(),
430            )
431        } {
432            0 => SlotDefaultType::None,
433            1 => SlotDefaultType::Static,
434            _ => SlotDefaultType::Dynamic,
435        }
436    }
437    /// The slot's default value as its printed form, when it has one.
438    pub fn default_value(&self) -> Option<String> {
439        let values = self.query_any(ffi::SlotDefaultValue);
440        values.first().cloned()
441    }
442    /// Whether the slot can be written after the instance is created.
443    pub fn is_writable(&self) -> bool {
444        unsafe { ffi::SlotWritableP(self.class.as_ptr(), self.name.as_ptr()) }
445    }
446    /// Whether the slot can be set by `make-instance`.
447    pub fn is_initable(&self) -> bool {
448        unsafe { ffi::SlotInitableP(self.class.as_ptr(), self.name.as_ptr()) }
449    }
450    /// Whether subclasses may access the slot directly.
451    ///
452    /// Like [`ClassSlot::default_type`], CLIPS resolves this without following
453    /// inheritance, so an inherited slot reports `false`. Ask the class named
454    /// by [`ClassSlot::sources`] for the defining class's answer.
455    pub fn is_public(&self) -> bool {
456        unsafe { ffi::SlotPublicP(self.class.as_ptr(), self.name.as_ptr()) }
457    }
458    /// Whether handlers of this class may read the slot without a message.
459    pub fn has_direct_access(&self) -> bool {
460        unsafe { ffi::SlotDirectAccessP(self.class.as_ptr(), self.name.as_ptr()) }
461    }
462
463    /// Runs a lexeme-valued CLIPS slot query.
464    fn query(
465        &self,
466        query: unsafe extern "C" fn(
467            *mut ffi::Defclass,
468            *const std::ffi::c_char,
469            *mut ffi::CLIPSValue,
470        ) -> bool,
471    ) -> Vec<String> {
472        let mut output = null_value();
473        if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
474            return Vec::new();
475        }
476        unsafe { lexeme_multifield(&output) }
477    }
478
479    /// Runs a slot query whose fields may be numbers as well as lexemes, and
480    /// renders each field as text.
481    fn query_any(
482        &self,
483        query: unsafe extern "C" fn(
484            *mut ffi::Defclass,
485            *const std::ffi::c_char,
486            *mut ffi::CLIPSValue,
487        ) -> bool,
488    ) -> Vec<String> {
489        let mut output = null_value();
490        if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
491            return Vec::new();
492        }
493        unsafe { printed_multifield(&output) }
494    }
495}
496
497fn null_value() -> ffi::CLIPSValue {
498    ffi::CLIPSValue {
499        value: std::ptr::null_mut(),
500    }
501}
502
503/// Renders every field of a multifield as text, including numeric fields, which
504/// slot ranges, cardinalities, and defaults use.
505/// Renders a CLIPS result as text fields. Single-valued results, which slot
506/// defaults use, become a one-element vector.
507unsafe fn printed_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
508    if unsafe { value.value.is_null() } {
509        return Vec::new();
510    }
511    if unsafe { (*value.header).type_ } != 4 {
512        return vec![unsafe { printed_field(value) }];
513    }
514    let multifield = unsafe { &*value.multifield };
515    (0..multifield.length)
516        .map(|index| unsafe { printed_field(&*multifield.contents.as_ptr().add(index)) })
517        .collect()
518}
519
520unsafe fn printed_field(cell: &ffi::CLIPSValue) -> String {
521    match unsafe { (*cell.header).type_ } {
522        0 => unsafe { (*cell.float).contents }.to_string(),
523        1 => unsafe { (*cell.integer).contents }.to_string(),
524        2 | 3 | 8 => unsafe { CStr::from_ptr((*cell.lexeme).contents) }
525            .to_string_lossy()
526            .into_owned(),
527        other => format!("<type {other}>"),
528    }
529}
530
531unsafe fn lexeme_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
532    if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
533        return Vec::new();
534    }
535    let multifield = unsafe { &*value.multifield };
536    (0..multifield.length)
537        .filter_map(|index| {
538            let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
539            let type_code = unsafe { (*cell.header).type_ };
540            matches!(type_code, 2 | 3 | 8).then(|| {
541                unsafe { CStr::from_ptr((*cell.lexeme).contents) }
542                    .to_string_lossy()
543                    .into_owned()
544            })
545        })
546        .collect()
547}