clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Agenda inspection and control.
//!
//! Activations borrow the environment, so the agenda cannot be reordered or
//! emptied while one is held.

use std::ffi::CStr;
use std::marker::PhantomData;
use std::ptr::NonNull;

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

/// When CLIPS evaluates a rule's salience expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum SalienceEvaluation {
    /// Once, when the rule is defined.
    WhenDefined = 0,
    /// Each time the rule is activated.
    WhenActivated = 1,
    /// Before every rule firing, re-sorting the agenda each cycle.
    EveryCycle = 2,
}

/// How CLIPS orders activations of equal salience on the agenda.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Strategy {
    /// Newest activation first.
    Depth = 0,
    /// Oldest activation first.
    Breadth = 1,
    /// Ordered by the recency of the matched facts, as in OPS5 `lex`.
    Lex = 2,
    /// Like `Lex`, but dominated by the first pattern's recency.
    Mea = 3,
    /// Most specific rule, by number of comparisons, first.
    Complexity = 4,
    /// Least specific rule first.
    Simplicity = 5,
    /// Arbitrary but stable order.
    Random = 6,
}

/// A rule activation on the agenda.
pub struct Activation<'env> {
    raw: NonNull<ffi::Activation>,
    environment: &'env Environment,
}
impl Activation<'_> {
    /// The name of the rule this activation would fire.
    pub fn rule_name(&self) -> &str {
        unsafe { CStr::from_ptr(ffi::ActivationRuleName(self.raw.as_ptr())) }
            .to_str()
            .unwrap_or("")
    }

    /// The activation's salience, which decides its place on the agenda.
    pub fn salience(&self) -> i32 {
        unsafe { ffi::ActivationGetSalience(self.raw.as_ptr()) }
    }

    /// Sets this activation's salience and returns the previous value.
    ///
    /// The value is clamped to CLIPS's range of -10000 to 10000. The agenda is
    /// not re-sorted until [`Environment::reorder_agendas`] runs.
    pub fn set_salience(&mut self, salience: i32) -> i32 {
        unsafe { ffi::ActivationSetSalience(self.raw.as_ptr(), salience.clamp(-10_000, 10_000)) }
    }

    /// Moves this activation to the top of its salience group, so it fires
    /// next. Returns whether CLIPS moved it.
    pub fn move_to_top(&mut self) -> bool {
        unsafe { ffi::MoveActivationToTop(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
    }

    /// The activation rendered as CLIPS prints it on the agenda, with its
    /// salience, rule name, and matched facts.
    pub fn pretty_print(&self) -> String {
        unsafe {
            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
            if builder.is_null() {
                return String::new();
            }
            ffi::ActivationPPForm(self.raw.as_ptr(), builder);
            let output = CStr::from_ptr((*builder).contents)
                .to_string_lossy()
                .into_owned();
            ffi::SBDispose(builder);
            output
        }
    }
    /// Removes this activation from the agenda so it never fires.
    ///
    /// Consumes the handle, since CLIPS frees the activation.
    pub fn delete(self) {
        unsafe { ffi::DeleteActivation(self.raw.as_ptr()) }
    }
}

/// Iterates the agenda of the module in focus, highest priority first.
pub struct Activations<'env> {
    environment: &'env Environment,
    current: *mut ffi::Activation,
    marker: PhantomData<&'env Environment>,
}
impl<'env> Iterator for Activations<'env> {
    type Item = Activation<'env>;
    fn next(&mut self) -> Option<Self::Item> {
        self.current =
            unsafe { ffi::GetNextActivation(self.environment.raw.as_ptr(), self.current) };
        NonNull::new(self.current).map(|raw| Activation {
            raw,
            environment: self.environment,
        })
    }
}

impl Environment {
    /// Iterates the agenda in firing order.
    pub fn activations(&self) -> Activations<'_> {
        Activations {
            environment: self,
            current: std::ptr::null_mut(),
            marker: PhantomData,
        }
    }

    /// The number of activations on the agenda.
    pub fn activation_count(&self) -> usize {
        unsafe { ffi::GetNumberOfActivations(self.raw.as_ptr()) as usize }
    }

    /// The current conflict-resolution strategy.
    pub fn strategy(&self) -> Strategy {
        match unsafe { ffi::GetStrategy(self.raw.as_ptr()) } {
            0 => Strategy::Depth,
            1 => Strategy::Breadth,
            2 => Strategy::Lex,
            3 => Strategy::Mea,
            4 => Strategy::Complexity,
            5 => Strategy::Simplicity,
            _ => Strategy::Random,
        }
    }
    /// Sets the conflict-resolution strategy and returns the previous one.
    ///
    /// CLIPS reorders every agenda to match.
    pub fn set_strategy(&mut self, strategy: Strategy) -> Strategy {
        let previous = unsafe { ffi::SetStrategy(self.raw.as_ptr(), strategy as u32) };
        match previous {
            0 => Strategy::Depth,
            1 => Strategy::Breadth,
            2 => Strategy::Lex,
            3 => Strategy::Mea,
            4 => Strategy::Complexity,
            5 => Strategy::Simplicity,
            _ => Strategy::Random,
        }
    }
    /// When rule saliences are evaluated.
    pub fn salience_evaluation(&self) -> SalienceEvaluation {
        match unsafe { ffi::GetSalienceEvaluation(self.raw.as_ptr()) } {
            0 => SalienceEvaluation::WhenDefined,
            1 => SalienceEvaluation::WhenActivated,
            _ => SalienceEvaluation::EveryCycle,
        }
    }
    /// Sets when saliences are evaluated and returns the previous setting.
    pub fn set_salience_evaluation(&mut self, value: SalienceEvaluation) -> SalienceEvaluation {
        match unsafe { ffi::SetSalienceEvaluation(self.raw.as_ptr(), value as u32) } {
            0 => SalienceEvaluation::WhenDefined,
            1 => SalienceEvaluation::WhenActivated,
            _ => SalienceEvaluation::EveryCycle,
        }
    }
    /// Re-adds every module's satisfied matches to its agenda, so matches that
    /// already fired can fire again.
    pub fn refresh_agendas(&mut self) {
        unsafe { ffi::RefreshAllAgendas(self.raw.as_ptr()) }
    }

    /// Re-sorts every agenda, which is needed after changing saliences.
    pub fn reorder_agendas(&mut self) {
        unsafe { ffi::ReorderAllAgendas(self.raw.as_ptr()) }
    }
    /// Removes every activation from every agenda.
    pub fn remove_all_activations(&mut self) {
        unsafe { ffi::RemoveAllActivations(self.raw.as_ptr()) }
    }
    /// Whether the agenda changed since this flag was last cleared.
    pub fn agenda_changed(&self) -> bool {
        unsafe { ffi::GetAgendaChanged(self.raw.as_ptr()) }
    }
    /// Sets or clears the agenda-changed flag.
    pub fn set_agenda_changed(&self, changed: bool) {
        unsafe { ffi::SetAgendaChanged(self.raw.as_ptr(), changed) }
    }
    /// Refreshes one module's agenda instead of every module's.
    ///
    /// Named rather than handle-based so a module from another environment can
    /// never be passed to CLIPS.
    pub fn refresh_module_agenda(&mut self, module: &str) -> std::result::Result<(), ModuleError> {
        self.with_module(module, |module| unsafe { ffi::RefreshAgenda(module) })
    }
    /// Reorders one module's agenda instead of every module's.
    pub fn reorder_module_agenda(&mut self, module: &str) -> std::result::Result<(), ModuleError> {
        self.with_module(module, |module| unsafe { ffi::ReorderAgenda(module) })
    }
    fn with_module(
        &mut self,
        name: &str,
        operation: impl FnOnce(*mut ffi::Defmodule),
    ) -> std::result::Result<(), ModuleError> {
        let c_name = std::ffi::CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
        if module.is_null() {
            return Err(ModuleError::NotFound(name.to_owned()));
        }
        operation(module);
        Ok(())
    }
    /// Empties the focus stack, so a run fires nothing until a module is
    /// focused again.
    pub fn clear_focus_stack(&mut self) {
        unsafe { ffi::ClearFocusStack(self.raw.as_ptr()) }
    }
}