Skip to main content

clips_bindings/
watch.rs

1//! Typed access to CLIPS watch and construct-loading diagnostics.
2
3use std::ffi::{CString, NulError};
4
5use crate::{Environment, ffi};
6
7/// A built-in CLIPS watch category.
8///
9/// These discriminants match `WatchItem` in CLIPS 6.4.2's `watch.h`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[repr(i32)]
12pub enum WatchItem {
13    /// Every category at once. This is CLIPS's shorthand rather than a
14    /// category of its own, so [`Environment::watch_state`] treats it
15    /// specially.
16    All = 0,
17    /// Fact assertions and retractions.
18    Facts = 1,
19    /// Instance creation and deletion.
20    Instances = 2,
21    /// Writes to instance slots.
22    Slots = 3,
23    /// Rule firings.
24    Rules = 4,
25    /// Activations added to and removed from the agenda.
26    Activations = 5,
27    /// Messages sent to instances.
28    Messages = 6,
29    /// Message handlers as they run.
30    MessageHandlers = 7,
31    /// Generic function calls.
32    GenericFunctions = 8,
33    /// Generic function methods as they run.
34    Methods = 9,
35    /// Deffunction calls.
36    Deffunctions = 10,
37    /// Constructs as they are compiled during loading.
38    Compilations = 11,
39    /// Per-run statistics such as rule firings and elapsed time.
40    Statistics = 12,
41    /// Changes to defglobal values.
42    Globals = 13,
43    /// Changes to the focus stack.
44    Focus = 14,
45}
46
47impl WatchItem {
48    /// Every individually watchable category, excluding [`WatchItem::All`],
49    /// which is CLIPS's shorthand for the whole set rather than a category.
50    pub const CATEGORIES: [Self; 14] = [
51        Self::Facts,
52        Self::Instances,
53        Self::Slots,
54        Self::Rules,
55        Self::Activations,
56        Self::Messages,
57        Self::MessageHandlers,
58        Self::GenericFunctions,
59        Self::Methods,
60        Self::Deffunctions,
61        Self::Compilations,
62        Self::Statistics,
63        Self::Globals,
64        Self::Focus,
65    ];
66
67    /// The category's CLIPS name, as the `watch` command spells it.
68    pub const fn name(self) -> &'static str {
69        match self {
70            Self::All => "all",
71            Self::Facts => "facts",
72            Self::Instances => "instances",
73            Self::Slots => "slots",
74            Self::Rules => "rules",
75            Self::Activations => "activations",
76            Self::Messages => "messages",
77            Self::MessageHandlers => "message-handlers",
78            Self::GenericFunctions => "generic-functions",
79            Self::Methods => "methods",
80            Self::Deffunctions => "deffunctions",
81            Self::Compilations => "compilations",
82            Self::Statistics => "statistics",
83            Self::Globals => "globals",
84            Self::Focus => "focus",
85        }
86    }
87}
88
89/// Why a watch or dribble operation failed.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum WatchError {
92    /// The name or path contained a NUL byte.
93    InteriorNul,
94    /// CLIPS has no watch item registered under that name.
95    UnknownItem(String),
96}
97
98impl From<NulError> for WatchError {
99    fn from(_: NulError) -> Self {
100        Self::InteriorNul
101    }
102}
103
104impl std::fmt::Display for WatchError {
105    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        match self {
107            Self::InteriorNul => formatter.write_str("watch item name contains a NUL byte"),
108            Self::UnknownItem(name) => write!(formatter, "unknown CLIPS watch item: {name}"),
109        }
110    }
111}
112
113impl std::error::Error for WatchError {}
114
115impl Environment {
116    /// Enables a built-in watch category.
117    pub fn watch(&mut self, item: WatchItem) {
118        unsafe { ffi::Watch(self.raw.as_ptr(), item as i32) }
119    }
120
121    /// Disables a built-in watch category.
122    pub fn unwatch(&mut self, item: WatchItem) {
123        unsafe { ffi::Unwatch(self.raw.as_ptr(), item as i32) }
124    }
125
126    /// Returns the global state of a built-in watch category.
127    pub fn watch_state(&self, item: WatchItem) -> bool {
128        if item == WatchItem::All {
129            // CLIPS's GetWatchState(ALL) always returns false; GetWatchItem
130            // implements the useful "are all categories enabled?" query.
131            unsafe { ffi::GetWatchItem(self.raw.as_ptr(), c"all".as_ptr()) == 1 }
132        } else {
133            unsafe { ffi::GetWatchState(self.raw.as_ptr(), item as i32) }
134        }
135    }
136
137    /// Changes the global state of a built-in watch category.
138    pub fn set_watch_state(&mut self, item: WatchItem, enabled: bool) {
139        unsafe { ffi::SetWatchState(self.raw.as_ptr(), item as i32, enabled) }
140    }
141
142    /// Every built-in watch category paired with its current state.
143    pub fn watch_states(&self) -> Vec<(WatchItem, bool)> {
144        WatchItem::CATEGORIES
145            .into_iter()
146            .map(|item| (item, self.watch_state(item)))
147            .collect()
148    }
149
150    /// Enables a watch item by its registered CLIPS name.
151    ///
152    /// This also supports watch items registered by CLIPS extensions.
153    pub fn watch_named(&mut self, name: &str) -> Result<(), WatchError> {
154        self.set_named_watch(name, true)
155    }
156
157    /// Disables a watch item by its registered CLIPS name.
158    pub fn unwatch_named(&mut self, name: &str) -> Result<(), WatchError> {
159        self.set_named_watch(name, false)
160    }
161
162    /// Returns the state of a watch item registered under `name`.
163    pub fn named_watch_state(&self, name: &str) -> Result<bool, WatchError> {
164        let name_c = CString::new(name)?;
165        match unsafe { ffi::GetWatchItem(self.raw.as_ptr(), name_c.as_ptr()) } {
166            0 => Ok(false),
167            1 => Ok(true),
168            _ => Err(WatchError::UnknownItem(name.to_owned())),
169        }
170    }
171
172    fn set_named_watch(&mut self, name: &str, enabled: bool) -> Result<(), WatchError> {
173        let name_c = CString::new(name)?;
174        let changed = unsafe {
175            if enabled {
176                ffi::WatchString(self.raw.as_ptr(), name_c.as_ptr())
177            } else {
178                ffi::UnwatchString(self.raw.as_ptr(), name_c.as_ptr())
179            }
180        };
181        changed
182            .then_some(())
183            .ok_or_else(|| WatchError::UnknownItem(name.to_owned()))
184    }
185
186    /// Whether construct compilations are currently traced.
187    pub fn compilations_watch(&self) -> bool {
188        unsafe { ffi::GetCompilationsWatch(self.raw.as_ptr()) }
189    }
190
191    /// Enables or disables tracing of construct compilation.
192    pub fn set_compilations_watch(&mut self, enabled: bool) {
193        unsafe { ffi::SetCompilationsWatch(self.raw.as_ptr(), enabled) }
194    }
195
196    /// Whether constructs are printed as they are loaded.
197    pub fn print_while_loading(&self) -> bool {
198        unsafe { ffi::GetPrintWhileLoading(self.raw.as_ptr()) }
199    }
200
201    /// Enables or disables echoing constructs as they load.
202    pub fn set_print_while_loading(&mut self, enabled: bool) {
203        unsafe { ffi::SetPrintWhileLoading(self.raw.as_ptr(), enabled) }
204    }
205
206    /// Whether CLIPS currently considers a load operation in progress.
207    pub fn load_in_progress(&self) -> bool {
208        unsafe { ffi::GetLoadInProgress(self.raw.as_ptr()) }
209    }
210
211    /// Sets the load-in-progress flag, which changes how CLIPS reports parse
212    /// errors. Setting it by hand is rarely correct.
213    pub fn set_load_in_progress(&mut self, in_progress: bool) {
214        unsafe { ffi::SetLoadInProgress(self.raw.as_ptr(), in_progress) }
215    }
216
217    /// Whether CLIPS is currently executing a construct.
218    pub fn executing_construct(&self) -> bool {
219        unsafe { ffi::ExecutingConstruct(self.raw.as_ptr()) }
220    }
221
222    /// Sets the executing-construct flag. Setting it by hand is rarely
223    /// correct; CLIPS maintains it during execution.
224    pub fn set_executing_construct(&mut self, executing: bool) {
225        unsafe { ffi::SetExecutingConstruct(self.raw.as_ptr(), executing) }
226    }
227
228    /// Bytes CLIPS currently has allocated.
229    pub fn memory_used(&self) -> i64 {
230        unsafe { ffi::MemUsed(self.raw.as_ptr()) }
231    }
232
233    /// Allocation requests CLIPS has made since the environment was created.
234    pub fn memory_requests(&self) -> i64 {
235        unsafe { ffi::MemRequests(self.raw.as_ptr()) }
236    }
237
238    /// Frees pooled memory, returning the number of bytes released. A negative
239    /// `amount` releases everything CLIPS can.
240    pub fn release_memory(&mut self, amount: i64) -> i64 {
241        unsafe { ffi::ReleaseMem(self.raw.as_ptr(), amount) }
242    }
243
244    /// Whether CLIPS returns freed memory immediately instead of pooling it.
245    pub fn conserve_memory(&self) -> bool {
246        unsafe { ffi::GetConserveMemory(self.raw.as_ptr()) }
247    }
248
249    /// Sets the conserve-memory behaviour and returns the previous value.
250    pub fn set_conserve_memory(&mut self, enabled: bool) -> bool {
251        unsafe { ffi::SetConserveMemory(self.raw.as_ptr(), enabled) }
252    }
253
254    /// The percentage below which profiled constructs are omitted from reports.
255    ///
256    /// CLIPS exposes profile collection and reporting only as its `profile` and
257    /// `profile-info` commands; run them with [`Environment::eval`] and capture
258    /// the report with a [`crate::Router`].
259    pub fn profile_percent_threshold(&self) -> f64 {
260        unsafe { ffi::GetProfilePercentThreshold(self.raw.as_ptr()) }
261    }
262
263    /// Sets the profile reporting threshold and returns the previous value.
264    pub fn set_profile_percent_threshold(&mut self, threshold: f64) -> f64 {
265        unsafe { ffi::SetProfilePercentThreshold(self.raw.as_ptr(), threshold) }
266    }
267
268    /// Starts copying router output to `path`.
269    ///
270    /// Returns `false` if CLIPS could not open the file or dribbling is already
271    /// active.
272    pub fn dribble_on(&mut self, path: &str) -> Result<bool, WatchError> {
273        let path = CString::new(path)?;
274        Ok(unsafe { ffi::DribbleOn(self.raw.as_ptr(), path.as_ptr()) })
275    }
276
277    /// Whether router output is currently being copied to a dribble file.
278    pub fn dribble_active(&self) -> bool {
279        unsafe { ffi::DribbleActive(self.raw.as_ptr()) }
280    }
281
282    /// Stops dribbling and closes the file. Returns `false` when no dribble
283    /// file was open.
284    pub fn dribble_off(&mut self) -> bool {
285        unsafe { ffi::DribbleOff(self.raw.as_ptr()) }
286    }
287
288    /// Starts dribbling to `path` and stops it again when the guard is dropped.
289    pub fn dribble_to(&mut self, path: &str) -> Result<Option<Dribble<'_>>, WatchError> {
290        if !self.dribble_on(path)? {
291            return Ok(None);
292        }
293        Ok(Some(Dribble { environment: self }))
294    }
295
296    /// Whether periodic hooks run during execution.
297    ///
298    /// Returns the previous setting.
299    pub fn set_periodic_functions_enabled(&mut self, enabled: bool) -> bool {
300        unsafe { ffi::EnablePeriodicFunctions(self.raw.as_ptr(), enabled) }
301    }
302
303    /// Whether CLIPS calls its yield-time function during execution.
304    ///
305    /// Returns the previous setting. The function itself cannot be installed
306    /// from Rust: CLIPS 6.4.2 keeps it in a private struct field with no public
307    /// setter, so only the enable flag is bound.
308    pub fn set_yield_function_enabled(&mut self, enabled: bool) -> bool {
309        unsafe { ffi::EnableYieldFunction(self.raw.as_ptr(), enabled) }
310    }
311}
312
313/// Stops dribbling when dropped.
314pub struct Dribble<'env> {
315    environment: &'env mut Environment,
316}
317
318impl Drop for Dribble<'_> {
319    fn drop(&mut self) {
320        self.environment.dribble_off();
321    }
322}