use std::cell::RefCell;
use std::ffi::{CStr, CString, c_void};
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr::NonNull;
use crate::ffi;
const ANY_TYPE_BITS: u32 = (1 << 11) - 1;
macro_rules! address_token {
($($name:ident($target:ty)),+ $(,)?) => {$(
/// An address CLIPS passed into the current UDF invocation.
///
/// The token is opaque and has no accessors: it exists so a UDF can
/// hand an address CLIPS gave it straight back as its result. Its
/// lifetime is the invocation that produced it, which is what stops a
/// `'static` callback from storing one and returning it after CLIPS
/// has freed the referent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct $name<'call> {
pub(crate) raw: NonNull<$target>,
pub(crate) marker: PhantomData<&'call ()>,
}
impl<'call> $name<'call> {
fn new(raw: *mut $target) -> Option<Self> {
NonNull::new(raw).map(|raw| Self { raw, marker: PhantomData })
}
}
)+};
}
address_token!(
UdfFact(ffi::Fact),
UdfInstance(ffi::Instance),
UdfExternalAddress(c_void),
);
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum UdfValue<'call> {
Float(f64),
Integer(i64),
Symbol(String),
String(String),
Boolean(bool),
InstanceName(String),
Multifield(Vec<UdfValue<'call>>),
FactAddress(UdfFact<'call>),
InstanceAddress(UdfInstance<'call>),
ExternalAddress(UdfExternalAddress<'call>),
Void,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum UdfReturn<'call> {
Float(f64),
Integer(i64),
Symbol(String),
String(String),
Boolean(bool),
InstanceName(String),
Multifield(Vec<UdfReturn<'call>>),
FactAddress(UdfFact<'call>),
InstanceAddress(UdfInstance<'call>),
ExternalAddress(UdfExternalAddress<'call>),
Void,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UdfType {
Any,
Boolean,
Float,
ExternalAddress,
FactAddress,
InstanceAddress,
Integer,
Multifield,
InstanceName,
String,
Symbol,
Void,
}
impl UdfType {
fn code(self) -> char {
match self {
Self::Any => '*',
Self::Boolean => 'b',
Self::Float => 'd',
Self::ExternalAddress => 'e',
Self::FactAddress => 'f',
Self::InstanceAddress => 'i',
Self::Integer => 'l',
Self::Multifield => 'm',
Self::InstanceName => 'n',
Self::String => 's',
Self::Symbol => 'y',
Self::Void => 'v',
}
}
}
#[derive(Clone, Debug)]
pub struct UdfSignature {
pub(crate) returns: CString,
pub(crate) min_args: u16,
pub(crate) max_args: u16,
pub(crate) arguments: Option<CString>,
}
impl UdfSignature {
pub fn builder(returns: &[UdfType]) -> UdfSignatureBuilder {
UdfSignatureBuilder {
returns: type_codes(returns),
min_args: 0,
max_args: 0,
default_arguments: Vec::new(),
positional_arguments: Vec::new(),
}
}
}
#[derive(Clone, Debug)]
pub struct UdfSignatureBuilder {
returns: String,
min_args: u16,
max_args: u16,
default_arguments: Vec<UdfType>,
positional_arguments: Vec<Vec<UdfType>>,
}
impl UdfSignatureBuilder {
pub fn arity(mut self, min: u16, max: u16) -> Self {
self.min_args = min;
self.max_args = max;
self
}
pub fn unbounded(mut self, min: u16) -> Self {
self.min_args = min;
self.max_args = u16::MAX;
self
}
pub fn default_arguments(mut self, types: &[UdfType]) -> Self {
self.default_arguments = types.to_vec();
self
}
pub fn argument(mut self, position: usize, types: &[UdfType]) -> Self {
assert!(position > 0, "UDF argument positions are one-based");
self.positional_arguments.resize(position, Vec::new());
self.positional_arguments[position - 1] = types.to_vec();
self
}
pub fn build(self) -> UdfSignature {
let arguments = if self.default_arguments.is_empty()
&& self.positional_arguments.iter().all(Vec::is_empty)
{
None
} else {
let mut restrictions = type_codes(&self.default_arguments);
for argument in self.positional_arguments {
restrictions.push(';');
restrictions.push_str(&type_codes(&argument));
}
Some(CString::new(restrictions).expect("type codes contain no NUL"))
};
UdfSignature {
returns: CString::new(self.returns).expect("type codes contain no NUL"),
min_args: self.min_args,
max_args: self.max_args,
arguments,
}
}
}
fn type_codes(types: &[UdfType]) -> String {
types.iter().map(|ty| ty.code()).collect()
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UdfCallbackError {
Message(String),
ReentrantCall,
Panic,
UnsupportedArgumentType(u16),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UdfRegistrationError {
InteriorNul,
MinimumExceedsMaximum,
NameInUse,
InvalidArgumentType,
InvalidReturnType,
NotFound,
Unknown(u32),
}
impl From<std::ffi::NulError> for UdfRegistrationError {
fn from(_: std::ffi::NulError) -> Self {
Self::InteriorNul
}
}
impl UdfRegistrationError {
pub(crate) fn from_code(code: u32) -> Self {
match code {
1 => Self::MinimumExceedsMaximum,
2 => Self::NameInUse,
3 => Self::InvalidArgumentType,
4 => Self::InvalidReturnType,
code => Self::Unknown(code),
}
}
}
impl std::fmt::Display for UdfRegistrationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "CLIPS UDF registration error: {self:?}")
}
}
impl std::error::Error for UdfRegistrationError {}
impl From<String> for UdfCallbackError {
fn from(value: String) -> Self {
Self::Message(value)
}
}
impl From<&str> for UdfCallbackError {
fn from(value: &str) -> Self {
Self::Message(value.to_owned())
}
}
type Callback = dyn for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
+ 'static;
pub(crate) struct UdfRegistration {
pub(crate) name: CString,
pub(crate) signature: UdfSignature,
callback: RefCell<Box<Callback>>,
last_error: RefCell<Option<UdfCallbackError>>,
}
impl UdfRegistration {
pub(crate) fn new<F>(name: CString, signature: UdfSignature, callback: F) -> Box<Self>
where
F: for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
+ 'static,
{
Box::new(Self {
name,
signature,
callback: RefCell::new(Box::new(callback)),
last_error: RefCell::new(None),
})
}
pub(crate) fn context(&mut self) -> *mut c_void {
self as *mut Self as *mut c_void
}
pub(crate) fn take_error(&self) -> Option<UdfCallbackError> {
self.last_error.borrow_mut().take()
}
}
pub(crate) unsafe extern "C" fn trampoline(
environment: *mut ffi::Environment,
context: *mut ffi::UDFContext,
output: *mut ffi::UDFValue,
) {
let result = catch_unwind(AssertUnwindSafe(|| {
let registration = unsafe { &*((*context).context as *const UdfRegistration) };
let argument_count = unsafe { ffi::UDFArgumentCount(context) } as usize;
let mut arguments = Vec::with_capacity(argument_count);
for position in 1..=argument_count {
let mut raw = ffi::UDFValue {
supplemental_info: std::ptr::null_mut(),
value: ffi::CLIPSValue {
value: std::ptr::null_mut(),
},
begin: 0,
range: usize::MAX,
next: std::ptr::null_mut(),
};
if !unsafe { ffi::UDFNthArgument(context, position as u32, ANY_TYPE_BITS, &mut raw) } {
return Err(UdfCallbackError::Message(format!(
"CLIPS rejected UDF argument {position}"
)));
}
arguments.push(unsafe { decode_value(&raw)? });
}
let mut callback = registration
.callback
.try_borrow_mut()
.map_err(|_| UdfCallbackError::ReentrantCall)?;
let returned = callback(&arguments)?;
unsafe { encode_return(environment, output, returned) }
}));
let error = match result {
Ok(Ok(())) => return,
Ok(Err(error)) => error,
Err(_) => UdfCallbackError::Panic,
};
let registration = unsafe { &*((*context).context as *const UdfRegistration) };
*registration.last_error.borrow_mut() = Some(error);
unsafe { ffi::UDFThrowError(context) };
}
unsafe fn decode_value<'call>(raw: &ffi::UDFValue) -> Result<UdfValue<'call>, UdfCallbackError> {
let type_code = unsafe { (*raw.value.header).type_ };
Ok(match type_code {
0 => UdfValue::Float(unsafe { (*raw.value.float).contents }),
1 => UdfValue::Integer(unsafe { (*raw.value.integer).contents }),
2 => {
let text = unsafe { lexeme(raw) };
if text == "TRUE" || text == "FALSE" {
UdfValue::Boolean(text == "TRUE")
} else {
UdfValue::Symbol(text)
}
}
3 => UdfValue::String(unsafe { lexeme(raw) }),
4 => {
let multifield = unsafe { &*raw.value.multifield };
let end = raw
.begin
.checked_add(raw.range)
.filter(|&end| end <= multifield.length)
.ok_or_else(|| {
UdfCallbackError::Message("CLIPS returned an invalid multifield slice".into())
})?;
let mut values = Vec::with_capacity(raw.range);
for index in raw.begin..end {
let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
let range = if unsafe { (*cell.header).type_ } == 4 {
unsafe { (*cell.multifield).length }
} else {
0
};
let nested = ffi::UDFValue {
supplemental_info: std::ptr::null_mut(),
value: *cell,
begin: 0,
range,
next: std::ptr::null_mut(),
};
values.push(unsafe { decode_value(&nested)? });
}
UdfValue::Multifield(values)
}
5 => UdfExternalAddress::new(unsafe { raw.value.value })
.map(UdfValue::ExternalAddress)
.ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
6 => UdfFact::new(unsafe { raw.value.fact })
.map(UdfValue::FactAddress)
.ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
7 => UdfInstance::new(unsafe { raw.value.instance })
.map(UdfValue::InstanceAddress)
.ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
8 => UdfValue::InstanceName(unsafe { lexeme(raw) }),
9 => UdfValue::Void,
other => return Err(UdfCallbackError::UnsupportedArgumentType(other)),
})
}
unsafe fn lexeme(raw: &ffi::UDFValue) -> String {
unsafe { CStr::from_ptr((*raw.value.lexeme).contents) }
.to_string_lossy()
.into_owned()
}
unsafe fn encode_return(
environment: *mut ffi::Environment,
output: *mut ffi::UDFValue,
value: UdfReturn<'_>,
) -> Result<(), UdfCallbackError> {
match value {
UdfReturn::Float(value) => unsafe {
(*output).value.float = ffi::CreateFloat(environment, value)
},
UdfReturn::Integer(value) => unsafe {
(*output).value.integer = ffi::CreateInteger(environment, value)
},
UdfReturn::Boolean(value) => unsafe {
(*output).value.lexeme = ffi::CreateBoolean(environment, value)
},
UdfReturn::Symbol(value) => {
let value = CString::new(value)
.map_err(|_| UdfCallbackError::Message("symbol contains NUL".into()))?;
unsafe { (*output).value.lexeme = ffi::CreateSymbol(environment, value.as_ptr()) };
}
UdfReturn::String(value) => {
let value = CString::new(value)
.map_err(|_| UdfCallbackError::Message("string contains NUL".into()))?;
unsafe { (*output).value.lexeme = ffi::CreateString(environment, value.as_ptr()) };
}
UdfReturn::InstanceName(value) => {
let value = CString::new(value)
.map_err(|_| UdfCallbackError::Message("instance name contains NUL".into()))?;
unsafe {
(*output).value.lexeme = ffi::CreateInstanceName(environment, value.as_ptr())
};
}
UdfReturn::Multifield(values) => {
let multifield = unsafe { build_multifield(environment, values)? };
unsafe {
(*output).value.multifield = multifield;
(*output).begin = 0;
(*output).range = (*multifield).length;
}
}
UdfReturn::FactAddress(fact) => unsafe { (*output).value.fact = fact.raw.as_ptr() },
UdfReturn::InstanceAddress(instance) => unsafe {
(*output).value.instance = instance.raw.as_ptr()
},
UdfReturn::ExternalAddress(address) => unsafe {
(*output).value.value = address.raw.as_ptr()
},
UdfReturn::Void => {}
}
Ok(())
}
struct MultifieldBuilderGuard(*mut ffi::MultifieldBuilder);
impl Drop for MultifieldBuilderGuard {
fn drop(&mut self) {
unsafe { ffi::MBDispose(self.0) }
}
}
unsafe fn build_multifield(
environment: *mut ffi::Environment,
values: Vec<UdfReturn<'_>>,
) -> Result<*mut ffi::Multifield, UdfCallbackError> {
let builder = unsafe { ffi::CreateMultifieldBuilder(environment, values.len()) };
if builder.is_null() {
return Err(UdfCallbackError::Message(
"CLIPS could not create a multifield builder".into(),
));
}
let guard = MultifieldBuilderGuard(builder);
for value in values {
match value {
UdfReturn::Float(value) => unsafe { ffi::MBAppendFloat(builder, value) },
UdfReturn::Integer(value) => unsafe { ffi::MBAppendInteger(builder, value) },
UdfReturn::Boolean(value) => {
let mut raw = ffi::CLIPSValue {
lexeme: unsafe { ffi::CreateBoolean(environment, value) },
};
unsafe { ffi::MBAppend(builder, &mut raw) };
}
UdfReturn::Symbol(value) => {
let value = nul_free(value, "symbol")?;
unsafe { ffi::MBAppendSymbol(builder, value.as_ptr()) };
}
UdfReturn::String(value) => {
let value = nul_free(value, "string")?;
unsafe { ffi::MBAppendString(builder, value.as_ptr()) };
}
UdfReturn::InstanceName(value) => {
let value = nul_free(value, "instance name")?;
unsafe { ffi::MBAppendInstanceName(builder, value.as_ptr()) };
}
UdfReturn::Multifield(values) => {
let nested = unsafe { build_multifield(environment, values)? };
unsafe { ffi::MBAppendMultifield(builder, nested) };
}
UdfReturn::FactAddress(fact) => unsafe {
ffi::MBAppendFact(builder, fact.raw.as_ptr())
},
UdfReturn::InstanceAddress(instance) => unsafe {
ffi::MBAppendInstance(builder, instance.raw.as_ptr())
},
UdfReturn::ExternalAddress(address) => {
let mut raw = ffi::CLIPSValue {
value: address.raw.as_ptr(),
};
unsafe { ffi::MBAppend(builder, &mut raw) };
}
UdfReturn::Void => {}
}
}
let multifield = unsafe { ffi::MBCreate(builder) };
drop(guard);
if multifield.is_null() {
return Err(UdfCallbackError::Message(
"CLIPS could not create the returned multifield".into(),
));
}
Ok(multifield)
}
fn nul_free(value: String, kind: &str) -> Result<CString, UdfCallbackError> {
CString::new(value).map_err(|_| UdfCallbackError::Message(format!("{kind} contains NUL")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decodes_nested_multifields_with_their_own_bounds() {
let mut integer = ffi::CLIPSInteger {
header: ffi::TypeHeader { type_: 1 },
next: std::ptr::null_mut(),
count: 0,
flags: 0,
contents: 42,
};
let mut inner = ffi::Multifield {
header: ffi::TypeHeader { type_: 4 },
busy_count: 0,
length: 1,
next: std::ptr::null_mut(),
contents: [ffi::CLIPSValue {
integer: &mut integer,
}],
};
let mut outer = ffi::Multifield {
header: ffi::TypeHeader { type_: 4 },
busy_count: 0,
length: 1,
next: std::ptr::null_mut(),
contents: [ffi::CLIPSValue {
multifield: &mut inner,
}],
};
let raw = ffi::UDFValue {
supplemental_info: std::ptr::null_mut(),
value: ffi::CLIPSValue {
multifield: &mut outer,
},
begin: 0,
range: 1,
next: std::ptr::null_mut(),
};
assert_eq!(
unsafe { decode_value(&raw) }.unwrap(),
UdfValue::Multifield(vec![UdfValue::Multifield(vec![UdfValue::Integer(42)])])
);
}
#[test]
fn rejects_out_of_bounds_multifield_slices() {
let mut multifield = ffi::Multifield {
header: ffi::TypeHeader { type_: 4 },
busy_count: 0,
length: 0,
next: std::ptr::null_mut(),
contents: [ffi::CLIPSValue {
value: std::ptr::null_mut(),
}],
};
let raw = ffi::UDFValue {
supplemental_info: std::ptr::null_mut(),
value: ffi::CLIPSValue {
multifield: &mut multifield,
},
begin: 1,
range: 1,
next: std::ptr::null_mut(),
};
assert!(matches!(
unsafe { decode_value(&raw) },
Err(UdfCallbackError::Message(message))
if message == "CLIPS returned an invalid multifield slice"
));
}
}