clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Defmodule selection and rule-engine focus stack operations.

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

use crate::{Defmodule, Environment, ffi};

/// Why a module operation failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ModuleError {
    /// The module name contained a NUL byte.
    InteriorNul,
    /// No defmodule of that name exists.
    NotFound(String),
}

impl std::fmt::Display for ModuleError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InteriorNul => formatter.write_str("module name contains a NUL byte"),
            Self::NotFound(name) => write!(formatter, "defmodule {name:?} was not found"),
        }
    }
}

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

/// A snapshot of an entry in the focus stack.
///
/// The name is owned because the underlying `FocalModule` node is destroyed by
/// `PopFocus` and `ClearFocusStack`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FocusEntry<'env> {
    name: String,
    marker: PhantomData<&'env Environment>,
}

impl FocusEntry<'_> {
    /// The name of the module at this position in the focus stack.
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// Immutable traversal of the environment's focus stack, from top to bottom.
pub struct FocusStack<'env> {
    environment: &'env Environment,
    current: *mut ffi::FocalModule,
}

impl<'env> Iterator for FocusStack<'env> {
    type Item = FocusEntry<'env>;

    fn next(&mut self) -> Option<Self::Item> {
        self.current = unsafe { ffi::GetNextFocus(self.environment.raw.as_ptr(), self.current) };
        NonNull::new(self.current).map(|current| {
            let name = unsafe { CStr::from_ptr(ffi::FocalModuleName(current.as_ptr())) }
                .to_string_lossy()
                .into_owned();
            FocusEntry {
                name,
                marker: PhantomData,
            }
        })
    }
}

impl Environment {
    /// Returns the module used for unqualified construct lookup and definition.
    pub fn current_module(&self) -> Defmodule<'_> {
        let raw = unsafe { ffi::GetCurrentModule(self.raw.as_ptr()) };
        // Every initialized CLIPS environment has a current module (MAIN).
        Defmodule::from_raw(
            self,
            NonNull::new(raw).expect("CLIPS returned no current module"),
        )
    }

    /// Sets the current module and returns the previous one.
    ///
    /// This accepts a name rather than a `Defmodule` handle so a handle from a
    /// different environment can never be passed to CLIPS.
    pub fn set_current_module(&mut self, name: &str) -> Result<Defmodule<'_>, ModuleError> {
        let c_name = CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
        let module = NonNull::new(module).ok_or_else(|| ModuleError::NotFound(name.to_owned()))?;
        let previous = unsafe { ffi::SetCurrentModule(self.raw.as_ptr(), module.as_ptr()) };
        Ok(Defmodule::from_raw(
            self,
            NonNull::new(previous).expect("CLIPS returned no previous current module"),
        ))
    }

    /// The number of defmodules, which is at least one because CLIPS always
    /// has `MAIN`.
    pub fn module_count(&self) -> usize {
        unsafe { ffi::GetNumberOfDefmodules(self.raw.as_ptr()) as usize }
    }

    /// Pushes a module onto the rule-engine focus stack.
    pub fn focus(&mut self, name: &str) -> Result<(), ModuleError> {
        let c_name = CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
        let module = NonNull::new(module).ok_or_else(|| ModuleError::NotFound(name.to_owned()))?;
        unsafe { ffi::Focus(module.as_ptr()) };
        Ok(())
    }

    /// Pops the top focus and returns its module, or `None` for an empty stack.
    pub fn pop_focus(&mut self) -> Option<Defmodule<'_>> {
        NonNull::new(unsafe { ffi::PopFocus(self.raw.as_ptr()) })
            .map(|raw| Defmodule::from_raw(self, raw))
    }

    /// The module the rule engine is currently focused on, or `None` when the
    /// focus stack is empty.
    pub fn current_focus(&self) -> Option<Defmodule<'_>> {
        NonNull::new(unsafe { ffi::GetFocus(self.raw.as_ptr()) })
            .map(|raw| Defmodule::from_raw(self, raw))
    }

    /// Whether the focus stack changed since this flag was last cleared.
    pub fn focus_changed(&self) -> bool {
        unsafe { ffi::GetFocusChanged(self.raw.as_ptr()) }
    }

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

    /// The names of every defmodule, in definition order.
    ///
    /// CLIPS returns this as a multifield of symbols; the names are copied so
    /// the result stays valid across later construct changes.
    pub fn module_names(&self) -> Vec<String> {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe { ffi::GetDefmoduleList(self.raw.as_ptr(), &mut raw) };
        let names = crate::Multifield::from_value(crate::Value::retaining(self, raw));
        names
            .iter()
            .filter_map(|name| name.as_str().map(str::to_owned))
            .collect()
    }

    /// Iterates the focus stack from the module in focus downwards.
    pub fn focus_stack(&self) -> FocusStack<'_> {
        FocusStack {
            environment: self,
            current: std::ptr::null_mut(),
        }
    }
}