1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//! 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();
}
}