Skip to main content

clips_bindings/
template.rs

1//! Deftemplate slot metadata and constraint inspection.
2
3use std::ffi::{CString, NulError};
4
5use crate::{Deftemplate, Multifield, Value, ffi};
6
7/// What kind of default value a slot has.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum SlotDefaultType {
10    /// No default: the slot must be given a value, as with `(default ?NONE)`.
11    None,
12    /// A fixed value, evaluated once when the construct is defined.
13    Static,
14    /// An expression re-evaluated for each new fact or instance, as with
15    /// `(default-dynamic ...)`.
16    Dynamic,
17}
18
19/// Why a deftemplate slot query failed.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum TemplateError {
22    /// The slot name contained a NUL byte.
23    InteriorNul,
24    /// The template has no slot of that name.
25    SlotNotFound(String),
26    /// CLIPS reported failure for this query on this slot.
27    QueryFailed {
28        /// The slot queried.
29        slot: String,
30        /// The CLIPS query that failed, for example `allowed-values`.
31        query: &'static str,
32    },
33    /// CLIPS returned a value of an unexpected type for the query, which means
34    /// this crate's declaration disagrees with CLIPS.
35    UnexpectedResult {
36        /// The CLIPS query whose result could not be interpreted.
37        query: &'static str,
38    },
39}
40
41impl From<NulError> for TemplateError {
42    fn from(_: NulError) -> Self {
43        Self::InteriorNul
44    }
45}
46
47impl std::fmt::Display for TemplateError {
48    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            Self::InteriorNul => formatter.write_str("slot name contains a NUL byte"),
51            Self::SlotNotFound(slot) => write!(formatter, "deftemplate slot not found: {slot}"),
52            Self::QueryFailed { slot, query } => {
53                write!(
54                    formatter,
55                    "deftemplate {query} query failed for slot {slot}"
56                )
57            }
58            Self::UnexpectedResult { query } => {
59                write!(
60                    formatter,
61                    "deftemplate {query} returned an unexpected value"
62                )
63            }
64        }
65    }
66}
67
68impl std::error::Error for TemplateError {}
69
70/// A named slot borrowed from a deftemplate.
71pub struct TemplateSlot<'template, 'env> {
72    template: &'template Deftemplate<'env>,
73    name: CString,
74}
75
76impl<'env> Deftemplate<'env> {
77    /// Returns all slot names in definition order.
78    ///
79    /// For an implied deftemplate, CLIPS returns its synthetic `implied` slot.
80    pub fn slot_names(&self) -> Result<Vec<String>, TemplateError> {
81        let mut raw = ffi::CLIPSValue {
82            value: std::ptr::null_mut(),
83        };
84        unsafe { ffi::DeftemplateSlotNames(self.raw.as_ptr(), &mut raw) };
85        let value = self.retain_value(raw);
86        let multifield = value
87            .as_multifield()
88            .ok_or(TemplateError::UnexpectedResult {
89                query: "slot names",
90            })?;
91        multifield
92            .iter()
93            .map(|item| {
94                item.as_str()
95                    .map(str::to_owned)
96                    .ok_or(TemplateError::UnexpectedResult {
97                        query: "slot names",
98                    })
99            })
100            .collect()
101    }
102
103    /// Iterates the template's slots in declaration order.
104    pub fn slots(&self) -> Result<impl Iterator<Item = TemplateSlot<'_, 'env>>, TemplateError> {
105        Ok(self.slot_names()?.into_iter().map(|name| TemplateSlot {
106            template: self,
107            name: CString::new(name).expect("CLIPS slot name contains no NUL"),
108        }))
109    }
110
111    /// Whether the template declares a slot of this name.
112    pub fn has_slot(&self, name: &str) -> Result<bool, TemplateError> {
113        let name = CString::new(name)?;
114        Ok(unsafe { ffi::DeftemplateSlotExistP(self.raw.as_ptr(), name.as_ptr()) })
115    }
116
117    /// A handle to one slot's metadata, or `None` if no such slot exists.
118    pub fn slot(&self, name: &str) -> Result<Option<TemplateSlot<'_, 'env>>, TemplateError> {
119        let name_c = CString::new(name)?;
120        Ok(
121            unsafe { ffi::DeftemplateSlotExistP(self.raw.as_ptr(), name_c.as_ptr()) }.then_some(
122                TemplateSlot {
123                    template: self,
124                    name: name_c,
125                },
126            ),
127        )
128    }
129
130    fn retain_value(&self, mut raw: ffi::CLIPSValue) -> Value<'env> {
131        unsafe { ffi::RetainCV(self._environment.raw.as_ptr(), &mut raw) };
132        Value::from_retained_raw(self._environment, raw)
133    }
134}
135
136impl<'env> TemplateSlot<'_, 'env> {
137    /// The slot's name.
138    pub fn name(&self) -> &str {
139        self.name.to_str().expect("validated deftemplate slot name")
140    }
141
142    /// Whether the slot holds a multifield, that is, was declared `multislot`.
143    pub fn is_multislot(&self) -> bool {
144        unsafe { ffi::DeftemplateSlotMultiP(self.template.raw.as_ptr(), self.name_ptr()) }
145    }
146
147    /// Whether the slot holds a single value, that is, was declared `slot`.
148    pub fn is_single_slot(&self) -> bool {
149        unsafe { ffi::DeftemplateSlotSingleP(self.template.raw.as_ptr(), self.name_ptr()) }
150    }
151
152    /// What kind of default the slot declares.
153    pub fn default_type(&self) -> SlotDefaultType {
154        match unsafe { ffi::DeftemplateSlotDefaultP(self.template.raw.as_ptr(), self.name_ptr()) } {
155            1 => SlotDefaultType::Static,
156            2 => SlotDefaultType::Dynamic,
157            _ => SlotDefaultType::None,
158        }
159    }
160
161    /// The slot's default value.
162    ///
163    /// For a dynamic default this is the result of evaluating the expression
164    /// now, not the expression itself.
165    pub fn default_value(&self) -> Result<Value<'env>, TemplateError> {
166        self.value_query("default value", ffi::DeftemplateSlotDefaultValue)
167    }
168
169    /// The type names the slot accepts, as symbols such as `INTEGER`.
170    pub fn allowed_types(&self) -> Result<Multifield<'env>, TemplateError> {
171        self.multifield_query("allowed types", ffi::DeftemplateSlotTypes)
172    }
173
174    /// The values the slot is restricted to, empty when unrestricted.
175    pub fn allowed_values(&self) -> Result<Multifield<'env>, TemplateError> {
176        self.multifield_query("allowed values", ffi::DeftemplateSlotAllowedValues)
177    }
178
179    /// The numeric range as a two-field multifield of minimum and maximum.
180    pub fn range(&self) -> Result<Multifield<'env>, TemplateError> {
181        self.multifield_query("range", ffi::DeftemplateSlotRange)
182    }
183
184    /// A multislot's permitted length, as a two-field multifield of minimum and
185    /// maximum.
186    pub fn cardinality(&self) -> Result<Multifield<'env>, TemplateError> {
187        self.multifield_query("cardinality", ffi::DeftemplateSlotCardinality)
188    }
189
190    fn name_ptr(&self) -> *const std::ffi::c_char {
191        self.name.as_ptr()
192    }
193
194    fn value_query(
195        &self,
196        query: &'static str,
197        function: unsafe extern "C" fn(
198            *mut ffi::Deftemplate,
199            *const std::ffi::c_char,
200            *mut ffi::CLIPSValue,
201        ) -> bool,
202    ) -> Result<Value<'env>, TemplateError> {
203        let mut raw = ffi::CLIPSValue {
204            value: std::ptr::null_mut(),
205        };
206        if !unsafe { function(self.template.raw.as_ptr(), self.name.as_ptr(), &mut raw) } {
207            return Err(TemplateError::QueryFailed {
208                slot: self.name().to_owned(),
209                query,
210            });
211        }
212        Ok(self.template.retain_value(raw))
213    }
214
215    fn multifield_query(
216        &self,
217        query: &'static str,
218        function: unsafe extern "C" fn(
219            *mut ffi::Deftemplate,
220            *const std::ffi::c_char,
221            *mut ffi::CLIPSValue,
222        ) -> bool,
223    ) -> Result<Multifield<'env>, TemplateError> {
224        self.value_query(query, function)?
225            .as_multifield()
226            .ok_or(TemplateError::UnexpectedResult { query })
227    }
228}