clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! Panic-contained lifecycle hooks owned by a CLIPS environment.

use std::cell::RefCell;
use std::ffi::{CString, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::ffi;

/// A CLIPS lifecycle event a Rust callback can be attached to.
///
/// The binary-load and module variants have no CLIPS removal entry point, so
/// their callbacks live until the environment is destroyed; see
/// [`HookKind::is_removable`].
///
/// After-module-defined is deliberately absent: CLIPS 6.4.2 invokes that list
/// as `(* (void (*)(void *)) func)(theEnv)`, dropping the context argument the
/// registration accepted, so the callback is called with the wrong arity and
/// can never reach a Rust closure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookKind {
    /// Runs on `reset`, after the fact list and instances are cleared and
    /// before deffacts and definstances are asserted.
    Reset,
    /// Runs on `clear`, after the constructs have been removed.
    Clear,
    /// Runs periodically while CLIPS executes, for example between rule firings.
    Periodic,
    /// Runs when CLIPS releases ephemeral values at a garbage-collection point.
    Cleanup,
    /// Runs before a binary image replaces the current constructs.
    BeforeBinaryLoad,
    /// Runs once a binary image has been loaded.
    AfterBinaryLoad,
    /// Runs when a binary load is abandoned part-way through.
    AbortBinaryLoad,
    /// Runs whenever the current module changes.
    AfterModuleChange,
}

impl HookKind {
    /// Whether CLIPS offers a way to unregister this hook before the
    /// environment is destroyed.
    pub fn is_removable(self) -> bool {
        matches!(
            self,
            Self::Reset | Self::Clear | Self::Periodic | Self::Cleanup
        )
    }
}

/// Which veto hook a callback answers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadyHookKind {
    /// Vetoes `clear`.
    Clear,
    /// Vetoes discarding the current constructs for a binary load.
    ClearForBinaryLoad,
}

impl ReadyHookKind {
    /// Whether CLIPS offers a way to unregister this hook before the
    /// environment is destroyed.
    pub fn is_removable(self) -> bool {
        matches!(self, Self::Clear)
    }
}

/// Which fact-lifecycle event a callback observes.
///
/// CLIPS has no matching public registry for instances; instance creation and
/// deletion are observable only through message handlers and pattern matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactEventKind {
    /// A fact was added to the fact list.
    Asserted,
    /// A fact was removed from the fact list.
    Retracted,
    /// A fact's slots were changed, which CLIPS reports as two calls. See
    /// [`FactChange`].
    Modified,
}

/// A fact identified for a lifecycle callback.
///
/// The fact itself is not handed out: during these callbacks CLIPS is part-way
/// through changing the fact list, and a retained handle taken here could
/// outlive the operation. The identity and relation are copied instead.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FactEvent {
    /// The fact index, the number CLIPS prints as `f-<n>`.
    pub index: i64,
    /// The fact's relation name, that is, its deftemplate name.
    pub relation: String,
}

/// What happened to a fact, as reported to a fact hook.
///
/// A modification is reported as two separate calls, matching how CLIPS
/// invokes the hook: once for the fact being replaced and once for its
/// replacement. CLIPS reuses the fact index across a modification, so both
/// calls carry the same index.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FactChange {
    /// The fact was asserted.
    Asserted(FactEvent),
    /// The fact was retracted.
    Retracted(FactEvent),
    /// The fact being replaced by a modification.
    ModifiedFrom(FactEvent),
    /// The replacement produced by a modification.
    ModifiedTo(FactEvent),
}

impl FactChange {
    /// The fact this change concerns, whichever kind of change it is.
    pub fn fact(&self) -> &FactEvent {
        match self {
            Self::Asserted(fact)
            | Self::Retracted(fact)
            | Self::ModifiedFrom(fact)
            | Self::ModifiedTo(fact) => fact,
        }
    }
}

/// A parser diagnostic, with every string copied out of CLIPS's buffers.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParserDiagnostic {
    /// The file being parsed, empty when parsing from a string.
    pub file: String,
    /// The warning text, empty when the diagnostic is an error.
    pub warning: String,
    /// The error text, empty when the diagnostic is a warning.
    pub error: String,
    /// The line the diagnostic refers to, or -1 when CLIPS reports none.
    pub line: i64,
}

/// Whether a rule-fire callback runs before or after the rule's actions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleFirePhase {
    /// Before the rule's right-hand side runs.
    Before,
    /// After the rule's right-hand side has run.
    After,
}

/// Why registering or removing a hook failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookError {
    /// The hook name contained a NUL byte.
    InteriorNul,
    /// A hook of that name is already registered. CLIPS would accept the
    /// duplicate but could not then remove it reliably, so it is refused.
    NameInUse,
    /// No hook of that name is registered.
    NotFound,
}
impl std::fmt::Display for HookError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CLIPS lifecycle hook error: {self:?}")
    }
}
impl std::error::Error for HookError {}

pub(crate) struct VoidContext {
    callback: RefCell<Box<dyn FnMut()>>,
}
pub(crate) struct ReadyContext {
    callback: RefCell<Box<dyn FnMut() -> bool>>,
}

type RuleFiredCallback = Box<dyn FnMut(&str)>;

pub(crate) struct RuleFiredContext {
    callback: RefCell<RuleFiredCallback>,
}

pub(crate) enum HookEntry {
    Void {
        name: CString,
        kind: HookKind,
        _context: Box<VoidContext>,
    },
    Ready {
        name: CString,
        kind: ReadyHookKind,
        _context: Box<ReadyContext>,
    },
    RuleFired {
        name: CString,
        phase: RuleFirePhase,
        _context: Box<RuleFiredContext>,
    },
    Fact {
        name: CString,
        kind: FactEventKind,
        _context: Box<FactContext>,
    },
    Save {
        name: CString,
        _context: Box<SaveContext>,
    },
}

type FactCallback = Box<dyn FnMut(&FactChange)>;
type SaveCallback = Box<dyn FnMut(&str, &str)>;

pub(crate) struct FactContext {
    callback: RefCell<FactCallback>,
}
pub(crate) struct SaveContext {
    callback: RefCell<SaveCallback>,
}

impl HookEntry {
    pub(crate) fn void<F>(
        environment: *mut ffi::Environment,
        name: &str,
        kind: HookKind,
        priority: i32,
        callback: F,
    ) -> Result<Self, HookError>
    where
        F: FnMut() + 'static,
    {
        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
        let context = Box::new(VoidContext {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const VoidContext)
            .cast_mut()
            .cast::<c_void>();
        let callback = Some(void_trampoline as ffi::VoidCallFunction);
        // CLIPS reports success only for the hook families that also support
        // removal; the rest register unconditionally and return nothing.
        let added = unsafe {
            match kind {
                HookKind::Reset => {
                    ffi::AddResetFunction(environment, name.as_ptr(), callback, priority, pointer)
                }
                HookKind::Clear => {
                    ffi::AddClearFunction(environment, name.as_ptr(), callback, priority, pointer)
                }
                HookKind::Periodic => ffi::AddPeriodicFunction(
                    environment,
                    name.as_ptr(),
                    callback,
                    priority,
                    pointer,
                ),
                HookKind::Cleanup => {
                    ffi::AddCleanupFunction(environment, name.as_ptr(), callback, priority, pointer)
                }
                HookKind::BeforeBinaryLoad => {
                    ffi::AddBeforeBloadFunction(
                        environment,
                        name.as_ptr(),
                        callback,
                        priority,
                        pointer,
                    );
                    true
                }
                HookKind::AfterBinaryLoad => {
                    ffi::AddAfterBloadFunction(
                        environment,
                        name.as_ptr(),
                        callback,
                        priority,
                        pointer,
                    );
                    true
                }
                HookKind::AbortBinaryLoad => {
                    ffi::AddAbortBloadFunction(
                        environment,
                        name.as_ptr(),
                        callback,
                        priority,
                        pointer,
                    );
                    true
                }
                HookKind::AfterModuleChange => {
                    ffi::AddAfterModuleChangeFunction(
                        environment,
                        name.as_ptr(),
                        callback,
                        priority,
                        pointer,
                    );
                    true
                }
            }
        };
        added
            .then_some(Self::Void {
                name,
                kind,
                _context: context,
            })
            .ok_or(HookError::NameInUse)
    }

    pub(crate) fn ready<F>(
        environment: *mut ffi::Environment,
        name: &str,
        kind: ReadyHookKind,
        priority: i32,
        callback: F,
    ) -> Result<Self, HookError>
    where
        F: FnMut() -> bool + 'static,
    {
        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
        let context = Box::new(ReadyContext {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const ReadyContext)
            .cast_mut()
            .cast::<c_void>();
        let callback = Some(ready_trampoline as ffi::BoolCallFunction);
        let added = unsafe {
            match kind {
                ReadyHookKind::Clear => ffi::AddClearReadyFunction(
                    environment,
                    name.as_ptr(),
                    callback,
                    priority,
                    pointer,
                ),
                ReadyHookKind::ClearForBinaryLoad => {
                    ffi::AddClearBloadReadyFunction(
                        environment,
                        name.as_ptr(),
                        callback,
                        priority,
                        pointer,
                    );
                    true
                }
            }
        };
        added
            .then_some(Self::Ready {
                name,
                kind,
                _context: context,
            })
            .ok_or(HookError::NameInUse)
    }

    pub(crate) fn rule_fired<F>(
        environment: *mut ffi::Environment,
        name: &str,
        phase: RuleFirePhase,
        priority: i32,
        callback: F,
    ) -> Result<Self, HookError>
    where
        F: FnMut(&str) + 'static,
    {
        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
        let context = Box::new(RuleFiredContext {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const RuleFiredContext)
            .cast_mut()
            .cast::<c_void>();
        let callback = Some(rule_fired_trampoline as ffi::RuleFiredFunction);
        let added = unsafe {
            match phase {
                RuleFirePhase::Before => ffi::AddBeforeRuleFiresFunction(
                    environment,
                    name.as_ptr(),
                    callback,
                    priority,
                    pointer,
                ),
                RuleFirePhase::After => ffi::AddAfterRuleFiresFunction(
                    environment,
                    name.as_ptr(),
                    callback,
                    priority,
                    pointer,
                ),
            }
        };
        added
            .then_some(Self::RuleFired {
                name,
                phase,
                _context: context,
            })
            .ok_or(HookError::NameInUse)
    }

    pub(crate) fn fact<F>(
        environment: *mut ffi::Environment,
        name: &str,
        kind: FactEventKind,
        priority: i32,
        callback: F,
    ) -> Result<Self, HookError>
    where
        F: FnMut(&FactChange) + 'static,
    {
        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
        let context = Box::new(FactContext {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const FactContext)
            .cast_mut()
            .cast::<c_void>();
        let added = unsafe {
            match kind {
                FactEventKind::Asserted => ffi::AddAssertFunction(
                    environment,
                    name.as_ptr(),
                    Some(assert_trampoline),
                    priority,
                    pointer,
                ),
                FactEventKind::Retracted => ffi::AddRetractFunction(
                    environment,
                    name.as_ptr(),
                    Some(retract_trampoline),
                    priority,
                    pointer,
                ),
                FactEventKind::Modified => ffi::AddModifyFunction(
                    environment,
                    name.as_ptr(),
                    Some(modify_trampoline),
                    priority,
                    pointer,
                ),
            }
        };
        added
            .then_some(Self::Fact {
                name,
                kind,
                _context: context,
            })
            .ok_or(HookError::NameInUse)
    }

    pub(crate) fn save<F>(
        environment: *mut ffi::Environment,
        name: &str,
        priority: i32,
        callback: F,
    ) -> Result<Self, HookError>
    where
        F: FnMut(&str, &str) + 'static,
    {
        let name = CString::new(name).map_err(|_| HookError::InteriorNul)?;
        let context = Box::new(SaveContext {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const SaveContext)
            .cast_mut()
            .cast::<c_void>();
        unsafe {
            ffi::AddSaveFunction(
                environment,
                name.as_ptr(),
                Some(save_trampoline),
                priority,
                pointer,
            )
        }
        .then_some(Self::Save {
            name,
            _context: context,
        })
        .ok_or(HookError::NameInUse)
    }

    pub(crate) fn name(&self) -> &[u8] {
        match self {
            Self::Void { name, .. }
            | Self::Ready { name, .. }
            | Self::RuleFired { name, .. }
            | Self::Fact { name, .. }
            | Self::Save { name, .. } => name.as_bytes(),
        }
    }
    /// Unregisters the hook, returning false for the families CLIPS provides no
    /// removal entry point for. Those keep their callback allocation until the
    /// environment is destroyed.
    pub(crate) fn unregister(&self, environment: *mut ffi::Environment) -> bool {
        unsafe {
            match self {
                Self::Void { name, kind, .. } => match kind {
                    HookKind::Reset => ffi::RemoveResetFunction(environment, name.as_ptr()),
                    HookKind::Clear => ffi::RemoveClearFunction(environment, name.as_ptr()),
                    HookKind::Periodic => ffi::RemovePeriodicFunction(environment, name.as_ptr()),
                    HookKind::Cleanup => ffi::RemoveCleanupFunction(environment, name.as_ptr()),
                    HookKind::BeforeBinaryLoad
                    | HookKind::AfterBinaryLoad
                    | HookKind::AbortBinaryLoad
                    | HookKind::AfterModuleChange => false,
                },
                Self::Ready { name, kind, .. } => match kind {
                    ReadyHookKind::Clear => {
                        ffi::RemoveClearReadyFunction(environment, name.as_ptr())
                    }
                    ReadyHookKind::ClearForBinaryLoad => false,
                },
                Self::RuleFired { name, phase, .. } => match phase {
                    RuleFirePhase::Before => {
                        ffi::RemoveBeforeRuleFiresFunction(environment, name.as_ptr())
                    }
                    RuleFirePhase::After => {
                        ffi::RemoveAfterRuleFiresFunction(environment, name.as_ptr())
                    }
                },
                Self::Fact { name, kind, .. } => match kind {
                    FactEventKind::Asserted => {
                        ffi::RemoveAssertFunction(environment, name.as_ptr())
                    }
                    FactEventKind::Retracted => {
                        ffi::RemoveRetractFunction(environment, name.as_ptr())
                    }
                    FactEventKind::Modified => {
                        ffi::RemoveModifyFunction(environment, name.as_ptr())
                    }
                },
                Self::Save { name, .. } => ffi::RemoveSaveFunction(environment, name.as_ptr()),
            }
        }
    }
}

/// Copies the identity of a fact CLIPS is part-way through changing.
unsafe fn fact_event(fact: *mut ffi::Fact) -> Option<FactEvent> {
    if fact.is_null() {
        return None;
    }
    let lexeme = unsafe { ffi::FactRelation(fact) };
    let relation = if lexeme.is_null() {
        String::new()
    } else {
        unsafe { std::ffi::CStr::from_ptr((*lexeme).contents) }
            .to_string_lossy()
            .into_owned()
    };
    Some(FactEvent {
        index: unsafe { ffi::FactIndex(fact) },
        relation,
    })
}

unsafe fn dispatch_fact(
    raw: *mut c_void,
    change: impl FnOnce(FactEvent) -> FactChange,
    fact: *mut ffi::Fact,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<FactContext>() }) else {
            return;
        };
        let Some(event) = (unsafe { fact_event(fact) }) else {
            return;
        };
        if let Ok(mut callback) = context.callback.try_borrow_mut() {
            callback(&change(event));
        }
    }));
}

unsafe extern "C" fn assert_trampoline(
    _environment: *mut ffi::Environment,
    fact: *mut c_void,
    raw: *mut c_void,
) {
    unsafe { dispatch_fact(raw, FactChange::Asserted, fact.cast()) }
}

unsafe extern "C" fn retract_trampoline(
    _environment: *mut ffi::Environment,
    fact: *mut c_void,
    raw: *mut c_void,
) {
    unsafe { dispatch_fact(raw, FactChange::Retracted, fact.cast()) }
}

// CLIPS reports a modification as two calls: `(old, NULL)` for the fact being
// replaced and `(NULL, new)` for its replacement.
unsafe extern "C" fn modify_trampoline(
    _environment: *mut ffi::Environment,
    old: *mut ffi::Fact,
    new: *mut ffi::Fact,
    raw: *mut c_void,
) {
    if !old.is_null() {
        unsafe { dispatch_fact(raw, FactChange::ModifiedFrom, old) }
    }
    if !new.is_null() {
        unsafe { dispatch_fact(raw, FactChange::ModifiedTo, new) }
    }
}

unsafe extern "C" fn save_trampoline(
    _environment: *mut ffi::Environment,
    module: *mut ffi::Defmodule,
    logical_name: *const std::ffi::c_char,
    raw: *mut c_void,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<SaveContext>() }) else {
            return;
        };
        let module = if module.is_null() {
            String::new()
        } else {
            unsafe { std::ffi::CStr::from_ptr(ffi::DefmoduleName(module)) }
                .to_string_lossy()
                .into_owned()
        };
        let logical_name = if logical_name.is_null() {
            String::new()
        } else {
            unsafe { std::ffi::CStr::from_ptr(logical_name) }
                .to_string_lossy()
                .into_owned()
        };
        if let Ok(mut callback) = context.callback.try_borrow_mut() {
            callback(&module, &logical_name);
        }
    }));
}

/// The single parser-error callback an environment may have installed.
type ParserErrorCallback = Box<dyn FnMut(&ParserDiagnostic)>;

pub(crate) struct ParserErrorContext {
    callback: RefCell<ParserErrorCallback>,
}

impl ParserErrorContext {
    pub(crate) fn install<F>(environment: *mut ffi::Environment, callback: F) -> Box<Self>
    where
        F: FnMut(&ParserDiagnostic) + 'static,
    {
        let context = Box::new(Self {
            callback: RefCell::new(Box::new(callback)),
        });
        let pointer = (&*context as *const Self).cast_mut().cast::<c_void>();
        unsafe {
            ffi::SetParserErrorCallback(environment, Some(parser_error_trampoline), pointer);
        }
        context
    }

    pub(crate) fn clear(environment: *mut ffi::Environment) {
        unsafe { ffi::SetParserErrorCallback(environment, None, std::ptr::null_mut()) };
    }
}

unsafe extern "C" fn parser_error_trampoline(
    _environment: *mut ffi::Environment,
    file: *const std::ffi::c_char,
    warning: *const std::ffi::c_char,
    error: *const std::ffi::c_char,
    line: std::ffi::c_long,
    raw: *mut c_void,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<ParserErrorContext>() })
        else {
            return;
        };
        let text = |value: *const std::ffi::c_char| {
            if value.is_null() {
                String::new()
            } else {
                unsafe { std::ffi::CStr::from_ptr(value) }
                    .to_string_lossy()
                    .into_owned()
            }
        };
        // `long` is 32 bits on Windows and 64 bits on Unix, so the widening
        // is a no-op only on some targets.
        #[allow(clippy::useless_conversion)]
        let line = i64::from(line);
        let diagnostic = ParserDiagnostic {
            file: text(file),
            warning: text(warning),
            error: text(error),
            line,
        };
        if let Ok(mut callback) = context.callback.try_borrow_mut() {
            callback(&diagnostic);
        }
    }));
}

unsafe extern "C" fn rule_fired_trampoline(
    _environment: *mut ffi::Environment,
    activation: *mut ffi::Activation,
    raw: *mut c_void,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<RuleFiredContext>() })
        else {
            return;
        };
        // CLIPS passes a null activation to the after-fire hook once the
        // activation has been removed from the agenda.
        let name = if activation.is_null() {
            String::new()
        } else {
            unsafe { std::ffi::CStr::from_ptr(ffi::ActivationRuleName(activation)) }
                .to_string_lossy()
                .into_owned()
        };
        if let Ok(mut callback) = context.callback.try_borrow_mut() {
            callback(&name);
        }
    }));
}

unsafe extern "C" fn void_trampoline(_environment: *mut ffi::Environment, raw: *mut c_void) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<VoidContext>() }) else {
            return;
        };
        if let Ok(mut callback) = context.callback.try_borrow_mut() {
            callback();
        }
    }));
}

unsafe extern "C" fn ready_trampoline(
    _environment: *mut ffi::Environment,
    raw: *mut c_void,
) -> bool {
    catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (!raw.is_null()).then(|| unsafe { &*raw.cast::<ReadyContext>() })
        else {
            return false;
        };
        context
            .callback
            .try_borrow_mut()
            .map(|mut callback| callback())
            .unwrap_or(false)
    }))
    .unwrap_or(false)
}