use std::cell::RefCell;
use std::ffi::{CString, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
use crate::ffi;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookKind {
Reset,
Clear,
Periodic,
Cleanup,
BeforeBinaryLoad,
AfterBinaryLoad,
AbortBinaryLoad,
AfterModuleChange,
}
impl HookKind {
pub fn is_removable(self) -> bool {
matches!(
self,
Self::Reset | Self::Clear | Self::Periodic | Self::Cleanup
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadyHookKind {
Clear,
ClearForBinaryLoad,
}
impl ReadyHookKind {
pub fn is_removable(self) -> bool {
matches!(self, Self::Clear)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FactEventKind {
Asserted,
Retracted,
Modified,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FactEvent {
pub index: i64,
pub relation: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FactChange {
Asserted(FactEvent),
Retracted(FactEvent),
ModifiedFrom(FactEvent),
ModifiedTo(FactEvent),
}
impl FactChange {
pub fn fact(&self) -> &FactEvent {
match self {
Self::Asserted(fact)
| Self::Retracted(fact)
| Self::ModifiedFrom(fact)
| Self::ModifiedTo(fact) => fact,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParserDiagnostic {
pub file: String,
pub warning: String,
pub error: String,
pub line: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleFirePhase {
Before,
After,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HookError {
InteriorNul,
NameInUse,
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);
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(),
}
}
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()),
}
}
}
}
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()) }
}
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);
}
}));
}
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()
}
};
#[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;
};
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)
}