use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::ptr::NonNull;
use crate::construct::Defgeneric;
use crate::{Environment, Result, Value, ffi};
pub struct Defmethod<'env> {
generic: NonNull<ffi::Defgeneric>,
index: u16,
marker: PhantomData<&'env Environment>,
}
impl Defmethod<'_> {
pub fn index(&self) -> u16 {
self.index
}
pub fn is_deletable(&self) -> bool {
unsafe { ffi::DefmethodIsDeletable(self.generic.as_ptr(), self.index) }
}
pub fn pretty_print(&self) -> Option<&str> {
let value = unsafe { ffi::DefmethodPPForm(self.generic.as_ptr(), self.index) };
if value.is_null() {
None
} else {
unsafe { CStr::from_ptr(value) }.to_str().ok()
}
}
pub fn watched(&self) -> bool {
unsafe { ffi::DefmethodGetWatch(self.generic.as_ptr(), self.index) }
}
pub fn set_watched(&mut self, enabled: bool) {
unsafe { ffi::DefmethodSetWatch(self.generic.as_ptr(), self.index, enabled) }
}
pub fn restrictions(&self) -> Option<MethodRestrictions> {
let mut raw = ffi::CLIPSValue {
value: std::ptr::null_mut(),
};
unsafe { ffi::GetMethodRestrictions(self.generic.as_ptr(), self.index, &mut raw) };
let fields = unsafe { flatten(&raw) };
let integer = |index: usize| match fields.get(index) {
Some(Field::Integer(value)) => Some(*value),
_ => None,
};
let min_arguments = integer(0)?;
let max_arguments = integer(1)?;
let count = usize::try_from(integer(2)?).ok()?;
let mut parameters = Vec::with_capacity(count);
for slot in 0..count {
let start = usize::try_from(integer(3 + slot)?).ok()?.checked_sub(1)?;
let has_query =
matches!(fields.get(start), Some(Field::Lexeme(text)) if text == "TRUE");
let classes = usize::try_from(integer(start + 1)?).ok()?;
let allowed_classes = (0..classes)
.map(|offset| match fields.get(start + 2 + offset) {
Some(Field::Lexeme(name)) => Some(name.clone()),
_ => None,
})
.collect::<Option<Vec<_>>>()?;
parameters.push(ParameterRestriction {
has_query,
allowed_classes,
});
}
Some(MethodRestrictions {
min_arguments,
max_arguments: (max_arguments >= 0).then_some(max_arguments),
parameters,
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MethodRestrictions {
pub min_arguments: i64,
pub max_arguments: Option<i64>,
pub parameters: Vec<ParameterRestriction>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterRestriction {
pub has_query: bool,
pub allowed_classes: Vec<String>,
}
enum Field {
Integer(i64),
Lexeme(String),
Other,
}
unsafe fn flatten(value: &ffi::CLIPSValue) -> Vec<Field> {
if unsafe { value.value.is_null() } || unsafe { (*value.header).type_ } != 4 {
return Vec::new();
}
let multifield = unsafe { &*value.multifield };
(0..multifield.length)
.map(|index| {
let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
match unsafe { (*cell.header).type_ } {
1 => Field::Integer(unsafe { (*cell.integer).contents }),
2 | 3 | 8 => Field::Lexeme(
unsafe { CStr::from_ptr((*cell.lexeme).contents) }
.to_string_lossy()
.into_owned(),
),
_ => Field::Other,
}
})
.collect()
}
pub struct Defmethods<'env> {
generic: NonNull<ffi::Defgeneric>,
current: u16,
marker: PhantomData<&'env Environment>,
}
impl<'env> Iterator for Defmethods<'env> {
type Item = Defmethod<'env>;
fn next(&mut self) -> Option<Self::Item> {
self.current = unsafe { ffi::GetNextDefmethod(self.generic.as_ptr(), self.current) };
(self.current != 0).then_some(Defmethod {
generic: self.generic,
index: self.current,
marker: PhantomData,
})
}
}
impl<'env> Defgeneric<'env> {
pub fn methods(&self) -> Defmethods<'env> {
Defmethods {
generic: self.raw,
current: 0,
marker: PhantomData,
}
}
pub fn method(&self, index: u16) -> Option<Defmethod<'env>> {
(index != 0
&& unsafe { !ffi::GetDefmethodPointer(self.raw.as_ptr(), index.into()).is_null() })
.then_some(Defmethod {
generic: self.raw,
index,
marker: PhantomData,
})
}
}
impl Environment {
pub fn undefine_defmethod(&mut self, generic: &str, index: u16) -> Result<bool> {
if index == 0 {
return Ok(false);
}
let generic = CString::new(generic)?;
let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
Ok(!generic.is_null() && unsafe { ffi::Undefmethod(generic, index, self.raw.as_ptr()) })
}
pub fn defmethod_restrictions(&self, generic: &str, index: u16) -> Result<Option<Value<'_>>> {
let generic = CString::new(generic)?;
let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
if generic.is_null()
|| index == 0
|| unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
{
return Ok(None);
}
let mut raw = ffi::CLIPSValue {
value: std::ptr::null_mut(),
};
unsafe {
ffi::GetMethodRestrictions(generic, index, &mut raw);
ffi::RetainCV(self.raw.as_ptr(), &mut raw);
}
Ok(Some(Value::new(self, raw)))
}
pub fn defmethod_description(&self, generic: &str, index: u16) -> Result<Option<String>> {
let generic = CString::new(generic)?;
let generic = unsafe { ffi::FindDefgeneric(self.raw.as_ptr(), generic.as_ptr()) };
if generic.is_null()
|| index == 0
|| unsafe { ffi::GetDefmethodPointer(generic, index.into()).is_null() }
{
return Ok(None);
}
let builder = unsafe { ffi::CreateStringBuilder(self.raw.as_ptr(), 128) };
if builder.is_null() {
return Ok(None);
}
unsafe { ffi::DefmethodDescription(generic, index, builder) };
let description = unsafe { CStr::from_ptr((*builder).contents) }
.to_string_lossy()
.into_owned();
unsafe { ffi::SBDispose(builder) };
Ok(Some(description))
}
pub fn defglobal_value(&self, name: &str) -> Result<Option<Value<'_>>> {
let name = CString::new(name)?;
let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
if global.is_null() {
return Ok(None);
}
let mut raw = ffi::CLIPSValue {
value: std::ptr::null_mut(),
};
unsafe {
ffi::DefglobalGetValue(global, &mut raw);
ffi::RetainCV(self.raw.as_ptr(), &mut raw);
}
Ok(Some(Value::new(self, raw)))
}
pub fn set_defglobal_integer(&mut self, name: &str, value: i64) -> Result<bool> {
let name = CString::new(name)?;
let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
if global.is_null() {
return Ok(false);
}
unsafe { ffi::DefglobalSetInteger(global, value) };
Ok(true)
}
pub fn set_defglobal_float(&mut self, name: &str, value: f64) -> Result<bool> {
let name = CString::new(name)?;
let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
if global.is_null() {
return Ok(false);
}
unsafe { ffi::DefglobalSetFloat(global, value) };
Ok(true)
}
pub fn set_defglobal_symbol(&mut self, name: &str, value: &str) -> Result<bool> {
self.set_defglobal_lexeme(name, value, ffi::DefglobalSetSymbol)
}
pub fn set_defglobal_string(&mut self, name: &str, value: &str) -> Result<bool> {
self.set_defglobal_lexeme(name, value, ffi::DefglobalSetString)
}
pub fn set_defglobal_instance_name(&mut self, name: &str, value: &str) -> Result<bool> {
self.set_defglobal_lexeme(name, value, ffi::DefglobalSetInstanceName)
}
pub fn set_defglobal_value(&self, name: &str, value: &Value<'_>) -> Result<bool> {
let mut raw = self.check_value(value)?;
let name = CString::new(name)?;
let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
if global.is_null() {
return Ok(false);
}
unsafe { ffi::DefglobalSetValue(global, &mut raw) };
Ok(true)
}
pub fn reset_globals(&self) -> bool {
unsafe { ffi::GetResetGlobals(self.raw.as_ptr()) }
}
pub fn set_reset_globals(&mut self, enabled: bool) -> bool {
unsafe { ffi::SetResetGlobals(self.raw.as_ptr(), enabled) }
}
pub fn globals_changed(&self) -> bool {
unsafe { ffi::GetGlobalsChanged(self.raw.as_ptr()) }
}
pub fn set_globals_changed(&self, changed: bool) {
unsafe { ffi::SetGlobalsChanged(self.raw.as_ptr(), changed) }
}
fn set_defglobal_lexeme(
&mut self,
name: &str,
value: &str,
setter: unsafe extern "C" fn(*mut ffi::Defglobal, *const std::ffi::c_char),
) -> Result<bool> {
let name = CString::new(name)?;
let value = CString::new(value)?;
let global = unsafe { ffi::FindDefglobal(self.raw.as_ptr(), name.as_ptr()) };
if global.is_null() {
return Ok(false);
}
unsafe { setter(global, value.as_ptr()) };
Ok(true)
}
}