clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Safe support for CLIPS logical-name I/O routers.
//!
//! Router callbacks are invoked synchronously by CLIPS. A callback which is
//! re-entered while it is already running is treated as unavailable, and a
//! panic in user code is contained at the FFI boundary.

use std::cell::RefCell;
use std::ffi::{CStr, CString, NulError, c_char, c_int, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr::NonNull;

use crate::ffi;

/// A destination and/or source for CLIPS logical I/O names.
///
/// The default methods implement a router which accepts no logical names and
/// has no input. CLIPS calls [`Router::query`] first and only dispatches the
/// other operations for names accepted by that method.
pub trait Router: 'static {
    /// Whether this router handles `logical_name`, such as `stdout`, `werror`,
    /// or a name of your own.
    ///
    /// CLIPS calls this before every other method and skips the router if it
    /// returns `false`. When several routers claim a name, the one registered
    /// with the highest priority wins.
    fn query(&mut self, logical_name: &str) -> bool;

    /// Receives text CLIPS writes to a claimed logical name.
    fn write(&mut self, _logical_name: &str, _text: &str) {}

    /// Returns the next input byte, or `None` for end of input.
    fn read(&mut self, _logical_name: &str) -> Option<u8> {
        None
    }

    /// Pushes a byte back onto the input stream.
    fn unread(&mut self, _logical_name: &str, _byte: u8) -> bool {
        false
    }

    /// Called when CLIPS is exiting, so the router can flush or close what it
    /// owns.
    fn exit(&mut self, _exit_code: i32) {}
}

/// Why registering or removing a router failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouterError {
    /// The router name contained a NUL byte.
    InteriorNul,
    /// A router of that name is already registered. CLIPS would accept the
    /// duplicate but could not then remove it reliably, so it is refused.
    DuplicateName,
    /// No router of that name is registered.
    NotFound,
}

impl From<NulError> for RouterError {
    fn from(_: NulError) -> Self {
        Self::InteriorNul
    }
}

impl std::fmt::Display for RouterError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InteriorNul => formatter.write_str("router name contains a NUL byte"),
            Self::DuplicateName => formatter.write_str("a CLIPS router already uses this name"),
            Self::NotFound => formatter.write_str("CLIPS router was not found"),
        }
    }
}

impl std::error::Error for RouterError {}

struct RouterContext {
    router: RefCell<Box<dyn Router>>,
}

/// An environment-owned router registration.
///
/// The context is separately boxed so its address remains stable if the
/// environment's registration collection reallocates.
pub(crate) struct RouterEntry {
    name: CString,
    _context: Box<RouterContext>,
}

impl RouterEntry {
    pub(crate) fn register<R: Router>(
        environment: NonNull<ffi::Environment>,
        name: &str,
        priority: i32,
        router: R,
    ) -> Result<Self, RouterError> {
        let name = CString::new(name)?;
        let context = Box::new(RouterContext {
            router: RefCell::new(Box::new(router)),
        });
        let context_ptr = (&*context as *const RouterContext)
            .cast_mut()
            .cast::<c_void>();
        let added = unsafe {
            ffi::AddRouter(
                environment.as_ptr(),
                name.as_ptr(),
                priority,
                Some(query_trampoline),
                Some(write_trampoline),
                Some(read_trampoline),
                Some(unread_trampoline),
                Some(exit_trampoline),
                context_ptr,
            )
        };
        added
            .then_some(Self {
                name,
                _context: context,
            })
            .ok_or(RouterError::DuplicateName)
    }

    pub(crate) fn name(&self) -> &CStr {
        &self.name
    }

    pub(crate) fn activate(
        &self,
        environment: NonNull<ffi::Environment>,
    ) -> Result<(), RouterError> {
        unsafe { ffi::ActivateRouter(environment.as_ptr(), self.name.as_ptr()) }
            .then_some(())
            .ok_or(RouterError::NotFound)
    }

    pub(crate) fn deactivate(
        &self,
        environment: NonNull<ffi::Environment>,
    ) -> Result<(), RouterError> {
        unsafe { ffi::DeactivateRouter(environment.as_ptr(), self.name.as_ptr()) }
            .then_some(())
            .ok_or(RouterError::NotFound)
    }

    /// Delete the C registration before dropping the callback context.
    pub(crate) fn unregister(
        self,
        environment: NonNull<ffi::Environment>,
    ) -> Result<(), (Self, RouterError)> {
        if unsafe { ffi::DeleteRouter(environment.as_ptr(), self.name.as_ptr()) } {
            Ok(())
        } else {
            Err((self, RouterError::NotFound))
        }
    }
}

unsafe fn context<'a>(raw: *mut c_void) -> Option<&'a RouterContext> {
    NonNull::new(raw.cast::<RouterContext>()).map(|pointer| unsafe { pointer.as_ref() })
}

unsafe fn text<'a>(raw: *const c_char) -> Option<&'a str> {
    (!raw.is_null())
        .then(|| unsafe { CStr::from_ptr(raw) })
        .and_then(|value| value.to_str().ok())
}

unsafe extern "C" fn query_trampoline(
    _environment: *mut ffi::Environment,
    logical_name: *const c_char,
    raw_context: *mut c_void,
) -> bool {
    catch_unwind(AssertUnwindSafe(|| {
        let (Some(context), Some(logical_name)) =
            (unsafe { (context(raw_context), text(logical_name)) })
        else {
            return false;
        };
        context
            .router
            .try_borrow_mut()
            .map(|mut router| router.query(logical_name))
            .unwrap_or(false)
    }))
    .unwrap_or(false)
}

unsafe extern "C" fn write_trampoline(
    _environment: *mut ffi::Environment,
    logical_name: *const c_char,
    output: *const c_char,
    raw_context: *mut c_void,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let (Some(context), Some(logical_name), Some(output)) =
            (unsafe { (context(raw_context), text(logical_name), text(output)) })
        else {
            return;
        };
        if let Ok(mut router) = context.router.try_borrow_mut() {
            router.write(logical_name, output);
        }
    }));
}

unsafe extern "C" fn read_trampoline(
    _environment: *mut ffi::Environment,
    logical_name: *const c_char,
    raw_context: *mut c_void,
) -> c_int {
    catch_unwind(AssertUnwindSafe(|| {
        let (Some(context), Some(logical_name)) =
            (unsafe { (context(raw_context), text(logical_name)) })
        else {
            return -1;
        };
        context
            .router
            .try_borrow_mut()
            .ok()
            .and_then(|mut router| router.read(logical_name))
            .map_or(-1, c_int::from)
    }))
    .unwrap_or(-1)
}

unsafe extern "C" fn unread_trampoline(
    _environment: *mut ffi::Environment,
    logical_name: *const c_char,
    character: c_int,
    raw_context: *mut c_void,
) -> c_int {
    catch_unwind(AssertUnwindSafe(|| {
        let (Some(context), Some(logical_name), Ok(byte)) = (
            unsafe { context(raw_context) },
            unsafe { text(logical_name) },
            u8::try_from(character),
        ) else {
            return -1;
        };
        if context
            .router
            .try_borrow_mut()
            .map(|mut router| router.unread(logical_name, byte))
            .unwrap_or(false)
        {
            character
        } else {
            -1
        }
    }))
    .unwrap_or(-1)
}

unsafe extern "C" fn exit_trampoline(
    _environment: *mut ffi::Environment,
    exit_code: c_int,
    raw_context: *mut c_void,
) {
    let _ = catch_unwind(AssertUnwindSafe(|| {
        let Some(context) = (unsafe { context(raw_context) }) else {
            return;
        };
        if let Ok(mut router) = context.router.try_borrow_mut() {
            router.exit(exit_code);
        }
    }));
}