clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Defgenerics, their methods, and defglobal values.

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

use crate::construct::Defgeneric;
use crate::{Environment, Result, Value, ffi};

/// A method belonging to a [`Defgeneric`].
pub struct Defmethod<'env> {
    generic: NonNull<ffi::Defgeneric>,
    index: u16,
    marker: PhantomData<&'env Environment>,
}

impl Defmethod<'_> {
    /// The method's index within its generic function, which is how CLIPS
    /// identifies it for undefinition.
    pub fn index(&self) -> u16 {
        self.index
    }

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

    /// The method's source text as CLIPS reformats it, or `None` when no
    /// pretty-print form is stored.
    pub fn pretty_print(&self) -> Option<&str> {
        let value = unsafe { ffi::DefmethodPPForm(self.generic.as_ptr(), self.index) };
        if value.is_null() {
            None
        } else {
            unsafe { CStr::from_ptr(value) }.to_str().ok()
        }
    }

    /// Whether CLIPS traces this method as it runs.
    pub fn watched(&self) -> bool {
        unsafe { ffi::DefmethodGetWatch(self.generic.as_ptr(), self.index) }
    }

    /// Enables or disables tracing of this method.
    pub fn set_watched(&mut self, enabled: bool) {
        unsafe { ffi::DefmethodSetWatch(self.generic.as_ptr(), self.index, enabled) }
    }

    /// The method's arity and per-parameter restrictions in structured form.
    ///
    /// CLIPS returns this as a flat multifield whose layout is documented in
    /// `genrccom.c`: minimum arity, maximum arity, restriction count, one index
    /// per restriction, then each restriction as a query flag, a class count,
    /// and that many class names. Returns `None` if CLIPS reports a layout this
    /// parser does not recognise.
    pub fn restrictions(&self) -> Option<MethodRestrictions> {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        // The multifield is read before returning to CLIPS, so it does not need
        // to be retained.
        unsafe { ffi::GetMethodRestrictions(self.generic.as_ptr(), self.index, &mut raw) };
        let fields = unsafe { flatten(&raw) };

        let integer = |index: usize| match fields.get(index) {
            Some(Field::Integer(value)) => Some(*value),
            _ => None,
        };
        let min_arguments = integer(0)?;
        let max_arguments = integer(1)?;
        let count = usize::try_from(integer(2)?).ok()?;

        let mut parameters = Vec::with_capacity(count);
        for slot in 0..count {
            // The index table is one-based over the whole multifield.
            let start = usize::try_from(integer(3 + slot)?).ok()?.checked_sub(1)?;
            let has_query =
                matches!(fields.get(start), Some(Field::Lexeme(text)) if text == "TRUE");
            let classes = usize::try_from(integer(start + 1)?).ok()?;
            let allowed_classes = (0..classes)
                .map(|offset| match fields.get(start + 2 + offset) {
                    Some(Field::Lexeme(name)) => Some(name.clone()),
                    _ => None,
                })
                .collect::<Option<Vec<_>>>()?;
            parameters.push(ParameterRestriction {
                has_query,
                allowed_classes,
            });
        }

        Some(MethodRestrictions {
            min_arguments,
            // CLIPS reports -1 for a wildcard parameter.
            max_arguments: (max_arguments >= 0).then_some(max_arguments),
            parameters,
        })
    }
}

/// A method's arity and parameter restrictions.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MethodRestrictions {
    /// The number of arguments the method requires.
    pub min_arguments: i64,
    /// `None` when the method accepts a wildcard number of arguments.
    pub max_arguments: Option<i64>,
    /// One entry per restricted parameter, in order.
    pub parameters: Vec<ParameterRestriction>,
}

/// The restrictions on one method parameter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterRestriction {
    /// Whether the parameter has a query expression, for example `(= 1 1)`.
    pub has_query: bool,
    /// The classes the argument must belong to, empty when unrestricted.
    pub allowed_classes: Vec<String>,
}

/// One decoded field of a CLIPS multifield.
enum Field {
    Integer(i64),
    Lexeme(String),
    Other,
}

unsafe fn flatten(value: &ffi::CLIPSValue) -> Vec<Field> {
    if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
        return Vec::new();
    }
    let multifield = unsafe { &*value.multifield };
    (0..multifield.length)
        .map(|index| {
            let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
            match unsafe { (*cell.header).type_ } {
                1 => Field::Integer(unsafe { (*cell.integer).contents }),
                2 | 3 | 8 => Field::Lexeme(
                    unsafe { CStr::from_ptr((*cell.lexeme).contents) }
                        .to_string_lossy()
                        .into_owned(),
                ),
                _ => Field::Other,
            }
        })
        .collect()
}

/// Iterates a generic function's methods in index order.
pub struct Defmethods<'env> {
    generic: NonNull<ffi::Defgeneric>,
    current: u16,
    marker: PhantomData<&'env Environment>,
}

impl<'env> Iterator for Defmethods<'env> {
    type Item = Defmethod<'env>;

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

impl<'env> Defgeneric<'env> {
    /// Iterates this generic function's methods.
    pub fn methods(&self) -> Defmethods<'env> {
        Defmethods {
            generic: self.raw,
            current: 0,
            marker: PhantomData,
        }
    }

    /// One method by index, or `None` if the generic has no such method.
    /// Index 0 is never valid.
    pub fn method(&self, index: u16) -> Option<Defmethod<'env>> {
        (index != 0
            && unsafe { !ffi::GetDefmethodPointer(self.raw.as_ptr(), index.into()).is_null() })
        .then_some(Defmethod {
            generic: self.raw,
            index,
            marker: PhantomData,
        })
    }
}

impl Environment {
    /// 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.
    pub fn undefine_defmethod(&mut self, generic: &str, index: u16) -> Result<bool> {
        if index == 0 {
            return Ok(false);
        }
        let generic = CString::new(generic)?;
        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
        Ok(!generic.is_null() && unsafe { ffi::Undefmethod(generic, index, self.raw.as_ptr()) })
    }

    /// 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.
    pub fn defmethod_restrictions(&self, generic: &str, index: u16) -> Result<Option<Value<'_>>> {
        let generic = CString::new(generic)?;
        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
        if generic.is_null()
            || index == 0
            || unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
        {
            return Ok(None);
        }
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe {
            ffi::GetMethodRestrictions(generic, index, &mut raw);
            ffi::RetainCV(self.raw.as_ptr(), &mut raw);
        }
        Ok(Some(Value::new(self, raw)))
    }

    /// CLIPS's own textual summary of a method's parameter restrictions.
    ///
    /// `None` when the generic or method does not exist.
    pub fn defmethod_description(&self, generic: &str, index: u16) -> Result<Option<String>> {
        let generic = CString::new(generic)?;
        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
        if generic.is_null()
            || index == 0
            || unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
        {
            return Ok(None);
        }
        let builder = unsafe { ffi::CreateStringBuilder(self.raw.as_ptr(), 128) };
        if builder.is_null() {
            return Ok(None);
        }
        unsafe { ffi::DefmethodDescription(generic, index, builder) };
        let description = unsafe { CStr::from_ptr((*builder).contents) }
            .to_string_lossy()
            .into_owned();
        unsafe { ffi::SBDispose(builder) };
        Ok(Some(description))
    }

    /// A defglobal's current value, retained. `None` if no such global exists.
    ///
    /// The name is given without the `?*` decoration, so `?*count*` is
    /// `"count"`.
    pub fn defglobal_value(&self, name: &str) -> Result<Option<Value<'_>>> {
        let name = CString::new(name)?;
        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
        if global.is_null() {
            return Ok(None);
        }
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe {
            ffi::DefglobalGetValue(global, &mut raw);
            ffi::RetainCV(self.raw.as_ptr(), &mut raw);
        }
        Ok(Some(Value::new(self, raw)))
    }

    /// Sets a defglobal to an integer, returning whether the global exists.
    pub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool> {
        let name = CString::new(name)?;
        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
        if global.is_null() {
            return Ok(false);
        }
        unsafe { ffi::DefglobalSetInteger(global, value) };
        Ok(true)
    }

    /// Sets a defglobal to a float, returning whether the global exists.
    pub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool> {
        let name = CString::new(name)?;
        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
        if global.is_null() {
            return Ok(false);
        }
        unsafe { ffi::DefglobalSetFloat(global, value) };
        Ok(true)
    }

    /// Sets a defglobal to a symbol, returning whether the global exists.
    pub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool> {
        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetSymbol)
    }

    /// Sets a defglobal to a string, returning whether the global exists.
    pub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool> {
        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetString)
    }

    /// Sets a defglobal to an instance name, returning whether the global
    /// exists.
    pub fn set_defglobal_instance_name(&mut self, name: &str, value: &str) -> Result<bool> {
        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetInstanceName)
    }

    /// 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.
    pub fn set_defglobal_value(&self, name: &str, value: &Value<'_>) -> Result<bool> {
        let mut raw = self.check_value(value)?;
        let name = CString::new(name)?;
        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
        if global.is_null() {
            return Ok(false);
        }
        unsafe { ffi::DefglobalSetValue(global, &mut raw) };
        Ok(true)
    }

    /// Whether `reset` restores defglobals to their initial values.
    pub fn reset_globals(&self) -> bool {
        unsafe { ffi::GetResetGlobals(self.raw.as_ptr()) }
    }

    /// Sets the reset behaviour for defglobals and returns the previous value.
    pub fn set_reset_globals(&mut self, enabled: bool) -> bool {
        unsafe { ffi::SetResetGlobals(self.raw.as_ptr(), enabled) }
    }

    /// Whether any defglobal changed since this flag was last cleared.
    pub fn globals_changed(&self) -> bool {
        unsafe { ffi::GetGlobalsChanged(self.raw.as_ptr()) }
    }

    /// Sets or clears the globals-changed flag.
    pub fn set_globals_changed(&self, changed: bool) {
        unsafe { ffi::SetGlobalsChanged(self.raw.as_ptr(), changed) }
    }

    fn set_defglobal_lexeme(
        &mut self,
        name: &str,
        value: &str,
        setter: unsafe extern "C" fn(*mut ffi::Defglobal, *const std::ffi::c_char),
    ) -> Result<bool> {
        let name = CString::new(name)?;
        let value = CString::new(value)?;
        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
        if global.is_null() {
            return Ok(false);
        }
        unsafe { setter(global, value.as_ptr()) };
        Ok(true)
    }
}