Skip to main content

clips_bindings/
router.rs

1//! Safe support for CLIPS logical-name I/O routers.
2//!
3//! Router callbacks are invoked synchronously by CLIPS. A callback which is
4//! re-entered while it is already running is treated as unavailable, and a
5//! panic in user code is contained at the FFI boundary.
6
7use std::cell::RefCell;
8use std::ffi::{CStr, CString, NulError, c_char, c_int, c_void};
9use std::panic::{AssertUnwindSafe, catch_unwind};
10use std::ptr::NonNull;
11
12use crate::ffi;
13
14/// A destination and/or source for CLIPS logical I/O names.
15///
16/// The default methods implement a router which accepts no logical names and
17/// has no input. CLIPS calls [`Router::query`] first and only dispatches the
18/// other operations for names accepted by that method.
19pub trait Router: 'static {
20    /// Whether this router handles `logical_name`, such as `stdout`, `werror`,
21    /// or a name of your own.
22    ///
23    /// CLIPS calls this before every other method and skips the router if it
24    /// returns `false`. When several routers claim a name, the one registered
25    /// with the highest priority wins.
26    fn query(&mut self, logical_name: &str) -> bool;
27
28    /// Receives text CLIPS writes to a claimed logical name.
29    fn write(&mut self, _logical_name: &str, _text: &str) {}
30
31    /// Returns the next input byte, or `None` for end of input.
32    fn read(&mut self, _logical_name: &str) -> Option<u8> {
33        None
34    }
35
36    /// Pushes a byte back onto the input stream.
37    fn unread(&mut self, _logical_name: &str, _byte: u8) -> bool {
38        false
39    }
40
41    /// Called when CLIPS is exiting, so the router can flush or close what it
42    /// owns.
43    fn exit(&mut self, _exit_code: i32) {}
44}
45
46/// Why registering or removing a router failed.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum RouterError {
49    /// The router name contained a NUL byte.
50    InteriorNul,
51    /// A router of that name is already registered. CLIPS would accept the
52    /// duplicate but could not then remove it reliably, so it is refused.
53    DuplicateName,
54    /// No router of that name is registered.
55    NotFound,
56}
57
58impl From<NulError> for RouterError {
59    fn from(_: NulError) -> Self {
60        Self::InteriorNul
61    }
62}
63
64impl std::fmt::Display for RouterError {
65    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        match self {
67            Self::InteriorNul => formatter.write_str("router name contains a NUL byte"),
68            Self::DuplicateName => formatter.write_str("a CLIPS router already uses this name"),
69            Self::NotFound => formatter.write_str("CLIPS router was not found"),
70        }
71    }
72}
73
74impl std::error::Error for RouterError {}
75
76struct RouterContext {
77    router: RefCell<Box<dyn Router>>,
78}
79
80/// An environment-owned router registration.
81///
82/// The context is separately boxed so its address remains stable if the
83/// environment's registration collection reallocates.
84pub(crate) struct RouterEntry {
85    name: CString,
86    _context: Box<RouterContext>,
87}
88
89impl RouterEntry {
90    pub(crate) fn register<R: Router>(
91        environment: NonNull<ffi::Environment>,
92        name: &str,
93        priority: i32,
94        router: R,
95    ) -> Result<Self, RouterError> {
96        let name = CString::new(name)?;
97        let context = Box::new(RouterContext {
98            router: RefCell::new(Box::new(router)),
99        });
100        let context_ptr = (&*context as *const RouterContext)
101            .cast_mut()
102            .cast::<c_void>();
103        let added = unsafe {
104            ffi::AddRouter(
105                environment.as_ptr(),
106                name.as_ptr(),
107                priority,
108                Some(query_trampoline),
109                Some(write_trampoline),
110                Some(read_trampoline),
111                Some(unread_trampoline),
112                Some(exit_trampoline),
113                context_ptr,
114            )
115        };
116        added
117            .then_some(Self {
118                name,
119                _context: context,
120            })
121            .ok_or(RouterError::DuplicateName)
122    }
123
124    pub(crate) fn name(&self) -> &CStr {
125        &self.name
126    }
127
128    pub(crate) fn activate(
129        &self,
130        environment: NonNull<ffi::Environment>,
131    ) -> Result<(), RouterError> {
132        unsafe { ffi::ActivateRouter(environment.as_ptr(), self.name.as_ptr()) }
133            .then_some(())
134            .ok_or(RouterError::NotFound)
135    }
136
137    pub(crate) fn deactivate(
138        &self,
139        environment: NonNull<ffi::Environment>,
140    ) -> Result<(), RouterError> {
141        unsafe { ffi::DeactivateRouter(environment.as_ptr(), self.name.as_ptr()) }
142            .then_some(())
143            .ok_or(RouterError::NotFound)
144    }
145
146    /// Delete the C registration before dropping the callback context.
147    pub(crate) fn unregister(
148        self,
149        environment: NonNull<ffi::Environment>,
150    ) -> Result<(), (Self, RouterError)> {
151        if unsafe { ffi::DeleteRouter(environment.as_ptr(), self.name.as_ptr()) } {
152            Ok(())
153        } else {
154            Err((self, RouterError::NotFound))
155        }
156    }
157}
158
159unsafe fn context<'a>(raw: *mut c_void) -> Option<&'a RouterContext> {
160    NonNull::new(raw.cast::<RouterContext>()).map(|pointer| unsafe { pointer.as_ref() })
161}
162
163unsafe fn text<'a>(raw: *const c_char) -> Option<&'a str> {
164    (!raw.is_null())
165        .then(|| unsafe { CStr::from_ptr(raw) })
166        .and_then(|value| value.to_str().ok())
167}
168
169unsafe extern "C" fn query_trampoline(
170    _environment: *mut ffi::Environment,
171    logical_name: *const c_char,
172    raw_context: *mut c_void,
173) -> bool {
174    catch_unwind(AssertUnwindSafe(|| {
175        let (Some(context), Some(logical_name)) =
176            (unsafe { (context(raw_context), text(logical_name)) })
177        else {
178            return false;
179        };
180        context
181            .router
182            .try_borrow_mut()
183            .map(|mut router| router.query(logical_name))
184            .unwrap_or(false)
185    }))
186    .unwrap_or(false)
187}
188
189unsafe extern "C" fn write_trampoline(
190    _environment: *mut ffi::Environment,
191    logical_name: *const c_char,
192    output: *const c_char,
193    raw_context: *mut c_void,
194) {
195    let _ = catch_unwind(AssertUnwindSafe(|| {
196        let (Some(context), Some(logical_name), Some(output)) =
197            (unsafe { (context(raw_context), text(logical_name), text(output)) })
198        else {
199            return;
200        };
201        if let Ok(mut router) = context.router.try_borrow_mut() {
202            router.write(logical_name, output);
203        }
204    }));
205}
206
207unsafe extern "C" fn read_trampoline(
208    _environment: *mut ffi::Environment,
209    logical_name: *const c_char,
210    raw_context: *mut c_void,
211) -> c_int {
212    catch_unwind(AssertUnwindSafe(|| {
213        let (Some(context), Some(logical_name)) =
214            (unsafe { (context(raw_context), text(logical_name)) })
215        else {
216            return -1;
217        };
218        context
219            .router
220            .try_borrow_mut()
221            .ok()
222            .and_then(|mut router| router.read(logical_name))
223            .map_or(-1, c_int::from)
224    }))
225    .unwrap_or(-1)
226}
227
228unsafe extern "C" fn unread_trampoline(
229    _environment: *mut ffi::Environment,
230    logical_name: *const c_char,
231    character: c_int,
232    raw_context: *mut c_void,
233) -> c_int {
234    catch_unwind(AssertUnwindSafe(|| {
235        let (Some(context), Some(logical_name), Ok(byte)) = (
236            unsafe { context(raw_context) },
237            unsafe { text(logical_name) },
238            u8::try_from(character),
239        ) else {
240            return -1;
241        };
242        if context
243            .router
244            .try_borrow_mut()
245            .map(|mut router| router.unread(logical_name, byte))
246            .unwrap_or(false)
247        {
248            character
249        } else {
250            -1
251        }
252    }))
253    .unwrap_or(-1)
254}
255
256unsafe extern "C" fn exit_trampoline(
257    _environment: *mut ffi::Environment,
258    exit_code: c_int,
259    raw_context: *mut c_void,
260) {
261    let _ = catch_unwind(AssertUnwindSafe(|| {
262        let Some(context) = (unsafe { context(raw_context) }) else {
263            return;
264        };
265        if let Ok(mut router) = context.router.try_borrow_mut() {
266            router.exit(exit_code);
267        }
268    }));
269}