Skip to main content

clips_bindings/
value.rs

1//! Retained CLIPS values.
2//!
3//! Every value handed out by this crate is retained on creation and
4//! released exactly once on drop, so it stays valid across CLIPS's
5//! garbage-collection points for as long as it is held.
6
7use std::ffi::CStr;
8use std::marker::PhantomData;
9
10use crate::{environment::Environment, ffi};
11
12/// A retained CLIPS value.
13///
14/// The `as_*` accessors return `None` when the value holds a different type,
15/// rather than converting, so a type mismatch is visible instead of silent.
16pub struct Value<'env> {
17    environment: &'env Environment,
18    raw: ffi::CLIPSValue,
19    marker: PhantomData<&'env Environment>,
20}
21
22impl<'env> Value<'env> {
23    pub(crate) fn new(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
24        Self {
25            environment,
26            raw,
27            marker: PhantomData,
28        }
29    }
30    pub(crate) fn from_retained_raw(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
31        Self {
32            environment,
33            raw,
34            marker: PhantomData,
35        }
36    }
37    /// Retains a value CLIPS just created and ties it to `environment`.
38    pub(crate) fn retaining(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
39        let mut raw = raw;
40        unsafe { ffi::RetainCV(environment.raw.as_ptr(), &mut raw) };
41        Self::from_retained_raw(environment, raw)
42    }
43    /// The raw CLIPS type tag: 0 float, 1 integer, 2 symbol, 3 string,
44    /// 4 multifield, 5 external address, 6 fact, 7 instance, 8 instance name,
45    /// 9 void.
46    pub fn type_code(&self) -> u16 {
47        unsafe { (*self.raw.header).type_ }
48    }
49
50    /// The value as an integer, or `None` if it is not one.
51    pub fn as_i64(&self) -> Option<i64> {
52        (self.type_code() == 1).then(|| unsafe { (*self.raw.integer).contents })
53    }
54
55    /// The value as a float, or `None` if it is not one. Integers are not
56    /// converted.
57    pub fn as_f64(&self) -> Option<f64> {
58        (self.type_code() == 0).then(|| unsafe { (*self.raw.float).contents })
59    }
60
61    /// The text of a symbol, string, or instance name.
62    ///
63    /// `None` for other types, and for text that is not valid UTF-8.
64    pub fn as_str(&self) -> Option<&str> {
65        matches!(self.type_code(), 2 | 3 | 8)
66            .then(|| {
67                unsafe { CStr::from_ptr((*self.raw.lexeme).contents) }
68                    .to_str()
69                    .ok()
70            })
71            .flatten()
72    }
73    /// A symbol's truth value.
74    ///
75    /// CLIPS treats every symbol except `FALSE` as true, so this returns
76    /// `Some(true)` for any other symbol, and `None` for non-symbols.
77    pub fn as_bool(&self) -> Option<bool> {
78        (self.type_code() == 2).then(|| self.as_str() != Some("FALSE"))
79    }
80
81    /// The value as a multifield, or `None` if it is not one.
82    pub fn as_multifield(&self) -> Option<crate::Multifield<'env>> {
83        (self.type_code() == 4).then(|| crate::Multifield::from_value(self.clone_retained()))
84    }
85
86    /// The value as a retained fact handle, or `None` if it is not a fact
87    /// address.
88    pub fn as_fact(&self) -> Option<crate::Fact<'env>> {
89        if self.type_code() != 6 {
90            return None;
91        }
92        crate::Fact::retained(self.environment, unsafe { self.raw.fact })
93    }
94
95    /// The value as a retained instance handle, or `None` if it is not an
96    /// instance address.
97    pub fn as_instance(&self) -> Option<crate::Instance<'env>> {
98        if self.type_code() != 7 {
99            return None;
100        }
101        crate::Instance::retained(self.environment, unsafe { self.raw.instance })
102    }
103    pub(crate) fn clone_retained(&self) -> Self {
104        let mut raw = self.raw;
105        unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
106        Self::from_retained_raw(self.environment, raw)
107    }
108    pub(crate) fn raw(&self) -> ffi::CLIPSValue {
109        self.raw
110    }
111    pub(crate) fn environment(&self) -> &'env Environment {
112        self.environment
113    }
114}
115
116impl Drop for Value<'_> {
117    fn drop(&mut self) {
118        unsafe { ffi::ReleaseCV(self.environment.raw.as_ptr(), &mut self.raw) }
119    }
120}
121
122impl std::fmt::Debug for Value<'_> {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        if let Some(value) = self.as_i64() {
125            return value.fmt(f);
126        }
127        if let Some(value) = self.as_f64() {
128            return value.fmt(f);
129        }
130        if let Some(value) = self.as_str() {
131            return value.fmt(f);
132        }
133        f.debug_struct("Value")
134            .field("type_code", &self.type_code())
135            .finish()
136    }
137}