Skip to main content

clips_bindings/
module.rs

1//! Defmodule selection and rule-engine focus stack operations.
2
3use std::ffi::{CStr, CString};
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::{Defmodule, Environment, ffi};
8
9/// Why a module operation failed.
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum ModuleError {
12    /// The module name contained a NUL byte.
13    InteriorNul,
14    /// No defmodule of that name exists.
15    NotFound(String),
16}
17
18impl std::fmt::Display for ModuleError {
19    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            Self::InteriorNul => formatter.write_str("module name contains a NUL byte"),
22            Self::NotFound(name) => write!(formatter, "defmodule {name:?} was not found"),
23        }
24    }
25}
26
27impl std::error::Error for ModuleError {}
28
29/// A snapshot of an entry in the focus stack.
30///
31/// The name is owned because the underlying `FocalModule` node is destroyed by
32/// `PopFocus` and `ClearFocusStack`.
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct FocusEntry<'env> {
35    name: String,
36    marker: PhantomData<&'env Environment>,
37}
38
39impl FocusEntry<'_> {
40    /// The name of the module at this position in the focus stack.
41    pub fn name(&self) -> &str {
42        &self.name
43    }
44}
45
46/// Immutable traversal of the environment's focus stack, from top to bottom.
47pub struct FocusStack<'env> {
48    environment: &'env Environment,
49    current: *mut ffi::FocalModule,
50}
51
52impl<'env> Iterator for FocusStack<'env> {
53    type Item = FocusEntry<'env>;
54
55    fn next(&mut self) -> Option<Self::Item> {
56        self.current = unsafe { ffi::GetNextFocus(self.environment.raw.as_ptr(), self.current) };
57        NonNull::new(self.current).map(|current| {
58            let name = unsafe { CStr::from_ptr(ffi::FocalModuleName(current.as_ptr())) }
59                .to_string_lossy()
60                .into_owned();
61            FocusEntry {
62                name,
63                marker: PhantomData,
64            }
65        })
66    }
67}
68
69impl Environment {
70    /// Returns the module used for unqualified construct lookup and definition.
71    pub fn current_module(&self) -> Defmodule<'_> {
72        let raw = unsafe { ffi::GetCurrentModule(self.raw.as_ptr()) };
73        // Every initialized CLIPS environment has a current module (MAIN).
74        Defmodule::from_raw(
75            self,
76            NonNull::new(raw).expect("CLIPS returned no current module"),
77        )
78    }
79
80    /// Sets the current module and returns the previous one.
81    ///
82    /// This accepts a name rather than a `Defmodule` handle so a handle from a
83    /// different environment can never be passed to CLIPS.
84    pub fn set_current_module(&mut self, name: &str) -> Result<Defmodule<'_>, ModuleError> {
85        let c_name = CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
86        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
87        let module = NonNull::new(module).ok_or_else(|| ModuleError::NotFound(name.to_owned()))?;
88        let previous = unsafe { ffi::SetCurrentModule(self.raw.as_ptr(), module.as_ptr()) };
89        Ok(Defmodule::from_raw(
90            self,
91            NonNull::new(previous).expect("CLIPS returned no previous current module"),
92        ))
93    }
94
95    /// The number of defmodules, which is at least one because CLIPS always
96    /// has `MAIN`.
97    pub fn module_count(&self) -> usize {
98        unsafe { ffi::GetNumberOfDefmodules(self.raw.as_ptr()) as usize }
99    }
100
101    /// Pushes a module onto the rule-engine focus stack.
102    pub fn focus(&mut self, name: &str) -> Result<(), ModuleError> {
103        let c_name = CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
104        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
105        let module = NonNull::new(module).ok_or_else(|| ModuleError::NotFound(name.to_owned()))?;
106        unsafe { ffi::Focus(module.as_ptr()) };
107        Ok(())
108    }
109
110    /// Pops the top focus and returns its module, or `None` for an empty stack.
111    pub fn pop_focus(&mut self) -> Option<Defmodule<'_>> {
112        NonNull::new(unsafe { ffi::PopFocus(self.raw.as_ptr()) })
113            .map(|raw| Defmodule::from_raw(self, raw))
114    }
115
116    /// The module the rule engine is currently focused on, or `None` when the
117    /// focus stack is empty.
118    pub fn current_focus(&self) -> Option<Defmodule<'_>> {
119        NonNull::new(unsafe { ffi::GetFocus(self.raw.as_ptr()) })
120            .map(|raw| Defmodule::from_raw(self, raw))
121    }
122
123    /// Whether the focus stack changed since this flag was last cleared.
124    pub fn focus_changed(&self) -> bool {
125        unsafe { ffi::GetFocusChanged(self.raw.as_ptr()) }
126    }
127
128    /// Sets or clears the focus-changed flag.
129    pub fn set_focus_changed(&self, changed: bool) {
130        unsafe { ffi::SetFocusChanged(self.raw.as_ptr(), changed) }
131    }
132
133    /// The names of every defmodule, in definition order.
134    ///
135    /// CLIPS returns this as a multifield of symbols; the names are copied so
136    /// the result stays valid across later construct changes.
137    pub fn module_names(&self) -> Vec<String> {
138        let mut raw = ffi::CLIPSValue {
139            value: std::ptr::null_mut(),
140        };
141        unsafe { ffi::GetDefmoduleList(self.raw.as_ptr(), &mut raw) };
142        let names = crate::Multifield::from_value(crate::Value::retaining(self, raw));
143        names
144            .iter()
145            .filter_map(|name| name.as_str().map(str::to_owned))
146            .collect()
147    }
148
149    /// Iterates the focus stack from the module in focus downwards.
150    pub fn focus_stack(&self) -> FocusStack<'_> {
151        FocusStack {
152            environment: self,
153            current: std::ptr::null_mut(),
154        }
155    }
156}