1use 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 pub fn module_name(&self) -> &str {
32 text(unsafe { ffi::$module(self.raw.as_ptr()) }).unwrap_or("")
33 }
34
35 pub fn pretty_print(&self) -> Option<&str> {
41 text(unsafe { ffi::$pp(self.raw.as_ptr()) })
42 }
43
44 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 pub fn pretty_print(&self) -> Option<&str> {
107 text(unsafe { ffi::DefmodulePPForm(self.raw.as_ptr()) })
108 }
109}
110
111impl Deftemplate<'_> {
112 pub fn is_implied(&self) -> bool {
121 self.pretty_print().is_none()
122 }
123}
124
125#[derive(Clone, Copy, Debug, Eq, PartialEq)]
127pub struct DeffunctionArity {
128 pub min_arguments: usize,
130 pub max_arguments: Option<usize>,
132}
133
134impl Deffunction<'_> {
135 pub fn arity(&self) -> Option<DeffunctionArity> {
142 let source = self.pretty_print()?;
143 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 = ¶meters[..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 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 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 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 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 pub fn remove_all_breakpoints(&mut self) {
234 unsafe { ffi::RemoveAllBreakpoints(self.raw.as_ptr()) }
235 }
236
237 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
251#[repr(i32)]
252pub enum Verbosity {
253 Verbose = 0,
255 Succinct = 1,
257 Terse = 2,
259}
260
261#[derive(Clone, Copy, Debug, Eq, PartialEq)]
263pub struct MatchSummary {
264 pub alpha_matches: i64,
266 pub beta_matches: i64,
268 pub activations: i64,
270}
271
272impl Defrule<'_> {
273 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 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 pub fn has_breakpoint(&self) -> bool {
318 unsafe { ffi::DefruleHasBreakpoint(self.raw.as_ptr()) }
319 }
320
321 pub fn watch_firings(&self) -> bool {
323 unsafe { ffi::DefruleGetWatchFirings(self.raw.as_ptr()) }
324 }
325
326 pub fn set_watch_firings(&mut self, enabled: bool) {
328 unsafe { ffi::DefruleSetWatchFirings(self.raw.as_ptr(), enabled) }
329 }
330
331 pub fn watch_activations(&self) -> bool {
333 unsafe { ffi::DefruleGetWatchActivations(self.raw.as_ptr()) }
334 }
335
336 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 pub fn watched(&self) -> bool {
348 unsafe { ffi::$get(self.raw.as_ptr()) }
349 }
350
351 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 pub fn watch_instances(&self) -> bool {
367 unsafe { ffi::DefclassGetWatchInstances(self.raw.as_ptr()) }
368 }
369
370 pub fn set_watch_instances(&mut self, enabled: bool) {
372 unsafe { ffi::DefclassSetWatchInstances(self.raw.as_ptr(), enabled) }
373 }
374
375 pub fn watch_slots(&self) -> bool {
377 unsafe { ffi::DefclassGetWatchSlots(self.raw.as_ptr()) }
378 }
379
380 pub fn set_watch_slots(&mut self, enabled: bool) {
382 unsafe { ffi::DefclassSetWatchSlots(self.raw.as_ptr(), enabled) }
383 }
384}