clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Construct metadata, undefinition, breakpoints, and per-construct watch
//! state.
//!
//! Undefinition is name-based: the construct is re-resolved under an
//! exclusive borrow rather than accepting a handle that may already be
//! stale.

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

use crate::construct::{
    Defclass, Deffacts, Deffunction, Defgeneric, Defglobal, Definstances, Defmodule, Defrule,
    Deftemplate,
};
use crate::{Environment, Result, ffi};

fn text<'a>(value: *const std::ffi::c_char) -> Option<&'a str> {
    if value.is_null() {
        None
    } else {
        unsafe { CStr::from_ptr(value) }.to_str().ok()
    }
}

macro_rules! construct_details {
    ($handle:ident, $module:ident, $pp:ident, $deletable:ident) => {
        impl $handle<'_> {
            /// The name of the defmodule this construct belongs to.
            ///
            /// Empty if CLIPS reports no module, which the safe API should not
            /// be able to produce.
            pub fn module_name(&self) -> &str {
                text(unsafe { ffi::$module(self.raw.as_ptr()) }).unwrap_or("")
            }

            /// The construct's source text as CLIPS reformats it.
            ///
            /// `None` when no pretty-print form is stored: CLIPS discards them
            /// for constructs defined while pretty-printing was disabled, and
            /// for everything restored from a binary image.
            pub fn pretty_print(&self) -> Option<&str> {
                text(unsafe { ffi::$pp(self.raw.as_ptr()) })
            }

            /// Whether the construct can currently be undefined.
            ///
            /// CLIPS refuses while the construct is in use, for example a
            /// deftemplate with existing facts or a class with instances.
            pub fn is_deletable(&self) -> bool {
                unsafe { ffi::$deletable(self.raw.as_ptr()) }
            }
        }
    };
}

construct_details!(
    Deftemplate,
    DeftemplateModule,
    DeftemplatePPForm,
    DeftemplateIsDeletable
);
construct_details!(Defrule, DefruleModule, DefrulePPForm, DefruleIsDeletable);
construct_details!(
    Deffacts,
    DeffactsModule,
    DeffactsPPForm,
    DeffactsIsDeletable
);
construct_details!(
    Defglobal,
    DefglobalModule,
    DefglobalPPForm,
    DefglobalIsDeletable
);
construct_details!(
    Deffunction,
    DeffunctionModule,
    DeffunctionPPForm,
    DeffunctionIsDeletable
);
construct_details!(
    Defgeneric,
    DefgenericModule,
    DefgenericPPForm,
    DefgenericIsDeletable
);
construct_details!(
    Defclass,
    DefclassModule,
    DefclassPPForm,
    DefclassIsDeletable
);
construct_details!(
    Definstances,
    DefinstancesModule,
    DefinstancesPPForm,
    DefinstancesIsDeletable
);

impl Defmodule<'_> {
    /// The module's source text as CLIPS reformats it, including its import
    /// and export specifications.
    ///
    /// `None` when no pretty-print form is stored. Modules have no separate
    /// deletability or module-name query, so this is the only metadata CLIPS
    /// exposes for them.
    pub fn pretty_print(&self) -> Option<&str> {
        text(unsafe { ffi::DefmodulePPForm(self.raw.as_ptr()) })
    }
}

impl Deftemplate<'_> {
    /// Whether this is an implied deftemplate, that is, one CLIPS generated for
    /// ordered facts rather than one written as a `deftemplate` construct.
    ///
    /// CLIPS exposes the implied flag only as a private struct field, and this
    /// crate adds no C to reach it. An implied template has no source and hence
    /// no pretty-print form, which is what this checks. It therefore also
    /// reports `true` for a template defined while pretty-print forms were
    /// disabled or after a binary load that discarded them.
    pub fn is_implied(&self) -> bool {
        self.pretty_print().is_none()
    }
}

/// A deffunction's declared arity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DeffunctionArity {
    /// The number of named parameters, all of which must be supplied.
    pub min_arguments: usize,
    /// `None` when the function ends in a wildcard parameter.
    pub max_arguments: Option<usize>,
}

impl Deffunction<'_> {
    /// The function's declared arity.
    ///
    /// CLIPS exposes arity only as private struct fields, so it is read back
    /// from the parameter list of the pretty-print form. Returns `None` when
    /// the deffunction has no pretty-print form, for example after a binary
    /// load that discarded it.
    pub fn arity(&self) -> Option<DeffunctionArity> {
        let source = self.pretty_print()?;
        // `(deffunction name [comment] (?a ?b $?rest) body...)`: the arity is
        // the first parenthesised group after the name.
        let parameters = source
            .char_indices()
            .skip_while(|&(_, character)| character != '(')
            .skip(1)
            .find(|&(_, character)| character == '(')
            .map(|(start, _)| &source[start + 1..])?;
        let parameters = &parameters[..parameters.find(')')?];

        let mut min_arguments = 0;
        let mut wildcard = false;
        for parameter in parameters.split_whitespace() {
            if parameter.starts_with("$?") {
                wildcard = true;
            } else if parameter.starts_with('?') {
                min_arguments += 1;
            }
        }
        Some(DeffunctionArity {
            min_arguments,
            max_arguments: (!wildcard).then_some(min_arguments),
        })
    }
}

macro_rules! undefine_by_name {
    ($method:ident, $find:ident, $undefine:ident) => {
        /// Undefines the named construct, returning whether it was removed.
        ///
        /// `Ok(false)` means no construct of that name exists, or CLIPS
        /// refused because it is in use; `is_deletable` on the corresponding
        /// handle distinguishes the two. Resolving the name here, under
        /// `&mut self`, is what makes this safe: no handle can outlive the
        /// construct it names.
        pub fn $method(&mut self, name: &str) -> Result<bool> {
            let name = CString::new(name)?;
            let raw = unsafe { ffi::$find(self.raw.as_ptr(), name.as_ptr()) };
            Ok(!raw.is_null() && unsafe { ffi::$undefine(raw, self.raw.as_ptr()) })
        }
    };
}

impl Environment {
    undefine_by_name!(undefine_deftemplate, FindDeftemplate, Undeftemplate);
    undefine_by_name!(undefine_defrule, FindDefrule, Undefrule);
    undefine_by_name!(undefine_deffacts, FindDeffacts, Undeffacts);
    undefine_by_name!(undefine_defglobal, FindDefglobal, Undefglobal);
    undefine_by_name!(undefine_deffunction, FindDeffunction, Undeffunction);
    undefine_by_name!(undefine_defgeneric, FindDefgeneric, Undefgeneric);
    undefine_by_name!(undefine_defclass, FindDefclass, Undefclass);
    undefine_by_name!(undefine_definstances, FindDefinstances, Undefinstances);

    /// Sets a breakpoint on the named rule, returning whether the rule exists.
    ///
    /// A run stops before firing a rule with a breakpoint.
    pub fn set_rule_breakpoint(&mut self, name: &str) -> Result<bool> {
        let name = CString::new(name)?;
        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
        if rule.is_null() {
            return Ok(false);
        }
        unsafe { ffi::SetBreak(rule) };
        Ok(true)
    }

    /// Removes the named rule's breakpoint.
    ///
    /// Returns `false` if no such rule exists or it had no breakpoint.
    pub fn remove_rule_breakpoint(&mut self, name: &str) -> Result<bool> {
        let name = CString::new(name)?;
        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
        Ok(!rule.is_null() && unsafe { ffi::RemoveBreak(rule) })
    }

    /// Re-adds the named rule's satisfied matches to the agenda, so matches
    /// that already fired can fire again.
    ///
    /// Returns whether the rule exists.
    pub fn refresh_rule(&mut self, name: &str) -> Result<bool> {
        let name = CString::new(name)?;
        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
        if rule.is_null() {
            return Ok(false);
        }
        unsafe { ffi::Refresh(rule) };
        Ok(true)
    }

    /// Removes every breakpoint in the environment.
    pub fn remove_all_breakpoints(&mut self) {
        unsafe { ffi::RemoveAllBreakpoints(self.raw.as_ptr()) }
    }

    /// The names of all rules that currently have a breakpoint.
    ///
    /// CLIPS's own listing writes to a router; this walks the rules instead so
    /// the result is owned data rather than captured output.
    pub fn breakpoint_rule_names(&self) -> Vec<String> {
        self.defrules()
            .filter(|rule| rule.has_breakpoint())
            .map(|rule| rule.name().to_owned())
            .collect()
    }
}

/// How much detail CLIPS prints to the routers while summarising matches.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(i32)]
pub enum Verbosity {
    /// Prints every partial match.
    Verbose = 0,
    /// Prints counts per pattern.
    Succinct = 1,
    /// Prints nothing.
    Terse = 2,
}

/// Counts summarising how far a rule's patterns have matched.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MatchSummary {
    /// Matches of the rule's individual patterns.
    pub alpha_matches: i64,
    /// Partial matches spanning more than one pattern.
    pub beta_matches: i64,
    /// Complete matches, that is, activations on the agenda.
    pub activations: i64,
}

impl Defrule<'_> {
    /// Summarises the rule's matches without exposing any rete structures.
    ///
    /// `verbosity` only controls what CLIPS prints to the routers while
    /// computing the summary; the returned counts are the same either way.
    pub fn matches(&self, verbosity: Verbosity) -> MatchSummary {
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        unsafe { ffi::Matches(self.raw.as_ptr(), verbosity as std::ffi::c_int, &mut raw) };
        let counts = crate::Multifield::from_value(crate::Value::retaining(self._environment, raw));
        let count = |index: usize| {
            counts
                .get(index)
                .and_then(|value| value.as_i64())
                .unwrap_or(0)
        };
        MatchSummary {
            alpha_matches: count(0),
            beta_matches: count(1),
            activations: count(2),
        }
    }

    /// The rule's disjuncts, that is, the separate rules CLIPS generates for an
    /// `or` conditional element. A rule without `or` has exactly one disjunct.
    pub fn disjuncts(&self) -> Vec<Defrule<'_>> {
        let environment = self._environment.raw.as_ptr();
        let count = unsafe { ffi::GetDisjunctCount(environment, self.raw.as_ptr()) };
        (1..=count)
            .filter_map(|index| {
                std::ptr::NonNull::new(unsafe {
                    ffi::GetNthDisjunct(environment, self.raw.as_ptr(), index)
                })
                .map(|raw| Defrule {
                    raw,
                    _environment: self._environment,
                })
            })
            .collect()
    }
}

impl Defrule<'_> {
    /// Whether a run stops before firing this rule.
    pub fn has_breakpoint(&self) -> bool {
        unsafe { ffi::DefruleHasBreakpoint(self.raw.as_ptr()) }
    }

    /// Whether CLIPS traces this rule's firings.
    pub fn watch_firings(&self) -> bool {
        unsafe { ffi::DefruleGetWatchFirings(self.raw.as_ptr()) }
    }

    /// Enables or disables tracing of this rule's firings.
    pub fn set_watch_firings(&mut self, enabled: bool) {
        unsafe { ffi::DefruleSetWatchFirings(self.raw.as_ptr(), enabled) }
    }

    /// Whether CLIPS traces this rule's activations and deactivations.
    pub fn watch_activations(&self) -> bool {
        unsafe { ffi::DefruleGetWatchActivations(self.raw.as_ptr()) }
    }

    /// Enables or disables tracing of this rule's activations.
    pub fn set_watch_activations(&mut self, enabled: bool) {
        unsafe { ffi::DefruleSetWatchActivations(self.raw.as_ptr(), enabled) }
    }
}

macro_rules! simple_watch {
    ($handle:ident, $get:ident, $set:ident) => {
        impl $handle<'_> {
            /// Whether CLIPS traces activity for this construct specifically,
            /// independently of the environment-wide watch categories.
            pub fn watched(&self) -> bool {
                unsafe { ffi::$get(self.raw.as_ptr()) }
            }

            /// Enables or disables tracing for this construct.
            pub fn set_watched(&mut self, enabled: bool) {
                unsafe { ffi::$set(self.raw.as_ptr(), enabled) }
            }
        }
    };
}

simple_watch!(Deftemplate, DeftemplateGetWatch, DeftemplateSetWatch);
simple_watch!(Defglobal, DefglobalGetWatch, DefglobalSetWatch);
simple_watch!(Deffunction, DeffunctionGetWatch, DeffunctionSetWatch);
simple_watch!(Defgeneric, DefgenericGetWatch, DefgenericSetWatch);

impl Defclass<'_> {
    /// Whether CLIPS traces creation and deletion of this class's instances.
    pub fn watch_instances(&self) -> bool {
        unsafe { ffi::DefclassGetWatchInstances(self.raw.as_ptr()) }
    }

    /// Enables or disables tracing of this class's instance lifecycle.
    pub fn set_watch_instances(&mut self, enabled: bool) {
        unsafe { ffi::DefclassSetWatchInstances(self.raw.as_ptr(), enabled) }
    }

    /// Whether CLIPS traces writes to this class's slots.
    pub fn watch_slots(&self) -> bool {
        unsafe { ffi::DefclassGetWatchSlots(self.raw.as_ptr()) }
    }

    /// Enables or disables tracing of writes to this class's slots.
    pub fn set_watch_slots(&mut self, enabled: bool) {
        unsafe { ffi::DefclassSetWatchSlots(self.raw.as_ptr(), enabled) }
    }
}