clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Deftemplate slot metadata and constraint inspection.

use std::ffi::{CString, NulError};

use crate::{Deftemplate, Multifield, Value, ffi};

/// What kind of default value a slot has.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotDefaultType {
    /// No default: the slot must be given a value, as with `(default ?NONE)`.
    None,
    /// A fixed value, evaluated once when the construct is defined.
    Static,
    /// An expression re-evaluated for each new fact or instance, as with
    /// `(default-dynamic ...)`.
    Dynamic,
}

/// Why a deftemplate slot query failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TemplateError {
    /// The slot name contained a NUL byte.
    InteriorNul,
    /// The template has no slot of that name.
    SlotNotFound(String),
    /// CLIPS reported failure for this query on this slot.
    QueryFailed {
        /// The slot queried.
        slot: String,
        /// The CLIPS query that failed, for example `allowed-values`.
        query: &'static str,
    },
    /// CLIPS returned a value of an unexpected type for the query, which means
    /// this crate's declaration disagrees with CLIPS.
    UnexpectedResult {
        /// The CLIPS query whose result could not be interpreted.
        query: &'static str,
    },
}

impl From<NulError> for TemplateError {
    fn from(_: NulError) -> Self {
        Self::InteriorNul
    }
}

impl std::fmt::Display for TemplateError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InteriorNul => formatter.write_str("slot name contains a NUL byte"),
            Self::SlotNotFound(slot) => write!(formatter, "deftemplate slot not found: {slot}"),
            Self::QueryFailed { slot, query } => {
                write!(
                    formatter,
                    "deftemplate {query} query failed for slot {slot}"
                )
            }
            Self::UnexpectedResult { query } => {
                write!(
                    formatter,
                    "deftemplate {query} returned an unexpected value"
                )
            }
        }
    }
}

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

/// A named slot borrowed from a deftemplate.
pub struct TemplateSlot<'template, 'env> {
    template: &'template Deftemplate<'env>,
    name: CString,
}

impl<'env> Deftemplate<'env> {
    /// Returns all slot names in definition order.
    ///
    /// For an implied deftemplate, CLIPS returns its synthetic `implied` slot.
    pub fn slot_names(&self) -> Result<Vec<String>, TemplateError> {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe { ffi::DeftemplateSlotNames(self.raw.as_ptr(), &mut raw) };
        let value = self.retain_value(raw);
        let multifield = value
            .as_multifield()
            .ok_or(TemplateError::UnexpectedResult {
                query: "slot names",
            })?;
        multifield
            .iter()
            .map(|item| {
                item.as_str()
                    .map(str::to_owned)
                    .ok_or(TemplateError::UnexpectedResult {
                        query: "slot names",
                    })
            })
            .collect()
    }

    /// Iterates the template's slots in declaration order.
    pub fn slots(&self) -> Result<impl Iterator<Item = TemplateSlot<'_, 'env>>, TemplateError> {
        Ok(self.slot_names()?.into_iter().map(|name| TemplateSlot {
            template: self,
            name: CString::new(name).expect("CLIPS slot name contains no NUL"),
        }))
    }

    /// Whether the template declares a slot of this name.
    pub fn has_slot(&self, name: &str) -> Result<bool, TemplateError> {
        let name = CString::new(name)?;
        Ok(unsafe { ffi::DeftemplateSlotExistP(self.raw.as_ptr(), name.as_ptr()) })
    }

    /// A handle to one slot's metadata, or `None` if no such slot exists.
    pub fn slot(&self, name: &str) -> Result<Option<TemplateSlot<'_, 'env>>, TemplateError> {
        let name_c = CString::new(name)?;
        Ok(
            unsafe { ffi::DeftemplateSlotExistP(self.raw.as_ptr(), name_c.as_ptr()) }.then_some(
                TemplateSlot {
                    template: self,
                    name: name_c,
                },
            ),
        )
    }

    fn retain_value(&self, mut raw: ffi::CLIPSValue) -> Value<'env> {
        unsafe { ffi::RetainCV(self._environment.raw.as_ptr(), &mut raw) };
        Value::from_retained_raw(self._environment, raw)
    }
}

impl<'env> TemplateSlot<'_, 'env> {
    /// The slot's name.
    pub fn name(&self) -> &str {
        self.name.to_str().expect("validated deftemplate slot name")
    }

    /// Whether the slot holds a multifield, that is, was declared `multislot`.
    pub fn is_multislot(&self) -> bool {
        unsafe { ffi::DeftemplateSlotMultiP(self.template.raw.as_ptr(), self.name_ptr()) }
    }

    /// Whether the slot holds a single value, that is, was declared `slot`.
    pub fn is_single_slot(&self) -> bool {
        unsafe { ffi::DeftemplateSlotSingleP(self.template.raw.as_ptr(), self.name_ptr()) }
    }

    /// What kind of default the slot declares.
    pub fn default_type(&self) -> SlotDefaultType {
        match unsafe { ffi::DeftemplateSlotDefaultP(self.template.raw.as_ptr(), self.name_ptr()) } {
            1 => SlotDefaultType::Static,
            2 => SlotDefaultType::Dynamic,
            _ => SlotDefaultType::None,
        }
    }

    /// The slot's default value.
    ///
    /// For a dynamic default this is the result of evaluating the expression
    /// now, not the expression itself.
    pub fn default_value(&self) -> Result<Value<'env>, TemplateError> {
        self.value_query("default value", ffi::DeftemplateSlotDefaultValue)
    }

    /// The type names the slot accepts, as symbols such as `INTEGER`.
    pub fn allowed_types(&self) -> Result<Multifield<'env>, TemplateError> {
        self.multifield_query("allowed types", ffi::DeftemplateSlotTypes)
    }

    /// The values the slot is restricted to, empty when unrestricted.
    pub fn allowed_values(&self) -> Result<Multifield<'env>, TemplateError> {
        self.multifield_query("allowed values", ffi::DeftemplateSlotAllowedValues)
    }

    /// The numeric range as a two-field multifield of minimum and maximum.
    pub fn range(&self) -> Result<Multifield<'env>, TemplateError> {
        self.multifield_query("range", ffi::DeftemplateSlotRange)
    }

    /// A multislot's permitted length, as a two-field multifield of minimum and
    /// maximum.
    pub fn cardinality(&self) -> Result<Multifield<'env>, TemplateError> {
        self.multifield_query("cardinality", ffi::DeftemplateSlotCardinality)
    }

    fn name_ptr(&self) -> *const std::ffi::c_char {
        self.name.as_ptr()
    }

    fn value_query(
        &self,
        query: &'static str,
        function: unsafe extern "C" fn(
            *mut ffi::Deftemplate,
            *const std::ffi::c_char,
            *mut ffi::CLIPSValue,
        ) -> bool,
    ) -> Result<Value<'env>, TemplateError> {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        if !unsafe { function(self.template.raw.as_ptr(), self.name.as_ptr(), &mut raw) } {
            return Err(TemplateError::QueryFailed {
                slot: self.name().to_owned(),
                query,
            });
        }
        Ok(self.template.retain_value(raw))
    }

    fn multifield_query(
        &self,
        query: &'static str,
        function: unsafe extern "C" fn(
            *mut ffi::Deftemplate,
            *const std::ffi::c_char,
            *mut ffi::CLIPSValue,
        ) -> bool,
    ) -> Result<Multifield<'env>, TemplateError> {
        self.value_query(query, function)?
            .as_multifield()
            .ok_or(TemplateError::UnexpectedResult { query })
    }
}