1use std::ffi::{CString, NulError};
4
5use crate::{Deftemplate, Multifield, Value, ffi};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum SlotDefaultType {
10 None,
12 Static,
14 Dynamic,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum TemplateError {
22 InteriorNul,
24 SlotNotFound(String),
26 QueryFailed {
28 slot: String,
30 query: &'static str,
32 },
33 UnexpectedResult {
36 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
70pub struct TemplateSlot<'template, 'env> {
72 template: &'template Deftemplate<'env>,
73 name: CString,
74}
75
76impl<'env> Deftemplate<'env> {
77 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 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 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 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 pub fn name(&self) -> &str {
139 self.name.to_str().expect("validated deftemplate slot name")
140 }
141
142 pub fn is_multislot(&self) -> bool {
144 unsafe { ffi::DeftemplateSlotMultiP(self.template.raw.as_ptr(), self.name_ptr()) }
145 }
146
147 pub fn is_single_slot(&self) -> bool {
149 unsafe { ffi::DeftemplateSlotSingleP(self.template.raw.as_ptr(), self.name_ptr()) }
150 }
151
152 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 pub fn default_value(&self) -> Result<Value<'env>, TemplateError> {
166 self.value_query("default value", ffi::DeftemplateSlotDefaultValue)
167 }
168
169 pub fn allowed_types(&self) -> Result<Multifield<'env>, TemplateError> {
171 self.multifield_query("allowed types", ffi::DeftemplateSlotTypes)
172 }
173
174 pub fn allowed_values(&self) -> Result<Multifield<'env>, TemplateError> {
176 self.multifield_query("allowed values", ffi::DeftemplateSlotAllowedValues)
177 }
178
179 pub fn range(&self) -> Result<Multifield<'env>, TemplateError> {
181 self.multifield_query("range", ffi::DeftemplateSlotRange)
182 }
183
184 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}