1use std::ffi::{CStr, CString};
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::{Defclass, Environment, SlotDefaultType, ffi};
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum HandlerType {
15 Around,
17 Before,
19 Primary,
21 After,
23}
24
25impl HandlerType {
26 fn as_str(self) -> &'static str {
27 match self {
28 Self::Around => "around",
29 Self::Before => "before",
30 Self::Primary => "primary",
31 Self::After => "after",
32 }
33 }
34}
35
36#[derive(Clone, Debug, Eq, PartialEq)]
38pub enum ClassError {
39 InteriorNul,
41 ClassNotFound(String),
43 HandlerNotFound {
45 class: String,
47 name: String,
49 kind: HandlerType,
51 },
52 ClassNotDeletable(String),
55 HandlerNotDeletable {
57 class: String,
59 name: String,
61 kind: HandlerType,
63 },
64 UndefineRejected,
67}
68
69impl std::fmt::Display for ClassError {
70 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 write!(formatter, "CLIPS class error: {self:?}")
72 }
73}
74
75impl std::error::Error for ClassError {}
76
77pub struct MessageHandler<'class> {
79 class: NonNull<ffi::Defclass>,
80 index: u32,
81 marker: PhantomData<&'class Environment>,
82}
83
84impl MessageHandler<'_> {
85 pub fn name(&self) -> &str {
87 unsafe { CStr::from_ptr(ffi::DefmessageHandlerName(self.class.as_ptr(), self.index)) }
88 .to_str()
89 .unwrap_or("")
90 }
91
92 pub fn handler_type(&self) -> HandlerType {
99 match unsafe {
100 CStr::from_ptr(ffi::DefmessageHandlerType(self.class.as_ptr(), self.index)).to_bytes()
101 } {
102 b"around" => HandlerType::Around,
103 b"before" => HandlerType::Before,
104 b"primary" => HandlerType::Primary,
105 b"after" => HandlerType::After,
106 other => panic!("CLIPS returned unknown message-handler type {other:?}"),
107 }
108 }
109
110 pub fn pretty_print(&self) -> Option<&str> {
112 let text = unsafe { ffi::DefmessageHandlerPPForm(self.class.as_ptr(), self.index) };
113 (!text.is_null())
114 .then(|| unsafe { CStr::from_ptr(text) }.to_str().ok())
115 .flatten()
116 }
117
118 pub fn is_deletable(&self) -> bool {
120 unsafe { ffi::DefmessageHandlerIsDeletable(self.class.as_ptr(), self.index) }
121 }
122
123 pub fn watch(&self) -> bool {
125 unsafe { ffi::DefmessageHandlerGetWatch(self.class.as_ptr(), self.index) }
126 }
127
128 pub fn set_watch(&mut self, enabled: bool) {
130 unsafe { ffi::DefmessageHandlerSetWatch(self.class.as_ptr(), self.index, enabled) }
131 }
132}
133
134pub struct MessageHandlers<'class> {
136 class: NonNull<ffi::Defclass>,
137 current: u32,
138 marker: PhantomData<&'class Environment>,
139}
140
141impl<'class> Iterator for MessageHandlers<'class> {
142 type Item = MessageHandler<'class>;
143
144 fn next(&mut self) -> Option<Self::Item> {
145 self.current = unsafe { ffi::GetNextDefmessageHandler(self.class.as_ptr(), self.current) };
146 (self.current != 0).then_some(MessageHandler {
147 class: self.class,
148 index: self.current,
149 marker: PhantomData,
150 })
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161#[repr(u32)]
162pub enum ClassDefaultsMode {
163 Convenience = 0,
166 Conservation = 1,
168}
169
170impl ClassDefaultsMode {
171 fn from_code(code: u32) -> Self {
172 match code {
173 1 => Self::Conservation,
174 _ => Self::Convenience,
175 }
176 }
177}
178
179impl Defclass<'_> {
180 pub fn is_abstract(&self) -> bool {
182 unsafe { ffi::ClassAbstractP(self.raw()) }
183 }
184
185 pub fn preview_send(&self, logical_name: &str, message: &str) -> crate::Result<()> {
192 let logical_name = std::ffi::CString::new(logical_name)?;
193 let message = std::ffi::CString::new(message)?;
194 unsafe { ffi::PreviewSend(self.raw(), logical_name.as_ptr(), message.as_ptr()) };
195 Ok(())
196 }
197
198 pub fn is_reactive(&self) -> bool {
200 unsafe { ffi::ClassReactiveP(self.raw()) }
201 }
202
203 pub fn slots(&self, inherit: bool) -> Vec<String> {
205 let mut output = null_value();
206 unsafe { ffi::ClassSlots(self.raw(), &mut output, inherit) };
207 unsafe { lexeme_multifield(&output) }
208 }
209
210 pub fn superclasses(&self, inherit: bool) -> Vec<String> {
213 let mut output = null_value();
214 unsafe { ffi::ClassSuperclasses(self.raw(), &mut output, inherit) };
215 unsafe { lexeme_multifield(&output) }
216 }
217
218 pub fn subclasses(&self, inherit: bool) -> Vec<String> {
220 let mut output = null_value();
221 unsafe { ffi::ClassSubclasses(self.raw(), &mut output, inherit) };
222 unsafe { lexeme_multifield(&output) }
223 }
224
225 pub fn has_slot(&self, name: &str, inherit: bool) -> Result<bool, ClassError> {
227 let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
228 Ok(unsafe { ffi::SlotExistP(self.raw(), name.as_ptr(), inherit) })
229 }
230
231 pub fn slot(&self, name: &str) -> Result<Option<ClassSlot<'_>>, ClassError> {
235 if !self.has_slot(name, true)? {
236 return Ok(None);
237 }
238 let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
239 Ok(Some(ClassSlot {
240 class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
241 name: c_name,
242 marker: PhantomData,
243 }))
244 }
245
246 pub fn is_superclass_of(&self, other: &Defclass<'_>) -> bool {
252 unsafe { ffi::SuperclassP(self.raw(), other.raw()) }
253 }
254
255 pub fn is_subclass_of(&self, other: &Defclass<'_>) -> bool {
257 unsafe { ffi::SubclassP(self.raw(), other.raw()) }
258 }
259
260 pub fn precedence_list(&self) -> Vec<String> {
262 let mut names = vec![
263 unsafe { CStr::from_ptr(ffi::DefclassName(self.raw())) }
264 .to_string_lossy()
265 .into_owned(),
266 ];
267 names.extend(self.superclasses(true));
268 names
269 }
270
271 pub fn message_handlers(&self) -> MessageHandlers<'_> {
276 MessageHandlers {
277 class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
278 current: 0,
279 marker: PhantomData,
280 }
281 }
282
283 pub fn find_message_handler(
285 &self,
286 name: &str,
287 kind: HandlerType,
288 ) -> Result<Option<MessageHandler<'_>>, ClassError> {
289 let name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
290 let kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
291 let index = unsafe { ffi::FindDefmessageHandler(self.raw(), name.as_ptr(), kind.as_ptr()) };
292 Ok((index != 0).then_some(MessageHandler {
293 class: NonNull::new(self.raw()).expect("Defclass handle is non-null"),
294 index,
295 marker: PhantomData,
296 }))
297 }
298}
299
300impl Environment {
301 pub fn class_defaults_mode(&self) -> ClassDefaultsMode {
303 ClassDefaultsMode::from_code(unsafe { ffi::GetClassDefaultsMode(self.raw.as_ptr()) })
304 }
305
306 pub fn set_class_defaults_mode(&mut self, mode: ClassDefaultsMode) -> ClassDefaultsMode {
309 ClassDefaultsMode::from_code(unsafe {
310 ffi::SetClassDefaultsMode(self.raw.as_ptr(), mode as u32)
311 })
312 }
313
314 pub fn undefine_class(&mut self, name: &str) -> Result<(), ClassError> {
316 let c_name = CString::new(name).map_err(|_| ClassError::InteriorNul)?;
317 let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_name.as_ptr()) })
318 .ok_or_else(|| ClassError::ClassNotFound(name.to_owned()))?;
319 if !unsafe { ffi::DefclassIsDeletable(class.as_ptr()) } {
320 return Err(ClassError::ClassNotDeletable(name.to_owned()));
321 }
322 unsafe { ffi::Undefclass(class.as_ptr(), self.raw.as_ptr()) }
323 .then_some(())
324 .ok_or(ClassError::UndefineRejected)
325 }
326
327 pub fn undefine_message_handler(
330 &mut self,
331 class_name: &str,
332 handler_name: &str,
333 kind: HandlerType,
334 ) -> Result<(), ClassError> {
335 let c_class = CString::new(class_name).map_err(|_| ClassError::InteriorNul)?;
336 let c_handler = CString::new(handler_name).map_err(|_| ClassError::InteriorNul)?;
337 let c_kind = CString::new(kind.as_str()).expect("static handler type has no NUL");
338 let class = NonNull::new(unsafe { ffi::FindDefclass(self.raw.as_ptr(), c_class.as_ptr()) })
339 .ok_or_else(|| ClassError::ClassNotFound(class_name.to_owned()))?;
340 let index = unsafe {
341 ffi::FindDefmessageHandler(class.as_ptr(), c_handler.as_ptr(), c_kind.as_ptr())
342 };
343 if index == 0 {
344 return Err(ClassError::HandlerNotFound {
345 class: class_name.to_owned(),
346 name: handler_name.to_owned(),
347 kind,
348 });
349 }
350 if !unsafe { ffi::DefmessageHandlerIsDeletable(class.as_ptr(), index) } {
351 return Err(ClassError::HandlerNotDeletable {
352 class: class_name.to_owned(),
353 name: handler_name.to_owned(),
354 kind,
355 });
356 }
357 unsafe { ffi::UndefmessageHandler(class.as_ptr(), index, self.raw.as_ptr()) }
358 .then_some(())
359 .ok_or(ClassError::UndefineRejected)
360 }
361}
362
363pub struct ClassSlot<'class> {
369 class: NonNull<ffi::Defclass>,
370 name: CString,
371 marker: PhantomData<&'class Environment>,
372}
373
374impl ClassSlot<'_> {
375 pub fn sources(&self) -> Vec<String> {
377 self.query(ffi::SlotSources)
378 }
379 pub fn facets(&self) -> Vec<String> {
386 self.query(ffi::SlotFacets)
387 }
388 pub fn allowed_types(&self) -> Vec<String> {
390 self.query(ffi::SlotTypes)
391 }
392 pub fn allowed_classes(&self) -> Vec<String> {
394 self.query(ffi::SlotAllowedClasses)
395 }
396 pub fn allowed_values(&self) -> Vec<String> {
399 self.query(ffi::SlotAllowedValues)
400 }
401 pub fn range(&self) -> Option<(String, String)> {
403 let values = self.query_any(ffi::SlotRange);
404 match values.as_slice() {
405 [low, high] => Some((low.clone(), high.clone())),
406 _ => None,
407 }
408 }
409 pub fn cardinality(&self) -> Option<(String, String)> {
412 let values = self.query_any(ffi::SlotCardinality);
413 match values.as_slice() {
414 [low, high] => Some((low.clone(), high.clone())),
415 _ => None,
416 }
417 }
418 pub fn default_type(&self, environment: &Environment) -> SlotDefaultType {
425 match unsafe {
426 ffi::SlotDefaultP(
427 environment.raw.as_ptr(),
428 self.class.as_ptr(),
429 self.name.as_ptr(),
430 )
431 } {
432 0 => SlotDefaultType::None,
433 1 => SlotDefaultType::Static,
434 _ => SlotDefaultType::Dynamic,
435 }
436 }
437 pub fn default_value(&self) -> Option<String> {
439 let values = self.query_any(ffi::SlotDefaultValue);
440 values.first().cloned()
441 }
442 pub fn is_writable(&self) -> bool {
444 unsafe { ffi::SlotWritableP(self.class.as_ptr(), self.name.as_ptr()) }
445 }
446 pub fn is_initable(&self) -> bool {
448 unsafe { ffi::SlotInitableP(self.class.as_ptr(), self.name.as_ptr()) }
449 }
450 pub fn is_public(&self) -> bool {
456 unsafe { ffi::SlotPublicP(self.class.as_ptr(), self.name.as_ptr()) }
457 }
458 pub fn has_direct_access(&self) -> bool {
460 unsafe { ffi::SlotDirectAccessP(self.class.as_ptr(), self.name.as_ptr()) }
461 }
462
463 fn query(
465 &self,
466 query: unsafe extern "C" fn(
467 *mut ffi::Defclass,
468 *const std::ffi::c_char,
469 *mut ffi::CLIPSValue,
470 ) -> bool,
471 ) -> Vec<String> {
472 let mut output = null_value();
473 if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
474 return Vec::new();
475 }
476 unsafe { lexeme_multifield(&output) }
477 }
478
479 fn query_any(
482 &self,
483 query: unsafe extern "C" fn(
484 *mut ffi::Defclass,
485 *const std::ffi::c_char,
486 *mut ffi::CLIPSValue,
487 ) -> bool,
488 ) -> Vec<String> {
489 let mut output = null_value();
490 if !unsafe { query(self.class.as_ptr(), self.name.as_ptr(), &mut output) } {
491 return Vec::new();
492 }
493 unsafe { printed_multifield(&output) }
494 }
495}
496
497fn null_value() -> ffi::CLIPSValue {
498 ffi::CLIPSValue {
499 value: std::ptr::null_mut(),
500 }
501}
502
503unsafe fn printed_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
508 if unsafe { value.value.is_null() } {
509 return Vec::new();
510 }
511 if unsafe { (*value.header).type_ } != 4 {
512 return vec![unsafe { printed_field(value) }];
513 }
514 let multifield = unsafe { &*value.multifield };
515 (0..multifield.length)
516 .map(|index| unsafe { printed_field(&*multifield.contents.as_ptr().add(index)) })
517 .collect()
518}
519
520unsafe fn printed_field(cell: &ffi::CLIPSValue) -> String {
521 match unsafe { (*cell.header).type_ } {
522 0 => unsafe { (*cell.float).contents }.to_string(),
523 1 => unsafe { (*cell.integer).contents }.to_string(),
524 2 | 3 | 8 => unsafe { CStr::from_ptr((*cell.lexeme).contents) }
525 .to_string_lossy()
526 .into_owned(),
527 other => format!("<type {other}>"),
528 }
529}
530
531unsafe fn lexeme_multifield(value: &ffi::CLIPSValue) -> Vec<String> {
532 if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
533 return Vec::new();
534 }
535 let multifield = unsafe { &*value.multifield };
536 (0..multifield.length)
537 .filter_map(|index| {
538 let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
539 let type_code = unsafe { (*cell.header).type_ };
540 matches!(type_code, 2 | 3 | 8).then(|| {
541 unsafe { CStr::from_ptr((*cell.lexeme).contents) }
542 .to_string_lossy()
543 .into_owned()
544 })
545 })
546 .collect()
547}