1use std::ffi::{CStr, CString};
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::construct::Defgeneric;
8use crate::{Environment, Result, Value, ffi};
9
10pub struct Defmethod<'env> {
12 generic: NonNull<ffi::Defgeneric>,
13 index: u16,
14 marker: PhantomData<&'env Environment>,
15}
16
17impl Defmethod<'_> {
18 pub fn index(&self) -> u16 {
21 self.index
22 }
23
24 pub fn is_deletable(&self) -> bool {
26 unsafe { ffi::DefmethodIsDeletable(self.generic.as_ptr(), self.index) }
27 }
28
29 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 pub fn watched(&self) -> bool {
42 unsafe { ffi::DefmethodGetWatch(self.generic.as_ptr(), self.index) }
43 }
44
45 pub fn set_watched(&mut self, enabled: bool) {
47 unsafe { ffi::DefmethodSetWatch(self.generic.as_ptr(), self.index, enabled) }
48 }
49
50 pub fn restrictions(&self) -> Option<MethodRestrictions> {
58 let mut raw = ffi::CLIPSValue {
59 value: std::ptr::null_mut(),
60 };
61 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 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 max_arguments: (max_arguments >= 0).then_some(max_arguments),
97 parameters,
98 })
99 }
100}
101
102#[derive(Clone, Debug, Eq, PartialEq)]
104pub struct MethodRestrictions {
105 pub min_arguments: i64,
107 pub max_arguments: Option<i64>,
109 pub parameters: Vec<ParameterRestriction>,
111}
112
113#[derive(Clone, Debug, Eq, PartialEq)]
115pub struct ParameterRestriction {
116 pub has_query: bool,
118 pub allowed_classes: Vec<String>,
120}
121
122enum 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
150pub 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 pub fn methods(&self) -> Defmethods<'env> {
173 Defmethods {
174 generic: self.raw,
175 current: 0,
176 marker: PhantomData,
177 }
178 }
179
180 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 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 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 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 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 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 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 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 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 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 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 pub fn reset_globals(&self) -> bool {
331 unsafe { ffi::GetResetGlobals(self.raw.as_ptr()) }
332 }
333
334 pub fn set_reset_globals(&mut self, enabled: bool) -> bool {
336 unsafe { ffi::SetResetGlobals(self.raw.as_ptr(), enabled) }
337 }
338
339 pub fn globals_changed(&self) -> bool {
341 unsafe { ffi::GetGlobalsChanged(self.raw.as_ptr()) }
342 }
343
344 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}