1use std::cell::RefCell;
8use std::ffi::{CStr, CString, c_void};
9use std::marker::PhantomData;
10use std::panic::{AssertUnwindSafe, catch_unwind};
11use std::ptr::NonNull;
12
13use crate::ffi;
14
15const ANY_TYPE_BITS: u32 = (1 << 11) - 1;
16
17macro_rules! address_token {
19 ($($name:ident($target:ty)),+ $(,)?) => {$(
20 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
28 pub struct $name<'call> {
29 pub(crate) raw: NonNull<$target>,
30 pub(crate) marker: PhantomData<&'call ()>,
31 }
32 impl<'call> $name<'call> {
33 fn new(raw: *mut $target) -> Option<Self> {
34 NonNull::new(raw).map(|raw| Self { raw, marker: PhantomData })
35 }
36 }
37 )+};
38}
39address_token!(
40 UdfFact(ffi::Fact),
41 UdfInstance(ffi::Instance),
42 UdfExternalAddress(c_void),
43);
44
45#[derive(Clone, Debug, PartialEq)]
50#[non_exhaustive]
51pub enum UdfValue<'call> {
52 Float(f64),
54 Integer(i64),
56 Symbol(String),
58 String(String),
60 Boolean(bool),
62 InstanceName(String),
64 Multifield(Vec<UdfValue<'call>>),
67 FactAddress(UdfFact<'call>),
69 InstanceAddress(UdfInstance<'call>),
71 ExternalAddress(UdfExternalAddress<'call>),
73 Void,
75}
76
77#[derive(Clone, Debug, PartialEq)]
83#[non_exhaustive]
84pub enum UdfReturn<'call> {
85 Float(f64),
87 Integer(i64),
89 Symbol(String),
91 String(String),
93 Boolean(bool),
95 InstanceName(String),
97 Multifield(Vec<UdfReturn<'call>>),
100 FactAddress(UdfFact<'call>),
102 InstanceAddress(UdfInstance<'call>),
104 ExternalAddress(UdfExternalAddress<'call>),
106 Void,
108}
109
110#[derive(Clone, Copy, Debug, Eq, PartialEq)]
112pub enum UdfType {
113 Any,
115 Boolean,
117 Float,
119 ExternalAddress,
121 FactAddress,
123 InstanceAddress,
125 Integer,
127 Multifield,
129 InstanceName,
131 String,
133 Symbol,
135 Void,
137}
138
139impl UdfType {
140 fn code(self) -> char {
141 match self {
142 Self::Any => '*',
143 Self::Boolean => 'b',
144 Self::Float => 'd',
145 Self::ExternalAddress => 'e',
146 Self::FactAddress => 'f',
147 Self::InstanceAddress => 'i',
148 Self::Integer => 'l',
149 Self::Multifield => 'm',
150 Self::InstanceName => 'n',
151 Self::String => 's',
152 Self::Symbol => 'y',
153 Self::Void => 'v',
154 }
155 }
156}
157
158#[derive(Clone, Debug)]
160pub struct UdfSignature {
161 pub(crate) returns: CString,
162 pub(crate) min_args: u16,
163 pub(crate) max_args: u16,
164 pub(crate) arguments: Option<CString>,
165}
166
167impl UdfSignature {
168 pub fn builder(returns: &[UdfType]) -> UdfSignatureBuilder {
170 UdfSignatureBuilder {
171 returns: type_codes(returns),
172 min_args: 0,
173 max_args: 0,
174 default_arguments: Vec::new(),
175 positional_arguments: Vec::new(),
176 }
177 }
178}
179
180#[derive(Clone, Debug)]
182pub struct UdfSignatureBuilder {
183 returns: String,
184 min_args: u16,
185 max_args: u16,
186 default_arguments: Vec<UdfType>,
187 positional_arguments: Vec<Vec<UdfType>>,
188}
189
190impl UdfSignatureBuilder {
191 pub fn arity(mut self, min: u16, max: u16) -> Self {
193 self.min_args = min;
194 self.max_args = max;
195 self
196 }
197
198 pub fn unbounded(mut self, min: u16) -> Self {
200 self.min_args = min;
201 self.max_args = u16::MAX;
202 self
203 }
204
205 pub fn default_arguments(mut self, types: &[UdfType]) -> Self {
208 self.default_arguments = types.to_vec();
209 self
210 }
211
212 pub fn argument(mut self, position: usize, types: &[UdfType]) -> Self {
218 assert!(position > 0, "UDF argument positions are one-based");
219 self.positional_arguments.resize(position, Vec::new());
220 self.positional_arguments[position - 1] = types.to_vec();
221 self
222 }
223
224 pub fn build(self) -> UdfSignature {
227 let arguments = if self.default_arguments.is_empty()
228 && self.positional_arguments.iter().all(Vec::is_empty)
229 {
230 None
231 } else {
232 let mut restrictions = type_codes(&self.default_arguments);
233 for argument in self.positional_arguments {
234 restrictions.push(';');
235 restrictions.push_str(&type_codes(&argument));
236 }
237 Some(CString::new(restrictions).expect("type codes contain no NUL"))
238 };
239 UdfSignature {
240 returns: CString::new(self.returns).expect("type codes contain no NUL"),
241 min_args: self.min_args,
242 max_args: self.max_args,
243 arguments,
244 }
245 }
246}
247
248fn type_codes(types: &[UdfType]) -> String {
249 types.iter().map(|ty| ty.code()).collect()
250}
251
252#[derive(Clone, Debug, Eq, PartialEq)]
254pub enum UdfCallbackError {
255 Message(String),
258 ReentrantCall,
262 Panic,
265 UnsupportedArgumentType(u16),
267}
268
269#[derive(Clone, Debug, Eq, PartialEq)]
271pub enum UdfRegistrationError {
272 InteriorNul,
274 MinimumExceedsMaximum,
276 NameInUse,
278 InvalidArgumentType,
280 InvalidReturnType,
282 NotFound,
284 Unknown(u32),
286}
287impl From<std::ffi::NulError> for UdfRegistrationError {
288 fn from(_: std::ffi::NulError) -> Self {
289 Self::InteriorNul
290 }
291}
292impl UdfRegistrationError {
293 pub(crate) fn from_code(code: u32) -> Self {
294 match code {
295 1 => Self::MinimumExceedsMaximum,
296 2 => Self::NameInUse,
297 3 => Self::InvalidArgumentType,
298 4 => Self::InvalidReturnType,
299 code => Self::Unknown(code),
300 }
301 }
302}
303impl std::fmt::Display for UdfRegistrationError {
304 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 write!(formatter, "CLIPS UDF registration error: {self:?}")
306 }
307}
308impl std::error::Error for UdfRegistrationError {}
309
310impl From<String> for UdfCallbackError {
311 fn from(value: String) -> Self {
312 Self::Message(value)
313 }
314}
315
316impl From<&str> for UdfCallbackError {
317 fn from(value: &str) -> Self {
318 Self::Message(value.to_owned())
319 }
320}
321
322type Callback = dyn for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
323 + 'static;
324
325pub(crate) struct UdfRegistration {
327 pub(crate) name: CString,
328 pub(crate) signature: UdfSignature,
329 callback: RefCell<Box<Callback>>,
330 last_error: RefCell<Option<UdfCallbackError>>,
331}
332
333impl UdfRegistration {
334 pub(crate) fn new<F>(name: CString, signature: UdfSignature, callback: F) -> Box<Self>
335 where
336 F: for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
337 + 'static,
338 {
339 Box::new(Self {
340 name,
341 signature,
342 callback: RefCell::new(Box::new(callback)),
343 last_error: RefCell::new(None),
344 })
345 }
346
347 pub(crate) fn context(&mut self) -> *mut c_void {
348 self as *mut Self as *mut c_void
349 }
350
351 pub(crate) fn take_error(&self) -> Option<UdfCallbackError> {
352 self.last_error.borrow_mut().take()
353 }
354}
355
356pub(crate) unsafe extern "C" fn trampoline(
358 environment: *mut ffi::Environment,
359 context: *mut ffi::UDFContext,
360 output: *mut ffi::UDFValue,
361) {
362 let result = catch_unwind(AssertUnwindSafe(|| {
363 let registration = unsafe { &*((*context).context as *const UdfRegistration) };
366 let argument_count = unsafe { ffi::UDFArgumentCount(context) } as usize;
367 let mut arguments = Vec::with_capacity(argument_count);
368 for position in 1..=argument_count {
369 let mut raw = ffi::UDFValue {
370 supplemental_info: std::ptr::null_mut(),
371 value: ffi::CLIPSValue {
372 value: std::ptr::null_mut(),
373 },
374 begin: 0,
375 range: usize::MAX,
376 next: std::ptr::null_mut(),
377 };
378 if !unsafe { ffi::UDFNthArgument(context, position as u32, ANY_TYPE_BITS, &mut raw) } {
379 return Err(UdfCallbackError::Message(format!(
380 "CLIPS rejected UDF argument {position}"
381 )));
382 }
383 arguments.push(unsafe { decode_value(&raw)? });
384 }
385
386 let mut callback = registration
387 .callback
388 .try_borrow_mut()
389 .map_err(|_| UdfCallbackError::ReentrantCall)?;
390 let returned = callback(&arguments)?;
391 unsafe { encode_return(environment, output, returned) }
392 }));
393
394 let error = match result {
395 Ok(Ok(())) => return,
396 Ok(Err(error)) => error,
397 Err(_) => UdfCallbackError::Panic,
398 };
399 let registration = unsafe { &*((*context).context as *const UdfRegistration) };
400 *registration.last_error.borrow_mut() = Some(error);
401 unsafe { ffi::UDFThrowError(context) };
402}
403
404unsafe fn decode_value<'call>(raw: &ffi::UDFValue) -> Result<UdfValue<'call>, UdfCallbackError> {
405 let type_code = unsafe { (*raw.value.header).type_ };
406 Ok(match type_code {
407 0 => UdfValue::Float(unsafe { (*raw.value.float).contents }),
408 1 => UdfValue::Integer(unsafe { (*raw.value.integer).contents }),
409 2 => {
410 let text = unsafe { lexeme(raw) };
411 if text == "TRUE" || text == "FALSE" {
412 UdfValue::Boolean(text == "TRUE")
413 } else {
414 UdfValue::Symbol(text)
415 }
416 }
417 3 => UdfValue::String(unsafe { lexeme(raw) }),
418 4 => {
419 let multifield = unsafe { &*raw.value.multifield };
420 let end = raw
421 .begin
422 .checked_add(raw.range)
423 .filter(|&end| end <= multifield.length)
424 .ok_or_else(|| {
425 UdfCallbackError::Message("CLIPS returned an invalid multifield slice".into())
426 })?;
427 let mut values = Vec::with_capacity(raw.range);
428 for index in raw.begin..end {
429 let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
430 let range = if unsafe { (*cell.header).type_ } == 4 {
431 unsafe { (*cell.multifield).length }
432 } else {
433 0
434 };
435 let nested = ffi::UDFValue {
436 supplemental_info: std::ptr::null_mut(),
437 value: *cell,
438 begin: 0,
439 range,
440 next: std::ptr::null_mut(),
441 };
442 values.push(unsafe { decode_value(&nested)? });
443 }
444 UdfValue::Multifield(values)
445 }
446 5 => UdfExternalAddress::new(unsafe { raw.value.value })
447 .map(UdfValue::ExternalAddress)
448 .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
449 6 => UdfFact::new(unsafe { raw.value.fact })
450 .map(UdfValue::FactAddress)
451 .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
452 7 => UdfInstance::new(unsafe { raw.value.instance })
453 .map(UdfValue::InstanceAddress)
454 .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
455 8 => UdfValue::InstanceName(unsafe { lexeme(raw) }),
456 9 => UdfValue::Void,
457 other => return Err(UdfCallbackError::UnsupportedArgumentType(other)),
458 })
459}
460
461unsafe fn lexeme(raw: &ffi::UDFValue) -> String {
462 unsafe { CStr::from_ptr((*raw.value.lexeme).contents) }
463 .to_string_lossy()
464 .into_owned()
465}
466
467unsafe fn encode_return(
468 environment: *mut ffi::Environment,
469 output: *mut ffi::UDFValue,
470 value: UdfReturn<'_>,
471) -> Result<(), UdfCallbackError> {
472 match value {
473 UdfReturn::Float(value) => unsafe {
474 (*output).value.float = ffi::CreateFloat(environment, value)
475 },
476 UdfReturn::Integer(value) => unsafe {
477 (*output).value.integer = ffi::CreateInteger(environment, value)
478 },
479 UdfReturn::Boolean(value) => unsafe {
480 (*output).value.lexeme = ffi::CreateBoolean(environment, value)
481 },
482 UdfReturn::Symbol(value) => {
483 let value = CString::new(value)
484 .map_err(|_| UdfCallbackError::Message("symbol contains NUL".into()))?;
485 unsafe { (*output).value.lexeme = ffi::CreateSymbol(environment, value.as_ptr()) };
486 }
487 UdfReturn::String(value) => {
488 let value = CString::new(value)
489 .map_err(|_| UdfCallbackError::Message("string contains NUL".into()))?;
490 unsafe { (*output).value.lexeme = ffi::CreateString(environment, value.as_ptr()) };
491 }
492 UdfReturn::InstanceName(value) => {
493 let value = CString::new(value)
494 .map_err(|_| UdfCallbackError::Message("instance name contains NUL".into()))?;
495 unsafe {
496 (*output).value.lexeme = ffi::CreateInstanceName(environment, value.as_ptr())
497 };
498 }
499 UdfReturn::Multifield(values) => {
500 let multifield = unsafe { build_multifield(environment, values)? };
501 unsafe {
502 (*output).value.multifield = multifield;
503 (*output).begin = 0;
504 (*output).range = (*multifield).length;
505 }
506 }
507 UdfReturn::FactAddress(fact) => unsafe { (*output).value.fact = fact.raw.as_ptr() },
508 UdfReturn::InstanceAddress(instance) => unsafe {
509 (*output).value.instance = instance.raw.as_ptr()
510 },
511 UdfReturn::ExternalAddress(address) => unsafe {
512 (*output).value.value = address.raw.as_ptr()
513 },
514 UdfReturn::Void => {}
515 }
516 Ok(())
517}
518
519struct MultifieldBuilderGuard(*mut ffi::MultifieldBuilder);
522impl Drop for MultifieldBuilderGuard {
523 fn drop(&mut self) {
524 unsafe { ffi::MBDispose(self.0) }
525 }
526}
527
528unsafe fn build_multifield(
529 environment: *mut ffi::Environment,
530 values: Vec<UdfReturn<'_>>,
531) -> Result<*mut ffi::Multifield, UdfCallbackError> {
532 let builder = unsafe { ffi::CreateMultifieldBuilder(environment, values.len()) };
533 if builder.is_null() {
534 return Err(UdfCallbackError::Message(
535 "CLIPS could not create a multifield builder".into(),
536 ));
537 }
538 let guard = MultifieldBuilderGuard(builder);
539
540 for value in values {
541 match value {
542 UdfReturn::Float(value) => unsafe { ffi::MBAppendFloat(builder, value) },
543 UdfReturn::Integer(value) => unsafe { ffi::MBAppendInteger(builder, value) },
544 UdfReturn::Boolean(value) => {
545 let mut raw = ffi::CLIPSValue {
546 lexeme: unsafe { ffi::CreateBoolean(environment, value) },
547 };
548 unsafe { ffi::MBAppend(builder, &mut raw) };
549 }
550 UdfReturn::Symbol(value) => {
551 let value = nul_free(value, "symbol")?;
552 unsafe { ffi::MBAppendSymbol(builder, value.as_ptr()) };
553 }
554 UdfReturn::String(value) => {
555 let value = nul_free(value, "string")?;
556 unsafe { ffi::MBAppendString(builder, value.as_ptr()) };
557 }
558 UdfReturn::InstanceName(value) => {
559 let value = nul_free(value, "instance name")?;
560 unsafe { ffi::MBAppendInstanceName(builder, value.as_ptr()) };
561 }
562 UdfReturn::Multifield(values) => {
566 let nested = unsafe { build_multifield(environment, values)? };
567 unsafe { ffi::MBAppendMultifield(builder, nested) };
568 }
569 UdfReturn::FactAddress(fact) => unsafe {
570 ffi::MBAppendFact(builder, fact.raw.as_ptr())
571 },
572 UdfReturn::InstanceAddress(instance) => unsafe {
573 ffi::MBAppendInstance(builder, instance.raw.as_ptr())
574 },
575 UdfReturn::ExternalAddress(address) => {
576 let mut raw = ffi::CLIPSValue {
577 value: address.raw.as_ptr(),
578 };
579 unsafe { ffi::MBAppend(builder, &mut raw) };
580 }
581 UdfReturn::Void => {}
584 }
585 }
586
587 let multifield = unsafe { ffi::MBCreate(builder) };
588 drop(guard);
589 if multifield.is_null() {
590 return Err(UdfCallbackError::Message(
591 "CLIPS could not create the returned multifield".into(),
592 ));
593 }
594 Ok(multifield)
595}
596
597fn nul_free(value: String, kind: &str) -> Result<CString, UdfCallbackError> {
598 CString::new(value).map_err(|_| UdfCallbackError::Message(format!("{kind} contains NUL")))
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn decodes_nested_multifields_with_their_own_bounds() {
607 let mut integer = ffi::CLIPSInteger {
608 header: ffi::TypeHeader { type_: 1 },
609 next: std::ptr::null_mut(),
610 count: 0,
611 flags: 0,
612 contents: 42,
613 };
614 let mut inner = ffi::Multifield {
615 header: ffi::TypeHeader { type_: 4 },
616 busy_count: 0,
617 length: 1,
618 next: std::ptr::null_mut(),
619 contents: [ffi::CLIPSValue {
620 integer: &mut integer,
621 }],
622 };
623 let mut outer = ffi::Multifield {
624 header: ffi::TypeHeader { type_: 4 },
625 busy_count: 0,
626 length: 1,
627 next: std::ptr::null_mut(),
628 contents: [ffi::CLIPSValue {
629 multifield: &mut inner,
630 }],
631 };
632 let raw = ffi::UDFValue {
633 supplemental_info: std::ptr::null_mut(),
634 value: ffi::CLIPSValue {
635 multifield: &mut outer,
636 },
637 begin: 0,
638 range: 1,
639 next: std::ptr::null_mut(),
640 };
641
642 assert_eq!(
643 unsafe { decode_value(&raw) }.unwrap(),
644 UdfValue::Multifield(vec![UdfValue::Multifield(vec![UdfValue::Integer(42)])])
645 );
646 }
647
648 #[test]
649 fn rejects_out_of_bounds_multifield_slices() {
650 let mut multifield = ffi::Multifield {
651 header: ffi::TypeHeader { type_: 4 },
652 busy_count: 0,
653 length: 0,
654 next: std::ptr::null_mut(),
655 contents: [ffi::CLIPSValue {
656 value: std::ptr::null_mut(),
657 }],
658 };
659 let raw = ffi::UDFValue {
660 supplemental_info: std::ptr::null_mut(),
661 value: ffi::CLIPSValue {
662 multifield: &mut multifield,
663 },
664 begin: 1,
665 range: 1,
666 next: std::ptr::null_mut(),
667 };
668
669 assert!(matches!(
670 unsafe { decode_value(&raw) },
671 Err(UdfCallbackError::Message(message))
672 if message == "CLIPS returned an invalid multifield slice"
673 ));
674 }
675}