Skip to main content

clips_bindings/
hook.rs

1//! Panic-contained lifecycle hooks owned by a CLIPS environment.
2
3use std::cell::RefCell;
4use std::ffi::{CString, c_void};
5use std::panic::{AssertUnwindSafe, catch_unwind};
6
7use crate::ffi;
8
9/// A CLIPS lifecycle event a Rust callback can be attached to.
10///
11/// The binary-load and module variants have no CLIPS removal entry point, so
12/// their callbacks live until the environment is destroyed; see
13/// [`HookKind::is_removable`].
14///
15/// After-module-defined is deliberately absent: CLIPS 6.4.2 invokes that list
16/// as `(* (void (*)(void *)) func)(theEnv)`, dropping the context argument the
17/// registration accepted, so the callback is called with the wrong arity and
18/// can never reach a Rust closure.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum HookKind {
21    /// Runs on `reset`, after the fact list and instances are cleared and
22    /// before deffacts and definstances are asserted.
23    Reset,
24    /// Runs on `clear`, after the constructs have been removed.
25    Clear,
26    /// Runs periodically while CLIPS executes, for example between rule firings.
27    Periodic,
28    /// Runs when CLIPS releases ephemeral values at a garbage-collection point.
29    Cleanup,
30    /// Runs before a binary image replaces the current constructs.
31    BeforeBinaryLoad,
32    /// Runs once a binary image has been loaded.
33    AfterBinaryLoad,
34    /// Runs when a binary load is abandoned part-way through.
35    AbortBinaryLoad,
36    /// Runs whenever the current module changes.
37    AfterModuleChange,
38}
39
40impl HookKind {
41    /// Whether CLIPS offers a way to unregister this hook before the
42    /// environment is destroyed.
43    pub fn is_removable(self) -> bool {
44        matches!(
45            self,
46            Self::Reset | Self::Clear | Self::Periodic | Self::Cleanup
47        )
48    }
49}
50
51/// Which veto hook a callback answers.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum ReadyHookKind {
54    /// Vetoes `clear`.
55    Clear,
56    /// Vetoes discarding the current constructs for a binary load.
57    ClearForBinaryLoad,
58}
59
60impl ReadyHookKind {
61    /// Whether CLIPS offers a way to unregister this hook before the
62    /// environment is destroyed.
63    pub fn is_removable(self) -> bool {
64        matches!(self, Self::Clear)
65    }
66}
67
68/// Which fact-lifecycle event a callback observes.
69///
70/// CLIPS has no matching public registry for instances; instance creation and
71/// deletion are observable only through message handlers and pattern matching.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum FactEventKind {
74    /// A fact was added to the fact list.
75    Asserted,
76    /// A fact was removed from the fact list.
77    Retracted,
78    /// A fact's slots were changed, which CLIPS reports as two calls. See
79    /// [`FactChange`].
80    Modified,
81}
82
83/// A fact identified for a lifecycle callback.
84///
85/// The fact itself is not handed out: during these callbacks CLIPS is part-way
86/// through changing the fact list, and a retained handle taken here could
87/// outlive the operation. The identity and relation are copied instead.
88#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct FactEvent {
90    /// The fact index, the number CLIPS prints as `f-<n>`.
91    pub index: i64,
92    /// The fact's relation name, that is, its deftemplate name.
93    pub relation: String,
94}
95
96/// What happened to a fact, as reported to a fact hook.
97///
98/// A modification is reported as two separate calls, matching how CLIPS
99/// invokes the hook: once for the fact being replaced and once for its
100/// replacement. CLIPS reuses the fact index across a modification, so both
101/// calls carry the same index.
102#[derive(Clone, Debug, Eq, PartialEq)]
103pub enum FactChange {
104    /// The fact was asserted.
105    Asserted(FactEvent),
106    /// The fact was retracted.
107    Retracted(FactEvent),
108    /// The fact being replaced by a modification.
109    ModifiedFrom(FactEvent),
110    /// The replacement produced by a modification.
111    ModifiedTo(FactEvent),
112}
113
114impl FactChange {
115    /// The fact this change concerns, whichever kind of change it is.
116    pub fn fact(&self) -> &FactEvent {
117        match self {
118            Self::Asserted(fact)
119            | Self::Retracted(fact)
120            | Self::ModifiedFrom(fact)
121            | Self::ModifiedTo(fact) => fact,
122        }
123    }
124}
125
126/// A parser diagnostic, with every string copied out of CLIPS's buffers.
127#[derive(Clone, Debug, Eq, PartialEq)]
128pub struct ParserDiagnostic {
129    /// The file being parsed, empty when parsing from a string.
130    pub file: String,
131    /// The warning text, empty when the diagnostic is an error.
132    pub warning: String,
133    /// The error text, empty when the diagnostic is a warning.
134    pub error: String,
135    /// The line the diagnostic refers to, or -1 when CLIPS reports none.
136    pub line: i64,
137}
138
139/// Whether a rule-fire callback runs before or after the rule's actions.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum RuleFirePhase {
142    /// Before the rule's right-hand side runs.
143    Before,
144    /// After the rule's right-hand side has run.
145    After,
146}
147
148/// Why registering or removing a hook failed.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum HookError {
151    /// The hook name contained a NUL byte.
152    InteriorNul,
153    /// A hook of that name is already registered. CLIPS would accept the
154    /// duplicate but could not then remove it reliably, so it is refused.
155    NameInUse,
156    /// No hook of that name is registered.
157    NotFound,
158}
159impl std::fmt::Display for HookError {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        write!(f, "CLIPS lifecycle hook error: {self:?}")
162    }
163}
164impl std::error::Error for HookError {}
165
166pub(crate) struct VoidContext {
167    callback: RefCell<Box<dyn FnMut()>>,
168}
169pub(crate) struct ReadyContext {
170    callback: RefCell<Box<dyn FnMut() -> bool>>,
171}
172
173type RuleFiredCallback = Box<dyn FnMut(&str)>;
174
175pub(crate) struct RuleFiredContext {
176    callback: RefCell<RuleFiredCallback>,
177}
178
179pub(crate) enum HookEntry {
180    Void {
181        name: CString,
182        kind: HookKind,
183        _context: Box<VoidContext>,
184    },
185    Ready {
186        name: CString,
187        kind: ReadyHookKind,
188        _context: Box<ReadyContext>,
189    },
190    RuleFired {
191        name: CString,
192        phase: RuleFirePhase,
193        _context: Box<RuleFiredContext>,
194    },
195    Fact {
196        name: CString,
197        kind: FactEventKind,
198        _context: Box<FactContext>,
199    },
200    Save {
201        name: CString,
202        _context: Box<SaveContext>,
203    },
204}
205
206type FactCallback = Box<dyn FnMut(&FactChange)>;
207type SaveCallback = Box<dyn FnMut(&str, &str)>;
208
209pub(crate) struct FactContext {
210    callback: RefCell<FactCallback>,
211}
212pub(crate) struct SaveContext {
213    callback: RefCell<SaveCallback>,
214}
215
216impl HookEntry {
217    pub(crate) fn void<F>(
218        environment: *mut ffi::Environment,
219        name: &str,
220        kind: HookKind,
221        priority: i32,
222        callback: F,
223    ) -> Result<Self, HookError>
224    where
225        F: FnMut() + 'static,
226    {
227        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
228        let context = Box::new(VoidContext {
229            callback: RefCell::new(Box::new(callback)),
230        });
231        let pointer = (&*context as *const VoidContext)
232            .cast_mut()
233            .cast::<c_void>();
234        let callback = Some(void_trampoline as ffi::VoidCallFunction);
235        // CLIPS reports success only for the hook families that also support
236        // removal; the rest register unconditionally and return nothing.
237        let added = unsafe {
238            match kind {
239                HookKind::Reset => {
240                    ffi::AddResetFunction(environment, name.as_ptr(), callback, priority, pointer)
241                }
242                HookKind::Clear => {
243                    ffi::AddClearFunction(environment, name.as_ptr(), callback, priority, pointer)
244                }
245                HookKind::Periodic => ffi::AddPeriodicFunction(
246                    environment,
247                    name.as_ptr(),
248                    callback,
249                    priority,
250                    pointer,
251                ),
252                HookKind::Cleanup => {
253                    ffi::AddCleanupFunction(environment, name.as_ptr(), callback, priority, pointer)
254                }
255                HookKind::BeforeBinaryLoad => {
256                    ffi::AddBeforeBloadFunction(
257                        environment,
258                        name.as_ptr(),
259                        callback,
260                        priority,
261                        pointer,
262                    );
263                    true
264                }
265                HookKind::AfterBinaryLoad => {
266                    ffi::AddAfterBloadFunction(
267                        environment,
268                        name.as_ptr(),
269                        callback,
270                        priority,
271                        pointer,
272                    );
273                    true
274                }
275                HookKind::AbortBinaryLoad => {
276                    ffi::AddAbortBloadFunction(
277                        environment,
278                        name.as_ptr(),
279                        callback,
280                        priority,
281                        pointer,
282                    );
283                    true
284                }
285                HookKind::AfterModuleChange => {
286                    ffi::AddAfterModuleChangeFunction(
287                        environment,
288                        name.as_ptr(),
289                        callback,
290                        priority,
291                        pointer,
292                    );
293                    true
294                }
295            }
296        };
297        added
298            .then_some(Self::Void {
299                name,
300                kind,
301                _context: context,
302            })
303            .ok_or(HookError::NameInUse)
304    }
305
306    pub(crate) fn ready<F>(
307        environment: *mut ffi::Environment,
308        name: &str,
309        kind: ReadyHookKind,
310        priority: i32,
311        callback: F,
312    ) -> Result<Self, HookError>
313    where
314        F: FnMut() -> bool + 'static,
315    {
316        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
317        let context = Box::new(ReadyContext {
318            callback: RefCell::new(Box::new(callback)),
319        });
320        let pointer = (&*context as *const ReadyContext)
321            .cast_mut()
322            .cast::<c_void>();
323        let callback = Some(ready_trampoline as ffi::BoolCallFunction);
324        let added = unsafe {
325            match kind {
326                ReadyHookKind::Clear => ffi::AddClearReadyFunction(
327                    environment,
328                    name.as_ptr(),
329                    callback,
330                    priority,
331                    pointer,
332                ),
333                ReadyHookKind::ClearForBinaryLoad => {
334                    ffi::AddClearBloadReadyFunction(
335                        environment,
336                        name.as_ptr(),
337                        callback,
338                        priority,
339                        pointer,
340                    );
341                    true
342                }
343            }
344        };
345        added
346            .then_some(Self::Ready {
347                name,
348                kind,
349                _context: context,
350            })
351            .ok_or(HookError::NameInUse)
352    }
353
354    pub(crate) fn rule_fired<F>(
355        environment: *mut ffi::Environment,
356        name: &str,
357        phase: RuleFirePhase,
358        priority: i32,
359        callback: F,
360    ) -> Result<Self, HookError>
361    where
362        F: FnMut(&str) + 'static,
363    {
364        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
365        let context = Box::new(RuleFiredContext {
366            callback: RefCell::new(Box::new(callback)),
367        });
368        let pointer = (&*context as *const RuleFiredContext)
369            .cast_mut()
370            .cast::<c_void>();
371        let callback = Some(rule_fired_trampoline as ffi::RuleFiredFunction);
372        let added = unsafe {
373            match phase {
374                RuleFirePhase::Before => ffi::AddBeforeRuleFiresFunction(
375                    environment,
376                    name.as_ptr(),
377                    callback,
378                    priority,
379                    pointer,
380                ),
381                RuleFirePhase::After => ffi::AddAfterRuleFiresFunction(
382                    environment,
383                    name.as_ptr(),
384                    callback,
385                    priority,
386                    pointer,
387                ),
388            }
389        };
390        added
391            .then_some(Self::RuleFired {
392                name,
393                phase,
394                _context: context,
395            })
396            .ok_or(HookError::NameInUse)
397    }
398
399    pub(crate) fn fact<F>(
400        environment: *mut ffi::Environment,
401        name: &str,
402        kind: FactEventKind,
403        priority: i32,
404        callback: F,
405    ) -> Result<Self, HookError>
406    where
407        F: FnMut(&FactChange) + 'static,
408    {
409        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
410        let context = Box::new(FactContext {
411            callback: RefCell::new(Box::new(callback)),
412        });
413        let pointer = (&*context as *const FactContext)
414            .cast_mut()
415            .cast::<c_void>();
416        let added = unsafe {
417            match kind {
418                FactEventKind::Asserted => ffi::AddAssertFunction(
419                    environment,
420                    name.as_ptr(),
421                    Some(assert_trampoline),
422                    priority,
423                    pointer,
424                ),
425                FactEventKind::Retracted => ffi::AddRetractFunction(
426                    environment,
427                    name.as_ptr(),
428                    Some(retract_trampoline),
429                    priority,
430                    pointer,
431                ),
432                FactEventKind::Modified => ffi::AddModifyFunction(
433                    environment,
434                    name.as_ptr(),
435                    Some(modify_trampoline),
436                    priority,
437                    pointer,
438                ),
439            }
440        };
441        added
442            .then_some(Self::Fact {
443                name,
444                kind,
445                _context: context,
446            })
447            .ok_or(HookError::NameInUse)
448    }
449
450    pub(crate) fn save<F>(
451        environment: *mut ffi::Environment,
452        name: &str,
453        priority: i32,
454        callback: F,
455    ) -> Result<Self, HookError>
456    where
457        F: FnMut(&str, &str) + 'static,
458    {
459        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
460        let context = Box::new(SaveContext {
461            callback: RefCell::new(Box::new(callback)),
462        });
463        let pointer = (&*context as *const SaveContext)
464            .cast_mut()
465            .cast::<c_void>();
466        unsafe {
467            ffi::AddSaveFunction(
468                environment,
469                name.as_ptr(),
470                Some(save_trampoline),
471                priority,
472                pointer,
473            )
474        }
475        .then_some(Self::Save {
476            name,
477            _context: context,
478        })
479        .ok_or(HookError::NameInUse)
480    }
481
482    pub(crate) fn name(&self) -> &[u8] {
483        match self {
484            Self::Void { name, .. }
485            | Self::Ready { name, .. }
486            | Self::RuleFired { name, .. }
487            | Self::Fact { name, .. }
488            | Self::Save { name, .. } => name.as_bytes(),
489        }
490    }
491    /// Unregisters the hook, returning false for the families CLIPS provides no
492    /// removal entry point for. Those keep their callback allocation until the
493    /// environment is destroyed.
494    pub(crate) fn unregister(&self, environment: *mut ffi::Environment) -> bool {
495        unsafe {
496            match self {
497                Self::Void { name, kind, .. } => match kind {
498                    HookKind::Reset => ffi::RemoveResetFunction(environment, name.as_ptr()),
499                    HookKind::Clear => ffi::RemoveClearFunction(environment, name.as_ptr()),
500                    HookKind::Periodic => ffi::RemovePeriodicFunction(environment, name.as_ptr()),
501                    HookKind::Cleanup => ffi::RemoveCleanupFunction(environment, name.as_ptr()),
502                    HookKind::BeforeBinaryLoad
503                    | HookKind::AfterBinaryLoad
504                    | HookKind::AbortBinaryLoad
505                    | HookKind::AfterModuleChange => false,
506                },
507                Self::Ready { name, kind, .. } => match kind {
508                    ReadyHookKind::Clear => {
509                        ffi::RemoveClearReadyFunction(environment, name.as_ptr())
510                    }
511                    ReadyHookKind::ClearForBinaryLoad => false,
512                },
513                Self::RuleFired { name, phase, .. } => match phase {
514                    RuleFirePhase::Before => {
515                        ffi::RemoveBeforeRuleFiresFunction(environment, name.as_ptr())
516                    }
517                    RuleFirePhase::After => {
518                        ffi::RemoveAfterRuleFiresFunction(environment, name.as_ptr())
519                    }
520                },
521                Self::Fact { name, kind, .. } => match kind {
522                    FactEventKind::Asserted => {
523                        ffi::RemoveAssertFunction(environment, name.as_ptr())
524                    }
525                    FactEventKind::Retracted => {
526                        ffi::RemoveRetractFunction(environment, name.as_ptr())
527                    }
528                    FactEventKind::Modified => {
529                        ffi::RemoveModifyFunction(environment, name.as_ptr())
530                    }
531                },
532                Self::Save { name, .. } => ffi::RemoveSaveFunction(environment, name.as_ptr()),
533            }
534        }
535    }
536}
537
538/// Copies the identity of a fact CLIPS is part-way through changing.
539unsafe fn fact_event(fact: *mut ffi::Fact) -> Option<FactEvent> {
540    if fact.is_null() {
541        return None;
542    }
543    let lexeme = unsafe { ffi::FactRelation(fact) };
544    let relation = if lexeme.is_null() {
545        String::new()
546    } else {
547        unsafe { std::ffi::CStr::from_ptr((*lexeme).contents) }
548            .to_string_lossy()
549            .into_owned()
550    };
551    Some(FactEvent {
552        index: unsafe { ffi::FactIndex(fact) },
553        relation,
554    })
555}
556
557unsafe fn dispatch_fact(
558    raw: *mut c_void,
559    change: impl FnOnce(FactEvent) -> FactChange,
560    fact: *mut ffi::Fact,
561) {
562    let _ = catch_unwind(AssertUnwindSafe(|| {
563        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<FactContext>() }) else {
564            return;
565        };
566        let Some(event) = (unsafe { fact_event(fact) }) else {
567            return;
568        };
569        if let Ok(mut callback) = context.callback.try_borrow_mut() {
570            callback(&change(event));
571        }
572    }));
573}
574
575unsafe extern "C" fn assert_trampoline(
576    _environment: *mut ffi::Environment,
577    fact: *mut c_void,
578    raw: *mut c_void,
579) {
580    unsafe { dispatch_fact(raw, FactChange::Asserted, fact.cast()) }
581}
582
583unsafe extern "C" fn retract_trampoline(
584    _environment: *mut ffi::Environment,
585    fact: *mut c_void,
586    raw: *mut c_void,
587) {
588    unsafe { dispatch_fact(raw, FactChange::Retracted, fact.cast()) }
589}
590
591// CLIPS reports a modification as two calls: `(old, NULL)` for the fact being
592// replaced and `(NULL, new)` for its replacement.
593unsafe extern "C" fn modify_trampoline(
594    _environment: *mut ffi::Environment,
595    old: *mut ffi::Fact,
596    new: *mut ffi::Fact,
597    raw: *mut c_void,
598) {
599    if !old.is_null() {
600        unsafe { dispatch_fact(raw, FactChange::ModifiedFrom, old) }
601    }
602    if !new.is_null() {
603        unsafe { dispatch_fact(raw, FactChange::ModifiedTo, new) }
604    }
605}
606
607unsafe extern "C" fn save_trampoline(
608    _environment: *mut ffi::Environment,
609    module: *mut ffi::Defmodule,
610    logical_name: *const std::ffi::c_char,
611    raw: *mut c_void,
612) {
613    let _ = catch_unwind(AssertUnwindSafe(|| {
614        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<SaveContext>() }) else {
615            return;
616        };
617        let module = if module.is_null() {
618            String::new()
619        } else {
620            unsafe { std::ffi::CStr::from_ptr(ffi::DefmoduleName(module)) }
621                .to_string_lossy()
622                .into_owned()
623        };
624        let logical_name = if logical_name.is_null() {
625            String::new()
626        } else {
627            unsafe { std::ffi::CStr::from_ptr(logical_name) }
628                .to_string_lossy()
629                .into_owned()
630        };
631        if let Ok(mut callback) = context.callback.try_borrow_mut() {
632            callback(&module, &logical_name);
633        }
634    }));
635}
636
637/// The single parser-error callback an environment may have installed.
638type ParserErrorCallback = Box<dyn FnMut(&ParserDiagnostic)>;
639
640pub(crate) struct ParserErrorContext {
641    callback: RefCell<ParserErrorCallback>,
642}
643
644impl ParserErrorContext {
645    pub(crate) fn install<F>(environment: *mut ffi::Environment, callback: F) -> Box<Self>
646    where
647        F: FnMut(&ParserDiagnostic) + 'static,
648    {
649        let context = Box::new(Self {
650            callback: RefCell::new(Box::new(callback)),
651        });
652        let pointer = (&*context as *const Self).cast_mut().cast::<c_void>();
653        unsafe {
654            ffi::SetParserErrorCallback(environment, Some(parser_error_trampoline), pointer);
655        }
656        context
657    }
658
659    pub(crate) fn clear(environment: *mut ffi::Environment) {
660        unsafe { ffi::SetParserErrorCallback(environment, None, std::ptr::null_mut()) };
661    }
662}
663
664unsafe extern "C" fn parser_error_trampoline(
665    _environment: *mut ffi::Environment,
666    file: *const std::ffi::c_char,
667    warning: *const std::ffi::c_char,
668    error: *const std::ffi::c_char,
669    line: std::ffi::c_long,
670    raw: *mut c_void,
671) {
672    let _ = catch_unwind(AssertUnwindSafe(|| {
673        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<ParserErrorContext>() })
674        else {
675            return;
676        };
677        let text = |value: *const std::ffi::c_char| {
678            if value.is_null() {
679                String::new()
680            } else {
681                unsafe { std::ffi::CStr::from_ptr(value) }
682                    .to_string_lossy()
683                    .into_owned()
684            }
685        };
686        // `long` is 32 bits on Windows and 64 bits on Unix, so the widening
687        // is a no-op only on some targets.
688        #[allow(clippy::useless_conversion)]
689        let line = i64::from(line);
690        let diagnostic = ParserDiagnostic {
691            file: text(file),
692            warning: text(warning),
693            error: text(error),
694            line,
695        };
696        if let Ok(mut callback) = context.callback.try_borrow_mut() {
697            callback(&diagnostic);
698        }
699    }));
700}
701
702unsafe extern "C" fn rule_fired_trampoline(
703    _environment: *mut ffi::Environment,
704    activation: *mut ffi::Activation,
705    raw: *mut c_void,
706) {
707    let _ = catch_unwind(AssertUnwindSafe(|| {
708        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<RuleFiredContext>() })
709        else {
710            return;
711        };
712        // CLIPS passes a null activation to the after-fire hook once the
713        // activation has been removed from the agenda.
714        let name = if activation.is_null() {
715            String::new()
716        } else {
717            unsafe { std::ffi::CStr::from_ptr(ffi::ActivationRuleName(activation)) }
718                .to_string_lossy()
719                .into_owned()
720        };
721        if let Ok(mut callback) = context.callback.try_borrow_mut() {
722            callback(&name);
723        }
724    }));
725}
726
727unsafe extern "C" fn void_trampoline(_environment: *mut ffi::Environment, raw: *mut c_void) {
728    let _ = catch_unwind(AssertUnwindSafe(|| {
729        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<VoidContext>() }) else {
730            return;
731        };
732        if let Ok(mut callback) = context.callback.try_borrow_mut() {
733            callback();
734        }
735    }));
736}
737
738unsafe extern "C" fn ready_trampoline(
739    _environment: *mut ffi::Environment,
740    raw: *mut c_void,
741) -> bool {
742    catch_unwind(AssertUnwindSafe(|| {
743        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<ReadyContext>() })
744        else {
745            return false;
746        };
747        context
748            .callback
749            .try_borrow_mut()
750            .map(|mut callback| callback())
751            .unwrap_or(false)
752    }))
753    .unwrap_or(false)
754}