clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Saving and loading constructs, facts, and instances, in text and binary
//! form.
//!
//! CLIPS reports counts with negative sentinels for failure; those become
//! typed errors here.

use std::ffi::CString;

use crate::error::{Error, Result};
use crate::{Environment, ffi};

/// Selects which constructs are included when facts or instances are saved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum SaveScope {
    /// Only constructs defined in the current module.
    Local = 0,
    /// Everything visible from the current module, including imports.
    Visible = 1,
}

/// Identifies a persistence operation which CLIPS could not complete.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PersistenceError {
    /// Constructs could not be written as text, usually because the file could
    /// not be opened.
    SaveConstructs,
    /// Constructs could not be written as a binary image.
    BinarySaveConstructs,
    /// The file could not be read, or is not a CLIPS binary construct image.
    BinaryLoadConstructs,
    /// Facts could not be written as text.
    SaveFacts,
    /// The file could not be read, or does not contain loadable facts.
    LoadFacts,
    /// Facts could not be written as a binary image.
    BinarySaveFacts,
    /// The file could not be read, or is not a CLIPS binary facts image.
    BinaryLoadFacts,
    /// Instances could not be written as text.
    SaveInstances,
    /// The file could not be read, or does not contain loadable instances.
    LoadInstances,
    /// The file could not be read, or does not contain restorable instances.
    RestoreInstances,
    /// Instances could not be written as a binary image.
    BinarySaveInstances,
    /// The file could not be read, or is not a CLIPS binary instances image.
    BinaryLoadInstances,
}

fn count(result: std::ffi::c_long, operation: PersistenceError) -> Result<usize> {
    usize::try_from(result).map_err(|_| Error::Persistence(operation))
}

impl Environment {
    /// Saves all construct definitions as CLIPS source text.
    pub fn save_constructs(&self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { ffi::Save(self.raw.as_ptr(), path.as_ptr()) }
            .then_some(())
            .ok_or(Error::Persistence(PersistenceError::SaveConstructs))
    }

    /// Saves construct definitions in CLIPS' binary format.
    pub fn binary_save_constructs(&self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { ffi::Bsave(self.raw.as_ptr(), path.as_ptr()) }
            .then_some(())
            .ok_or(Error::Persistence(PersistenceError::BinarySaveConstructs))
    }

    /// Replaces the current construct set with a CLIPS binary image.
    pub fn binary_load_constructs(&mut self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { ffi::Bload(self.raw.as_ptr(), path.as_ptr()) }
            .then_some(())
            .ok_or(Error::Persistence(PersistenceError::BinaryLoadConstructs))
    }

    /// Whether a binary construct image is currently loaded.
    ///
    /// While it is, CLIPS refuses to define further constructs; clearing the
    /// environment releases the image.
    pub fn constructs_are_binary_loaded(&self) -> bool {
        unsafe { ffi::Bloaded(self.raw.as_ptr()) }
    }

    /// Writes facts as `assert` text, returning how many were saved.
    pub fn save_facts(&self, path: &str, scope: SaveScope) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::SaveFacts(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
            PersistenceError::SaveFacts,
        )
    }

    /// Asserts the facts in a file written by [`Environment::save_facts`],
    /// returning how many were loaded.
    ///
    /// The facts are added to whatever is already asserted; nothing is cleared
    /// first.
    pub fn load_facts(&mut self, path: &str) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::LoadFacts(self.raw.as_ptr(), path.as_ptr()) },
            PersistenceError::LoadFacts,
        )
    }

    /// Asserts facts from CLIPS text rather than a file.
    pub fn load_facts_str(&mut self, source: &str) -> Result<usize> {
        let source = CString::new(source)?;
        count(
            unsafe {
                ffi::LoadFactsFromString(
                    self.raw.as_ptr(),
                    source.as_ptr(),
                    source.as_bytes().len(),
                )
            },
            PersistenceError::LoadFacts,
        )
    }

    /// Writes facts in CLIPS's binary format, which loads faster than text but
    /// is not portable across CLIPS builds.
    pub fn binary_save_facts(&self, path: &str, scope: SaveScope) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::BinarySaveFacts(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
            PersistenceError::BinarySaveFacts,
        )
    }

    /// Asserts the facts in a binary file, returning how many were loaded.
    pub fn binary_load_facts(&mut self, path: &str) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::BinaryLoadFacts(self.raw.as_ptr(), path.as_ptr()) },
            PersistenceError::BinaryLoadFacts,
        )
    }

    /// Writes instances as `make-instance` text, returning how many were saved.
    pub fn save_instances(&self, path: &str, scope: SaveScope) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::SaveInstances(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
            PersistenceError::SaveInstances,
        )
    }

    /// Creates instances from a saved file through message passing, so
    /// `init-slots` and slot daemons run.
    ///
    /// Use [`Environment::restore_instances`] to bypass message passing.
    pub fn load_instances(&mut self, path: &str) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::LoadInstances(self.raw.as_ptr(), path.as_ptr()) },
            PersistenceError::LoadInstances,
        )
    }

    /// Creates instances from CLIPS text rather than a file, with message
    /// passing.
    pub fn load_instances_str(&mut self, source: &str) -> Result<usize> {
        let source = CString::new(source)?;
        count(
            unsafe {
                ffi::LoadInstancesFromString(
                    self.raw.as_ptr(),
                    source.as_ptr(),
                    source.as_bytes().len(),
                )
            },
            PersistenceError::LoadInstances,
        )
    }

    /// Creates instances from a saved file without message passing, so slots
    /// are written directly and no handler runs.
    ///
    /// This restores the saved state exactly, where
    /// [`Environment::load_instances`] would let handlers alter it.
    pub fn restore_instances(&mut self, path: &str) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::RestoreInstances(self.raw.as_ptr(), path.as_ptr()) },
            PersistenceError::RestoreInstances,
        )
    }

    /// Restores instances from CLIPS text rather than a file, without message
    /// passing.
    pub fn restore_instances_str(&mut self, source: &str) -> Result<usize> {
        let source = CString::new(source)?;
        count(
            unsafe {
                ffi::RestoreInstancesFromString(
                    self.raw.as_ptr(),
                    source.as_ptr(),
                    source.as_bytes().len(),
                )
            },
            PersistenceError::RestoreInstances,
        )
    }

    /// Writes instances in CLIPS's binary format.
    pub fn binary_save_instances(&self, path: &str, scope: SaveScope) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::BinarySaveInstances(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
            PersistenceError::BinarySaveInstances,
        )
    }

    /// Creates instances from a binary file, without message passing.
    pub fn binary_load_instances(&mut self, path: &str) -> Result<usize> {
        let path = CString::new(path)?;
        count(
            unsafe { ffi::BinaryLoadInstances(self.raw.as_ptr(), path.as_ptr()) },
            PersistenceError::BinaryLoadInstances,
        )
    }
}