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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! 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 = ¶meters[..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) }
}
}