use std::ffi::{CStr, CString};
use std::ptr::NonNull;
use crate::error::{
AssertionError, Error, FactBuilderError, GetSlotError, PutSlotError, Result, RetractionError,
};
use crate::{Deftemplate, Environment, Instance, Multifield, Value, ffi};
pub struct Fact<'env> {
pub(crate) raw: NonNull<ffi::Fact>,
environment: &'env Environment,
}
impl<'env> Fact<'env> {
pub(crate) fn retained(environment: &'env Environment, raw: *mut ffi::Fact) -> Option<Self> {
NonNull::new(raw).map(|raw| {
unsafe { ffi::RetainFact(raw.as_ptr()) };
Self { raw, environment }
})
}
pub(crate) fn from_result(
environment: &'env Environment,
raw: *mut ffi::Fact,
code: u32,
) -> Result<Self> {
Self::retained(environment, raw).ok_or(Error::Assertion(AssertionError::from(code)))
}
pub fn index(&self) -> i64 {
unsafe { ffi::FactIndex(self.raw.as_ptr()) }
}
pub fn is_retracted(&self) -> bool {
unsafe { ffi::FactIsDeleted(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
}
pub fn retract(&mut self) -> Result<()> {
match unsafe { ffi::Retract(self.raw.as_ptr()) } {
0 => Ok(()),
code => Err(Error::Retraction(RetractionError::from(code))),
}
}
pub fn pretty_print(&self, ignore_defaults: bool) -> String {
unsafe {
let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
if builder.is_null() {
return String::new();
}
ffi::FactPPForm(self.raw.as_ptr(), builder, ignore_defaults);
let output = CStr::from_ptr((*builder).contents)
.to_string_lossy()
.into_owned();
ffi::SBDispose(builder);
output
}
}
pub fn relation(&self) -> String {
let lexeme = unsafe { ffi::FactRelation(self.raw.as_ptr()) };
if lexeme.is_null() {
return String::new();
}
unsafe { CStr::from_ptr((*lexeme).contents) }
.to_string_lossy()
.into_owned()
}
pub fn template(&self) -> Option<Deftemplate<'env>> {
NonNull::new(unsafe { ffi::FactDeftemplate(self.raw.as_ptr()) }).map(|raw| Deftemplate {
raw,
_environment: self.environment,
})
}
pub fn slot_names(&self) -> Multifield<'env> {
let mut raw = ffi::CLIPSValue {
value: std::ptr::null_mut(),
};
unsafe { ffi::FactSlotNames(self.raw.as_ptr(), &mut raw) };
Multifield::from_value(Value::retaining(self.environment, raw))
}
pub fn modifier(&self) -> Result<FactModifier<'env>> {
FactModifier::new(self)
}
pub fn slot(&self, name: &str) -> Result<Value<'env>> {
let name = CString::new(name)?;
let mut raw = ffi::CLIPSValue {
value: std::ptr::null_mut(),
};
match unsafe { ffi::GetFactSlot(self.raw.as_ptr(), name.as_ptr(), &mut raw) } {
0 => {
unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
Ok(Value::from_retained_raw(self.environment, raw))
}
code => Err(Error::GetSlot(GetSlotError::from(code))),
}
}
}
impl Drop for Fact<'_> {
fn drop(&mut self) {
unsafe { ffi::ReleaseFact(self.raw.as_ptr()) }
}
}
pub struct Facts<'env> {
environment: &'env Environment,
next: *mut ffi::Fact,
}
impl<'env> Facts<'env> {
pub(crate) fn new(environment: &'env Environment) -> Self {
Self {
environment,
next: std::ptr::null_mut(),
}
}
}
impl<'env> Iterator for Facts<'env> {
type Item = Fact<'env>;
fn next(&mut self) -> Option<Self::Item> {
self.next = unsafe { ffi::GetNextFact(self.environment.raw.as_ptr(), self.next) };
Fact::retained(self.environment, self.next)
}
}
pub struct FactsInTemplate<'env> {
environment: &'env Environment,
template: NonNull<ffi::Deftemplate>,
next: *mut ffi::Fact,
}
impl<'env> Iterator for FactsInTemplate<'env> {
type Item = Fact<'env>;
fn next(&mut self) -> Option<Self::Item> {
self.next = unsafe { ffi::GetNextFactInTemplate(self.template.as_ptr(), self.next) };
Fact::retained(self.environment, self.next)
}
}
impl Environment {
pub fn find_fact(&self, index: i64) -> Option<Fact<'_>> {
Fact::retained(self, unsafe {
ffi::FindIndexedFact(self.raw.as_ptr(), index)
})
}
pub fn facts_in_template<'env>(
&'env self,
template: &Deftemplate<'env>,
) -> FactsInTemplate<'env> {
FactsInTemplate {
environment: self,
template: template.raw,
next: std::ptr::null_mut(),
}
}
pub fn fact_list_changed(&self) -> bool {
unsafe { ffi::GetFactListChanged(self.raw.as_ptr()) }
}
pub fn set_fact_list_changed(&self, changed: bool) {
unsafe { ffi::SetFactListChanged(self.raw.as_ptr(), changed) }
}
pub fn retract_all_facts(&mut self) -> Result<()> {
match unsafe { ffi::RetractAllFacts(self.raw.as_ptr()) } {
0 => Ok(()),
code => Err(Error::Retraction(RetractionError::from(code))),
}
}
}
pub struct FactBuilder<'env> {
raw: NonNull<ffi::FactBuilder>,
environment: &'env Environment,
asserted: bool,
}
impl<'env> FactBuilder<'env> {
pub(crate) fn new(environment: &'env Environment, template: &str) -> Result<Self> {
let template = CString::new(template)?;
NonNull::new(unsafe { ffi::CreateFactBuilder(environment.raw.as_ptr(), template.as_ptr()) })
.map(|raw| Self {
raw,
environment,
asserted: false,
})
.ok_or(Error::FactBuilder(FactBuilderError::from(unsafe {
ffi::FBError(environment.raw.as_ptr())
})))
}
fn put(
&mut self,
slot: &str,
operation: impl FnOnce(*const std::ffi::c_char) -> u32,
) -> Result<&mut Self> {
let slot = CString::new(slot)?;
match operation(slot.as_ptr()) {
0 => Ok(self),
code => Err(Error::PutSlot(PutSlotError::from(code))),
}
}
pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotInteger(raw, slot, value)
})
}
pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotFloat(raw, slot, value)
})
}
pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotSymbol(raw, slot, value.as_ptr())
})
}
pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotString(raw, slot, value.as_ptr())
})
}
pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotInstanceName(raw, slot, value.as_ptr())
})
}
pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotFact(raw, slot, value.raw.as_ptr())
})
}
pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotInstance(raw, slot, value.raw.as_ptr())
})
}
pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FBPutSlotMultifield(raw, slot, value.raw())
})
}
pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
let mut cv = self.environment.check_value(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe { ffi::FBPutSlot(raw, slot, &mut cv) })
}
pub fn assert(&mut self) -> Result<Fact<'env>> {
let raw = unsafe { ffi::FBAssert(self.raw.as_ptr()) };
self.asserted = !raw.is_null();
Fact::from_result(self.environment, raw, unsafe {
ffi::FBError(self.environment.raw.as_ptr())
})
}
}
impl Drop for FactBuilder<'_> {
fn drop(&mut self) {
unsafe {
if !self.asserted {
ffi::FBAbort(self.raw.as_ptr())
}
ffi::FBDispose(self.raw.as_ptr())
}
}
}
pub struct FactModifier<'env> {
raw: NonNull<ffi::FactModifier>,
environment: &'env Environment,
}
impl<'env> FactModifier<'env> {
fn new(fact: &Fact<'env>) -> Result<Self> {
NonNull::new(unsafe {
ffi::CreateFactModifier(fact.environment.raw.as_ptr(), fact.raw.as_ptr())
})
.map(|raw| Self {
raw,
environment: fact.environment,
})
.ok_or_else(|| {
Error::FactModifier(crate::error::FactModifierError::from(unsafe {
ffi::FMError(fact.environment.raw.as_ptr())
}))
})
}
fn put(
&mut self,
slot: &str,
operation: impl FnOnce(*const std::ffi::c_char) -> u32,
) -> Result<&mut Self> {
let slot = CString::new(slot)?;
match operation(slot.as_ptr()) {
0 => Ok(self),
code => Err(Error::PutSlot(PutSlotError::from(code))),
}
}
pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotInteger(raw, slot, value)
})
}
pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotFloat(raw, slot, value)
})
}
pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotSymbol(raw, slot, value.as_ptr())
})
}
pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotString(raw, slot, value.as_ptr())
})
}
pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
let value = CString::new(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotInstanceName(raw, slot, value.as_ptr())
})
}
pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotFact(raw, slot, value.raw.as_ptr())
})
}
pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotInstance(raw, slot, value.raw.as_ptr())
})
}
pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe {
ffi::FMPutSlotMultifield(raw, slot, value.raw())
})
}
pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
let mut cv = self.environment.check_value(value)?;
let raw = self.raw.as_ptr();
self.put(slot, |slot| unsafe { ffi::FMPutSlot(raw, slot, &mut cv) })
}
pub fn modify(&mut self) -> Result<Fact<'env>> {
let raw = unsafe { ffi::FMModify(self.raw.as_ptr()) };
Fact::retained(self.environment, raw).ok_or_else(|| {
Error::FactModifier(crate::error::FactModifierError::from(unsafe {
ffi::FMError(self.environment.raw.as_ptr())
}))
})
}
pub fn abort(&mut self) {
unsafe { ffi::FMAbort(self.raw.as_ptr()) }
}
}
impl Drop for FactModifier<'_> {
fn drop(&mut self) {
unsafe {
ffi::FMAbort(self.raw.as_ptr());
ffi::FMDispose(self.raw.as_ptr())
}
}
}