Skip to main content

clips_bindings/
construct_manage.rs

1//! Construct metadata, undefinition, breakpoints, and per-construct watch
2//! state.
3//!
4//! Undefinition is name-based: the construct is re-resolved under an
5//! exclusive borrow rather than accepting a handle that may already be
6//! stale.
7
8use std::ffi::{CStr, CString};
9
10use crate::construct::{
11    Defclass, Deffacts, Deffunction, Defgeneric, Defglobal, Definstances, Defmodule, Defrule,
12    Deftemplate,
13};
14use crate::{Environment, Result, ffi};
15
16fn text<'a>(value: *const std::ffi::c_char) -> Option<&'a str> {
17    if value.is_null() {
18        None
19    } else {
20        unsafe { CStr::from_ptr(value) }.to_str().ok()
21    }
22}
23
24macro_rules! construct_details {
25    ($handle:ident, $module:ident, $pp:ident, $deletable:ident) => {
26        impl $handle<'_> {
27            /// The name of the defmodule this construct belongs to.
28            ///
29            /// Empty if CLIPS reports no module, which the safe API should not
30            /// be able to produce.
31            pub fn module_name(&self) -> &str {
32                text(unsafe { ffi::$module(self.raw.as_ptr()) }).unwrap_or("")
33            }
34
35            /// The construct's source text as CLIPS reformats it.
36            ///
37            /// `None` when no pretty-print form is stored: CLIPS discards them
38            /// for constructs defined while pretty-printing was disabled, and
39            /// for everything restored from a binary image.
40            pub fn pretty_print(&self) -> Option<&str> {
41                text(unsafe { ffi::$pp(self.raw.as_ptr()) })
42            }
43
44            /// Whether the construct can currently be undefined.
45            ///
46            /// CLIPS refuses while the construct is in use, for example a
47            /// deftemplate with existing facts or a class with instances.
48            pub fn is_deletable(&self) -> bool {
49                unsafe { ffi::$deletable(self.raw.as_ptr()) }
50            }
51        }
52    };
53}
54
55construct_details!(
56    Deftemplate,
57    DeftemplateModule,
58    DeftemplatePPForm,
59    DeftemplateIsDeletable
60);
61construct_details!(Defrule, DefruleModule, DefrulePPForm, DefruleIsDeletable);
62construct_details!(
63    Deffacts,
64    DeffactsModule,
65    DeffactsPPForm,
66    DeffactsIsDeletable
67);
68construct_details!(
69    Defglobal,
70    DefglobalModule,
71    DefglobalPPForm,
72    DefglobalIsDeletable
73);
74construct_details!(
75    Deffunction,
76    DeffunctionModule,
77    DeffunctionPPForm,
78    DeffunctionIsDeletable
79);
80construct_details!(
81    Defgeneric,
82    DefgenericModule,
83    DefgenericPPForm,
84    DefgenericIsDeletable
85);
86construct_details!(
87    Defclass,
88    DefclassModule,
89    DefclassPPForm,
90    DefclassIsDeletable
91);
92construct_details!(
93    Definstances,
94    DefinstancesModule,
95    DefinstancesPPForm,
96    DefinstancesIsDeletable
97);
98
99impl Defmodule<'_> {
100    /// The module's source text as CLIPS reformats it, including its import
101    /// and export specifications.
102    ///
103    /// `None` when no pretty-print form is stored. Modules have no separate
104    /// deletability or module-name query, so this is the only metadata CLIPS
105    /// exposes for them.
106    pub fn pretty_print(&self) -> Option<&str> {
107        text(unsafe { ffi::DefmodulePPForm(self.raw.as_ptr()) })
108    }
109}
110
111impl Deftemplate<'_> {
112    /// Whether this is an implied deftemplate, that is, one CLIPS generated for
113    /// ordered facts rather than one written as a `deftemplate` construct.
114    ///
115    /// CLIPS exposes the implied flag only as a private struct field, and this
116    /// crate adds no C to reach it. An implied template has no source and hence
117    /// no pretty-print form, which is what this checks. It therefore also
118    /// reports `true` for a template defined while pretty-print forms were
119    /// disabled or after a binary load that discarded them.
120    pub fn is_implied(&self) -> bool {
121        self.pretty_print().is_none()
122    }
123}
124
125/// A deffunction's declared arity.
126#[derive(Clone, Copy, Debug, Eq, PartialEq)]
127pub struct DeffunctionArity {
128    /// The number of named parameters, all of which must be supplied.
129    pub min_arguments: usize,
130    /// `None` when the function ends in a wildcard parameter.
131    pub max_arguments: Option<usize>,
132}
133
134impl Deffunction<'_> {
135    /// The function's declared arity.
136    ///
137    /// CLIPS exposes arity only as private struct fields, so it is read back
138    /// from the parameter list of the pretty-print form. Returns `None` when
139    /// the deffunction has no pretty-print form, for example after a binary
140    /// load that discarded it.
141    pub fn arity(&self) -> Option<DeffunctionArity> {
142        let source = self.pretty_print()?;
143        // `(deffunction name [comment] (?a ?b $?rest) body...)`: the arity is
144        // the first parenthesised group after the name.
145        let parameters = source
146            .char_indices()
147            .skip_while(|&(_, character)| character != '(')
148            .skip(1)
149            .find(|&(_, character)| character == '(')
150            .map(|(start, _)| &source[start + 1..])?;
151        let parameters = &parameters[..parameters.find(')')?];
152
153        let mut min_arguments = 0;
154        let mut wildcard = false;
155        for parameter in parameters.split_whitespace() {
156            if parameter.starts_with("$?") {
157                wildcard = true;
158            } else if parameter.starts_with('?') {
159                min_arguments += 1;
160            }
161        }
162        Some(DeffunctionArity {
163            min_arguments,
164            max_arguments: (!wildcard).then_some(min_arguments),
165        })
166    }
167}
168
169macro_rules! undefine_by_name {
170    ($method:ident, $find:ident, $undefine:ident) => {
171        /// Undefines the named construct, returning whether it was removed.
172        ///
173        /// `Ok(false)` means no construct of that name exists, or CLIPS
174        /// refused because it is in use; `is_deletable` on the corresponding
175        /// handle distinguishes the two. Resolving the name here, under
176        /// `&mut self`, is what makes this safe: no handle can outlive the
177        /// construct it names.
178        pub fn $method(&mut self, name: &str) -> Result<bool> {
179            let name = CString::new(name)?;
180            let raw = unsafe { ffi::$find(self.raw.as_ptr(), name.as_ptr()) };
181            Ok(!raw.is_null() && unsafe { ffi::$undefine(raw, self.raw.as_ptr()) })
182        }
183    };
184}
185
186impl Environment {
187    undefine_by_name!(undefine_deftemplate, FindDeftemplate, Undeftemplate);
188    undefine_by_name!(undefine_defrule, FindDefrule, Undefrule);
189    undefine_by_name!(undefine_deffacts, FindDeffacts, Undeffacts);
190    undefine_by_name!(undefine_defglobal, FindDefglobal, Undefglobal);
191    undefine_by_name!(undefine_deffunction, FindDeffunction, Undeffunction);
192    undefine_by_name!(undefine_defgeneric, FindDefgeneric, Undefgeneric);
193    undefine_by_name!(undefine_defclass, FindDefclass, Undefclass);
194    undefine_by_name!(undefine_definstances, FindDefinstances, Undefinstances);
195
196    /// Sets a breakpoint on the named rule, returning whether the rule exists.
197    ///
198    /// A run stops before firing a rule with a breakpoint.
199    pub fn set_rule_breakpoint(&mut self, name: &str) -> Result<bool> {
200        let name = CString::new(name)?;
201        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
202        if rule.is_null() {
203            return Ok(false);
204        }
205        unsafe { ffi::SetBreak(rule) };
206        Ok(true)
207    }
208
209    /// Removes the named rule's breakpoint.
210    ///
211    /// Returns `false` if no such rule exists or it had no breakpoint.
212    pub fn remove_rule_breakpoint(&mut self, name: &str) -> Result<bool> {
213        let name = CString::new(name)?;
214        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
215        Ok(!rule.is_null() && unsafe { ffi::RemoveBreak(rule) })
216    }
217
218    /// Re-adds the named rule's satisfied matches to the agenda, so matches
219    /// that already fired can fire again.
220    ///
221    /// Returns whether the rule exists.
222    pub fn refresh_rule(&mut self, name: &str) -> Result<bool> {
223        let name = CString::new(name)?;
224        let rule = unsafe { ffi::FindDefrule(self.raw.as_ptr(), name.as_ptr()) };
225        if rule.is_null() {
226            return Ok(false);
227        }
228        unsafe { ffi::Refresh(rule) };
229        Ok(true)
230    }
231
232    /// Removes every breakpoint in the environment.
233    pub fn remove_all_breakpoints(&mut self) {
234        unsafe { ffi::RemoveAllBreakpoints(self.raw.as_ptr()) }
235    }
236
237    /// The names of all rules that currently have a breakpoint.
238    ///
239    /// CLIPS's own listing writes to a router; this walks the rules instead so
240    /// the result is owned data rather than captured output.
241    pub fn breakpoint_rule_names(&self) -> Vec<String> {
242        self.defrules()
243            .filter(|rule| rule.has_breakpoint())
244            .map(|rule| rule.name().to_owned())
245            .collect()
246    }
247}
248
249/// How much detail CLIPS prints to the routers while summarising matches.
250#[derive(Clone, Copy, Debug, Eq, PartialEq)]
251#[repr(i32)]
252pub enum Verbosity {
253    /// Prints every partial match.
254    Verbose = 0,
255    /// Prints counts per pattern.
256    Succinct = 1,
257    /// Prints nothing.
258    Terse = 2,
259}
260
261/// Counts summarising how far a rule's patterns have matched.
262#[derive(Clone, Copy, Debug, Eq, PartialEq)]
263pub struct MatchSummary {
264    /// Matches of the rule's individual patterns.
265    pub alpha_matches: i64,
266    /// Partial matches spanning more than one pattern.
267    pub beta_matches: i64,
268    /// Complete matches, that is, activations on the agenda.
269    pub activations: i64,
270}
271
272impl Defrule<'_> {
273    /// Summarises the rule's matches without exposing any rete structures.
274    ///
275    /// `verbosity` only controls what CLIPS prints to the routers while
276    /// computing the summary; the returned counts are the same either way.
277    pub fn matches(&self, verbosity: Verbosity) -> MatchSummary {
278        let mut raw = ffi::CLIPSValue {
279            value: std::ptr::null_mut(),
280        };
281        unsafe { ffi::Matches(self.raw.as_ptr(), verbosity as std::ffi::c_int, &mut raw) };
282        let counts = crate::Multifield::from_value(crate::Value::retaining(self._environment, raw));
283        let count = |index: usize| {
284            counts
285                .get(index)
286                .and_then(|value| value.as_i64())
287                .unwrap_or(0)
288        };
289        MatchSummary {
290            alpha_matches: count(0),
291            beta_matches: count(1),
292            activations: count(2),
293        }
294    }
295
296    /// The rule's disjuncts, that is, the separate rules CLIPS generates for an
297    /// `or` conditional element. A rule without `or` has exactly one disjunct.
298    pub fn disjuncts(&self) -> Vec<Defrule<'_>> {
299        let environment = self._environment.raw.as_ptr();
300        let count = unsafe { ffi::GetDisjunctCount(environment, self.raw.as_ptr()) };
301        (1..=count)
302            .filter_map(|index| {
303                std::ptr::NonNull::new(unsafe {
304                    ffi::GetNthDisjunct(environment, self.raw.as_ptr(), index)
305                })
306                .map(|raw| Defrule {
307                    raw,
308                    _environment: self._environment,
309                })
310            })
311            .collect()
312    }
313}
314
315impl Defrule<'_> {
316    /// Whether a run stops before firing this rule.
317    pub fn has_breakpoint(&self) -> bool {
318        unsafe { ffi::DefruleHasBreakpoint(self.raw.as_ptr()) }
319    }
320
321    /// Whether CLIPS traces this rule's firings.
322    pub fn watch_firings(&self) -> bool {
323        unsafe { ffi::DefruleGetWatchFirings(self.raw.as_ptr()) }
324    }
325
326    /// Enables or disables tracing of this rule's firings.
327    pub fn set_watch_firings(&mut self, enabled: bool) {
328        unsafe { ffi::DefruleSetWatchFirings(self.raw.as_ptr(), enabled) }
329    }
330
331    /// Whether CLIPS traces this rule's activations and deactivations.
332    pub fn watch_activations(&self) -> bool {
333        unsafe { ffi::DefruleGetWatchActivations(self.raw.as_ptr()) }
334    }
335
336    /// Enables or disables tracing of this rule's activations.
337    pub fn set_watch_activations(&mut self, enabled: bool) {
338        unsafe { ffi::DefruleSetWatchActivations(self.raw.as_ptr(), enabled) }
339    }
340}
341
342macro_rules! simple_watch {
343    ($handle:ident, $get:ident, $set:ident) => {
344        impl $handle<'_> {
345            /// Whether CLIPS traces activity for this construct specifically,
346            /// independently of the environment-wide watch categories.
347            pub fn watched(&self) -> bool {
348                unsafe { ffi::$get(self.raw.as_ptr()) }
349            }
350
351            /// Enables or disables tracing for this construct.
352            pub fn set_watched(&mut self, enabled: bool) {
353                unsafe { ffi::$set(self.raw.as_ptr(), enabled) }
354            }
355        }
356    };
357}
358
359simple_watch!(Deftemplate, DeftemplateGetWatch, DeftemplateSetWatch);
360simple_watch!(Defglobal, DefglobalGetWatch, DefglobalSetWatch);
361simple_watch!(Deffunction, DeffunctionGetWatch, DeffunctionSetWatch);
362simple_watch!(Defgeneric, DefgenericGetWatch, DefgenericSetWatch);
363
364impl Defclass<'_> {
365    /// Whether CLIPS traces creation and deletion of this class's instances.
366    pub fn watch_instances(&self) -> bool {
367        unsafe { ffi::DefclassGetWatchInstances(self.raw.as_ptr()) }
368    }
369
370    /// Enables or disables tracing of this class's instance lifecycle.
371    pub fn set_watch_instances(&mut self, enabled: bool) {
372        unsafe { ffi::DefclassSetWatchInstances(self.raw.as_ptr(), enabled) }
373    }
374
375    /// Whether CLIPS traces writes to this class's slots.
376    pub fn watch_slots(&self) -> bool {
377        unsafe { ffi::DefclassGetWatchSlots(self.raw.as_ptr()) }
378    }
379
380    /// Enables or disables tracing of writes to this class's slots.
381    pub fn set_watch_slots(&mut self, enabled: bool) {
382        unsafe { ffi::DefclassSetWatchSlots(self.raw.as_ptr(), enabled) }
383    }
384}