Skip to main content

clips_bindings/
generic.rs

1//! Defgenerics, their methods, and defglobal values.
2
3use std::ffi::{CStr, CString};
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::construct::Defgeneric;
8use crate::{Environment, Result, Value, ffi};
9
10/// A method belonging to a [`Defgeneric`].
11pub struct Defmethod<'env> {
12    generic: NonNull<ffi::Defgeneric>,
13    index: u16,
14    marker: PhantomData<&'env Environment>,
15}
16
17impl Defmethod<'_> {
18    /// The method's index within its generic function, which is how CLIPS
19    /// identifies it for undefinition.
20    pub fn index(&self) -> u16 {
21        self.index
22    }
23
24    /// Whether the method can currently be undefined.
25    pub fn is_deletable(&self) -> bool {
26        unsafe { ffi::DefmethodIsDeletable(self.generic.as_ptr(), self.index) }
27    }
28
29    /// The method's source text as CLIPS reformats it, or `None` when no
30    /// pretty-print form is stored.
31    pub fn pretty_print(&self) -> Option<&str> {
32        let value = unsafe { ffi::DefmethodPPForm(self.generic.as_ptr(), self.index) };
33        if value.is_null() {
34            None
35        } else {
36            unsafe { CStr::from_ptr(value) }.to_str().ok()
37        }
38    }
39
40    /// Whether CLIPS traces this method as it runs.
41    pub fn watched(&self) -> bool {
42        unsafe { ffi::DefmethodGetWatch(self.generic.as_ptr(), self.index) }
43    }
44
45    /// Enables or disables tracing of this method.
46    pub fn set_watched(&mut self, enabled: bool) {
47        unsafe { ffi::DefmethodSetWatch(self.generic.as_ptr(), self.index, enabled) }
48    }
49
50    /// The method's arity and per-parameter restrictions in structured form.
51    ///
52    /// CLIPS returns this as a flat multifield whose layout is documented in
53    /// `genrccom.c`: minimum arity, maximum arity, restriction count, one index
54    /// per restriction, then each restriction as a query flag, a class count,
55    /// and that many class names. Returns `None` if CLIPS reports a layout this
56    /// parser does not recognise.
57    pub fn restrictions(&self) -> Option<MethodRestrictions> {
58        let mut raw = ffi::CLIPSValue {
59            value: std::ptr::null_mut(),
60        };
61        // The multifield is read before returning to CLIPS, so it does not need
62        // to be retained.
63        unsafe { ffi::GetMethodRestrictions(self.generic.as_ptr(), self.index, &mut raw) };
64        let fields = unsafe { flatten(&raw) };
65
66        let integer = |index: usize| match fields.get(index) {
67            Some(Field::Integer(value)) => Some(*value),
68            _ => None,
69        };
70        let min_arguments = integer(0)?;
71        let max_arguments = integer(1)?;
72        let count = usize::try_from(integer(2)?).ok()?;
73
74        let mut parameters = Vec::with_capacity(count);
75        for slot in 0..count {
76            // The index table is one-based over the whole multifield.
77            let start = usize::try_from(integer(3 + slot)?).ok()?.checked_sub(1)?;
78            let has_query =
79                matches!(fields.get(start), Some(Field::Lexeme(text)) if text == "TRUE");
80            let classes = usize::try_from(integer(start + 1)?).ok()?;
81            let allowed_classes = (0..classes)
82                .map(|offset| match fields.get(start + 2 + offset) {
83                    Some(Field::Lexeme(name)) => Some(name.clone()),
84                    _ => None,
85                })
86                .collect::<Option<Vec<_>>>()?;
87            parameters.push(ParameterRestriction {
88                has_query,
89                allowed_classes,
90            });
91        }
92
93        Some(MethodRestrictions {
94            min_arguments,
95            // CLIPS reports -1 for a wildcard parameter.
96            max_arguments: (max_arguments >= 0).then_some(max_arguments),
97            parameters,
98        })
99    }
100}
101
102/// A method's arity and parameter restrictions.
103#[derive(Clone, Debug, Eq, PartialEq)]
104pub struct MethodRestrictions {
105    /// The number of arguments the method requires.
106    pub min_arguments: i64,
107    /// `None` when the method accepts a wildcard number of arguments.
108    pub max_arguments: Option<i64>,
109    /// One entry per restricted parameter, in order.
110    pub parameters: Vec<ParameterRestriction>,
111}
112
113/// The restrictions on one method parameter.
114#[derive(Clone, Debug, Eq, PartialEq)]
115pub struct ParameterRestriction {
116    /// Whether the parameter has a query expression, for example `(= 1 1)`.
117    pub has_query: bool,
118    /// The classes the argument must belong to, empty when unrestricted.
119    pub allowed_classes: Vec<String>,
120}
121
122/// One decoded field of a CLIPS multifield.
123enum Field {
124    Integer(i64),
125    Lexeme(String),
126    Other,
127}
128
129unsafe fn flatten(value: &ffi::CLIPSValue) -> Vec<Field> {
130    if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
131        return Vec::new();
132    }
133    let multifield = unsafe { &*value.multifield };
134    (0..multifield.length)
135        .map(|index| {
136            let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
137            match unsafe { (*cell.header).type_ } {
138                1 => Field::Integer(unsafe { (*cell.integer).contents }),
139                2 | 3 | 8 => Field::Lexeme(
140                    unsafe { CStr::from_ptr((*cell.lexeme).contents) }
141                        .to_string_lossy()
142                        .into_owned(),
143                ),
144                _ => Field::Other,
145            }
146        })
147        .collect()
148}
149
150/// Iterates a generic function's methods in index order.
151pub struct Defmethods<'env> {
152    generic: NonNull<ffi::Defgeneric>,
153    current: u16,
154    marker: PhantomData<&'env Environment>,
155}
156
157impl<'env> Iterator for Defmethods<'env> {
158    type Item = Defmethod<'env>;
159
160    fn next(&mut self) -> Option<Self::Item> {
161        self.current = unsafe { ffi::GetNextDefmethod(self.generic.as_ptr(), self.current) };
162        (self.current != 0).then_some(Defmethod {
163            generic: self.generic,
164            index: self.current,
165            marker: PhantomData,
166        })
167    }
168}
169
170impl<'env> Defgeneric<'env> {
171    /// Iterates this generic function's methods.
172    pub fn methods(&self) -> Defmethods<'env> {
173        Defmethods {
174            generic: self.raw,
175            current: 0,
176            marker: PhantomData,
177        }
178    }
179
180    /// One method by index, or `None` if the generic has no such method.
181    /// Index 0 is never valid.
182    pub fn method(&self, index: u16) -> Option<Defmethod<'env>> {
183        (index != 0
184            && unsafe { !ffi::GetDefmethodPointer(self.raw.as_ptr(), index.into()).is_null() })
185        .then_some(Defmethod {
186            generic: self.raw,
187            index,
188            marker: PhantomData,
189        })
190    }
191}
192
193impl Environment {
194    /// Undefines one method of a generic function, returning whether it was
195    /// removed.
196    ///
197    /// Both the generic and the index are resolved here, under `&mut self`, so
198    /// no method handle can outlive the method it names.
199    pub fn undefine_defmethod(&mut self, generic: &str, index: u16) -> Result<bool> {
200        if index == 0 {
201            return Ok(false);
202        }
203        let generic = CString::new(generic)?;
204        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
205        Ok(!generic.is_null() && unsafe { ffi::Undefmethod(generic, index, self.raw.as_ptr()) })
206    }
207
208    /// A method's restrictions as the raw CLIPS multifield.
209    ///
210    /// [`Defmethod::restrictions`] decodes the same data into a structured
211    /// form; this is for callers that want the untouched value.
212    pub fn defmethod_restrictions(&self, generic: &str, index: u16) -> Result<Option<Value<'_>>> {
213        let generic = CString::new(generic)?;
214        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
215        if generic.is_null()
216            || index == 0
217            || unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
218        {
219            return Ok(None);
220        }
221        let mut raw = ffi::CLIPSValue {
222            value: std::ptr::null_mut(),
223        };
224        unsafe {
225            ffi::GetMethodRestrictions(generic, index, &mut raw);
226            ffi::RetainCV(self.raw.as_ptr(), &mut raw);
227        }
228        Ok(Some(Value::new(self, raw)))
229    }
230
231    /// CLIPS's own textual summary of a method's parameter restrictions.
232    ///
233    /// `None` when the generic or method does not exist.
234    pub fn defmethod_description(&self, generic: &str, index: u16) -> Result<Option<String>> {
235        let generic = CString::new(generic)?;
236        let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
237        if generic.is_null()
238            || index == 0
239            || unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
240        {
241            return Ok(None);
242        }
243        let builder = unsafe { ffi::CreateStringBuilder(self.raw.as_ptr(), 128) };
244        if builder.is_null() {
245            return Ok(None);
246        }
247        unsafe { ffi::DefmethodDescription(generic, index, builder) };
248        let description = unsafe { CStr::from_ptr((*builder).contents) }
249            .to_string_lossy()
250            .into_owned();
251        unsafe { ffi::SBDispose(builder) };
252        Ok(Some(description))
253    }
254
255    /// A defglobal's current value, retained. `None` if no such global exists.
256    ///
257    /// The name is given without the `?*` decoration, so `?*count*` is
258    /// `"count"`.
259    pub fn defglobal_value(&self, name: &str) -> Result<Option<Value<'_>>> {
260        let name = CString::new(name)?;
261        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
262        if global.is_null() {
263            return Ok(None);
264        }
265        let mut raw = ffi::CLIPSValue {
266            value: std::ptr::null_mut(),
267        };
268        unsafe {
269            ffi::DefglobalGetValue(global, &mut raw);
270            ffi::RetainCV(self.raw.as_ptr(), &mut raw);
271        }
272        Ok(Some(Value::new(self, raw)))
273    }
274
275    /// Sets a defglobal to an integer, returning whether the global exists.
276    pub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool> {
277        let name = CString::new(name)?;
278        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
279        if global.is_null() {
280            return Ok(false);
281        }
282        unsafe { ffi::DefglobalSetInteger(global, value) };
283        Ok(true)
284    }
285
286    /// Sets a defglobal to a float, returning whether the global exists.
287    pub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool> {
288        let name = CString::new(name)?;
289        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
290        if global.is_null() {
291            return Ok(false);
292        }
293        unsafe { ffi::DefglobalSetFloat(global, value) };
294        Ok(true)
295    }
296
297    /// Sets a defglobal to a symbol, returning whether the global exists.
298    pub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool> {
299        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetSymbol)
300    }
301
302    /// Sets a defglobal to a string, returning whether the global exists.
303    pub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool> {
304        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetString)
305    }
306
307    /// Sets a defglobal to an instance name, returning whether the global
308    /// exists.
309    pub fn set_defglobal_instance_name(&mut self, name: &str, value: &str) -> Result<bool> {
310        self.set_defglobal_lexeme(name, value, ffi::DefglobalSetInstanceName)
311    }
312
313    /// Sets a defglobal to an already existing CLIPS value, which is the only
314    /// way to store a fact, instance, or multifield in a global.
315    ///
316    /// Fails with [`crate::Error::ForeignEnvironment`] if `value` belongs to
317    /// another environment.
318    pub fn set_defglobal_value(&self, name: &str, value: &Value<'_>) -> Result<bool> {
319        let mut raw = self.check_value(value)?;
320        let name = CString::new(name)?;
321        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
322        if global.is_null() {
323            return Ok(false);
324        }
325        unsafe { ffi::DefglobalSetValue(global, &mut raw) };
326        Ok(true)
327    }
328
329    /// Whether `reset` restores defglobals to their initial values.
330    pub fn reset_globals(&self) -> bool {
331        unsafe { ffi::GetResetGlobals(self.raw.as_ptr()) }
332    }
333
334    /// Sets the reset behaviour for defglobals and returns the previous value.
335    pub fn set_reset_globals(&mut self, enabled: bool) -> bool {
336        unsafe { ffi::SetResetGlobals(self.raw.as_ptr(), enabled) }
337    }
338
339    /// Whether any defglobal changed since this flag was last cleared.
340    pub fn globals_changed(&self) -> bool {
341        unsafe { ffi::GetGlobalsChanged(self.raw.as_ptr()) }
342    }
343
344    /// Sets or clears the globals-changed flag.
345    pub fn set_globals_changed(&self, changed: bool) {
346        unsafe { ffi::SetGlobalsChanged(self.raw.as_ptr(), changed) }
347    }
348
349    fn set_defglobal_lexeme(
350        &mut self,
351        name: &str,
352        value: &str,
353        setter: unsafe extern "C" fn(*mut ffi::Defglobal, *const std::ffi::c_char),
354    ) -> Result<bool> {
355        let name = CString::new(name)?;
356        let value = CString::new(value)?;
357        let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
358        if global.is_null() {
359            return Ok(false);
360        }
361        unsafe { setter(global, value.as_ptr()) };
362        Ok(true)
363    }
364}