clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Typed access to CLIPS watch and construct-loading diagnostics.

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

use crate::{Environment, ffi};

/// A built-in CLIPS watch category.
///
/// These discriminants match `WatchItem` in CLIPS 6.4.2's `watch.h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum WatchItem {
    /// Every category at once. This is CLIPS's shorthand rather than a
    /// category of its own, so [`Environment::watch_state`] treats it
    /// specially.
    All = 0,
    /// Fact assertions and retractions.
    Facts = 1,
    /// Instance creation and deletion.
    Instances = 2,
    /// Writes to instance slots.
    Slots = 3,
    /// Rule firings.
    Rules = 4,
    /// Activations added to and removed from the agenda.
    Activations = 5,
    /// Messages sent to instances.
    Messages = 6,
    /// Message handlers as they run.
    MessageHandlers = 7,
    /// Generic function calls.
    GenericFunctions = 8,
    /// Generic function methods as they run.
    Methods = 9,
    /// Deffunction calls.
    Deffunctions = 10,
    /// Constructs as they are compiled during loading.
    Compilations = 11,
    /// Per-run statistics such as rule firings and elapsed time.
    Statistics = 12,
    /// Changes to defglobal values.
    Globals = 13,
    /// Changes to the focus stack.
    Focus = 14,
}

impl WatchItem {
    /// Every individually watchable category, excluding [`WatchItem::All`],
    /// which is CLIPS's shorthand for the whole set rather than a category.
    pub const CATEGORIES: [Self; 14] = [
        Self::Facts,
        Self::Instances,
        Self::Slots,
        Self::Rules,
        Self::Activations,
        Self::Messages,
        Self::MessageHandlers,
        Self::GenericFunctions,
        Self::Methods,
        Self::Deffunctions,
        Self::Compilations,
        Self::Statistics,
        Self::Globals,
        Self::Focus,
    ];

    /// The category's CLIPS name, as the `watch` command spells it.
    pub const fn name(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Facts => "facts",
            Self::Instances => "instances",
            Self::Slots => "slots",
            Self::Rules => "rules",
            Self::Activations => "activations",
            Self::Messages => "messages",
            Self::MessageHandlers => "message-handlers",
            Self::GenericFunctions => "generic-functions",
            Self::Methods => "methods",
            Self::Deffunctions => "deffunctions",
            Self::Compilations => "compilations",
            Self::Statistics => "statistics",
            Self::Globals => "globals",
            Self::Focus => "focus",
        }
    }
}

/// Why a watch or dribble operation failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WatchError {
    /// The name or path contained a NUL byte.
    InteriorNul,
    /// CLIPS has no watch item registered under that name.
    UnknownItem(String),
}

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

impl std::fmt::Display for WatchError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InteriorNul => formatter.write_str("watch item name contains a NUL byte"),
            Self::UnknownItem(name) => write!(formatter, "unknown CLIPS watch item: {name}"),
        }
    }
}

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

impl Environment {
    /// Enables a built-in watch category.
    pub fn watch(&mut self, item: WatchItem) {
        unsafe { ffi::Watch(self.raw.as_ptr(), item as i32) }
    }

    /// Disables a built-in watch category.
    pub fn unwatch(&mut self, item: WatchItem) {
        unsafe { ffi::Unwatch(self.raw.as_ptr(), item as i32) }
    }

    /// Returns the global state of a built-in watch category.
    pub fn watch_state(&self, item: WatchItem) -> bool {
        if item == WatchItem::All {
            // CLIPS's GetWatchState(ALL) always returns false; GetWatchItem
            // implements the useful "are all categories enabled?" query.
            unsafe { ffi::GetWatchItem(self.raw.as_ptr(), c"all".as_ptr()) == 1 }
        } else {
            unsafe { ffi::GetWatchState(self.raw.as_ptr(), item as i32) }
        }
    }

    /// Changes the global state of a built-in watch category.
    pub fn set_watch_state(&mut self, item: WatchItem, enabled: bool) {
        unsafe { ffi::SetWatchState(self.raw.as_ptr(), item as i32, enabled) }
    }

    /// Every built-in watch category paired with its current state.
    pub fn watch_states(&self) -> Vec<(WatchItem, bool)> {
        WatchItem::CATEGORIES
            .into_iter()
            .map(|item| (item, self.watch_state(item)))
            .collect()
    }

    /// Enables a watch item by its registered CLIPS name.
    ///
    /// This also supports watch items registered by CLIPS extensions.
    pub fn watch_named(&mut self, name: &str) -> Result<(), WatchError> {
        self.set_named_watch(name, true)
    }

    /// Disables a watch item by its registered CLIPS name.
    pub fn unwatch_named(&mut self, name: &str) -> Result<(), WatchError> {
        self.set_named_watch(name, false)
    }

    /// Returns the state of a watch item registered under `name`.
    pub fn named_watch_state(&self, name: &str) -> Result<bool, WatchError> {
        let name_c = CString::new(name)?;
        match unsafe { ffi::GetWatchItem(self.raw.as_ptr(), name_c.as_ptr()) } {
            0 => Ok(false),
            1 => Ok(true),
            _ => Err(WatchError::UnknownItem(name.to_owned())),
        }
    }

    fn set_named_watch(&mut self, name: &str, enabled: bool) -> Result<(), WatchError> {
        let name_c = CString::new(name)?;
        let changed = unsafe {
            if enabled {
                ffi::WatchString(self.raw.as_ptr(), name_c.as_ptr())
            } else {
                ffi::UnwatchString(self.raw.as_ptr(), name_c.as_ptr())
            }
        };
        changed
            .then_some(())
            .ok_or_else(|| WatchError::UnknownItem(name.to_owned()))
    }

    /// Whether construct compilations are currently traced.
    pub fn compilations_watch(&self) -> bool {
        unsafe { ffi::GetCompilationsWatch(self.raw.as_ptr()) }
    }

    /// Enables or disables tracing of construct compilation.
    pub fn set_compilations_watch(&mut self, enabled: bool) {
        unsafe { ffi::SetCompilationsWatch(self.raw.as_ptr(), enabled) }
    }

    /// Whether constructs are printed as they are loaded.
    pub fn print_while_loading(&self) -> bool {
        unsafe { ffi::GetPrintWhileLoading(self.raw.as_ptr()) }
    }

    /// Enables or disables echoing constructs as they load.
    pub fn set_print_while_loading(&mut self, enabled: bool) {
        unsafe { ffi::SetPrintWhileLoading(self.raw.as_ptr(), enabled) }
    }

    /// Whether CLIPS currently considers a load operation in progress.
    pub fn load_in_progress(&self) -> bool {
        unsafe { ffi::GetLoadInProgress(self.raw.as_ptr()) }
    }

    /// Sets the load-in-progress flag, which changes how CLIPS reports parse
    /// errors. Setting it by hand is rarely correct.
    pub fn set_load_in_progress(&mut self, in_progress: bool) {
        unsafe { ffi::SetLoadInProgress(self.raw.as_ptr(), in_progress) }
    }

    /// Whether CLIPS is currently executing a construct.
    pub fn executing_construct(&self) -> bool {
        unsafe { ffi::ExecutingConstruct(self.raw.as_ptr()) }
    }

    /// Sets the executing-construct flag. Setting it by hand is rarely
    /// correct; CLIPS maintains it during execution.
    pub fn set_executing_construct(&mut self, executing: bool) {
        unsafe { ffi::SetExecutingConstruct(self.raw.as_ptr(), executing) }
    }

    /// Bytes CLIPS currently has allocated.
    pub fn memory_used(&self) -> i64 {
        unsafe { ffi::MemUsed(self.raw.as_ptr()) }
    }

    /// Allocation requests CLIPS has made since the environment was created.
    pub fn memory_requests(&self) -> i64 {
        unsafe { ffi::MemRequests(self.raw.as_ptr()) }
    }

    /// Frees pooled memory, returning the number of bytes released. A negative
    /// `amount` releases everything CLIPS can.
    pub fn release_memory(&mut self, amount: i64) -> i64 {
        unsafe { ffi::ReleaseMem(self.raw.as_ptr(), amount) }
    }

    /// Whether CLIPS returns freed memory immediately instead of pooling it.
    pub fn conserve_memory(&self) -> bool {
        unsafe { ffi::GetConserveMemory(self.raw.as_ptr()) }
    }

    /// Sets the conserve-memory behaviour and returns the previous value.
    pub fn set_conserve_memory(&mut self, enabled: bool) -> bool {
        unsafe { ffi::SetConserveMemory(self.raw.as_ptr(), enabled) }
    }

    /// The percentage below which profiled constructs are omitted from reports.
    ///
    /// CLIPS exposes profile collection and reporting only as its `profile` and
    /// `profile-info` commands; run them with [`Environment::eval`] and capture
    /// the report with a [`crate::Router`].
    pub fn profile_percent_threshold(&self) -> f64 {
        unsafe { ffi::GetProfilePercentThreshold(self.raw.as_ptr()) }
    }

    /// Sets the profile reporting threshold and returns the previous value.
    pub fn set_profile_percent_threshold(&mut self, threshold: f64) -> f64 {
        unsafe { ffi::SetProfilePercentThreshold(self.raw.as_ptr(), threshold) }
    }

    /// Starts copying router output to `path`.
    ///
    /// Returns `false` if CLIPS could not open the file or dribbling is already
    /// active.
    pub fn dribble_on(&mut self, path: &str) -> Result<bool, WatchError> {
        let path = CString::new(path)?;
        Ok(unsafe { ffi::DribbleOn(self.raw.as_ptr(), path.as_ptr()) })
    }

    /// Whether router output is currently being copied to a dribble file.
    pub fn dribble_active(&self) -> bool {
        unsafe { ffi::DribbleActive(self.raw.as_ptr()) }
    }

    /// Stops dribbling and closes the file. Returns `false` when no dribble
    /// file was open.
    pub fn dribble_off(&mut self) -> bool {
        unsafe { ffi::DribbleOff(self.raw.as_ptr()) }
    }

    /// Starts dribbling to `path` and stops it again when the guard is dropped.
    pub fn dribble_to(&mut self, path: &str) -> Result<Option<Dribble<'_>>, WatchError> {
        if !self.dribble_on(path)? {
            return Ok(None);
        }
        Ok(Some(Dribble { environment: self }))
    }

    /// Whether periodic hooks run during execution.
    ///
    /// Returns the previous setting.
    pub fn set_periodic_functions_enabled(&mut self, enabled: bool) -> bool {
        unsafe { ffi::EnablePeriodicFunctions(self.raw.as_ptr(), enabled) }
    }

    /// Whether CLIPS calls its yield-time function during execution.
    ///
    /// Returns the previous setting. The function itself cannot be installed
    /// from Rust: CLIPS 6.4.2 keeps it in a private struct field with no public
    /// setter, so only the enable flag is bound.
    pub fn set_yield_function_enabled(&mut self, enabled: bool) -> bool {
        unsafe { ffi::EnableYieldFunction(self.raw.as_ptr(), enabled) }
    }
}

/// Stops dribbling when dropped.
pub struct Dribble<'env> {
    environment: &'env mut Environment,
}

impl Drop for Dribble<'_> {
    fn drop(&mut self) {
        self.environment.dribble_off();
    }
}