Skip to main content

clips_bindings/
instance.rs

1//! COOL instances, builders, modifiers, and message dispatch.
2//!
3//! An `Instance` is a retained handle: it stays valid while held, and
4//! reports deletion through [`Instance::is_deleted`] rather than dangling.
5
6use std::ffi::{CStr, CString, c_char};
7use std::ptr::NonNull;
8
9use crate::error::{
10    Error, GetSlotError, InstanceBuilderError, MakeInstanceError, PutSlotError, Result,
11    UnmakeInstanceError,
12};
13use crate::{Defclass, Environment, Fact, Multifield, Value, ffi};
14
15/// A COOL instance, retained for as long as the handle lives.
16///
17/// Borrowing the environment is what keeps the handle sound: operations that
18/// could invalidate it, such as `clear` or `reset`, take `&mut Environment` and
19/// so cannot run while one exists.
20pub struct Instance<'env> {
21    pub(crate) raw: NonNull<ffi::Instance>,
22    environment: &'env Environment,
23}
24
25impl<'env> Instance<'env> {
26    pub(crate) fn retained(
27        environment: &'env Environment,
28        raw: *mut ffi::Instance,
29    ) -> Option<Self> {
30        NonNull::new(raw).map(|raw| {
31            unsafe { ffi::RetainInstance(raw.as_ptr()) };
32            Self { raw, environment }
33        })
34    }
35    /// The instance's name, or `""` once the instance has been unmade.
36    ///
37    /// Retaining an instance keeps its record alive but not its name symbol,
38    /// which CLIPS releases on `unmake-instance`; reading the name afterwards
39    /// would dereference freed memory, so it is checked first.
40    pub fn name(&self) -> &str {
41        if self.is_deleted() {
42            return "";
43        }
44        unsafe { CStr::from_ptr(ffi::InstanceName(self.raw.as_ptr())) }
45            .to_str()
46            .unwrap_or("")
47    }
48    /// Whether the instance has been deleted.
49    ///
50    /// The handle stays valid: CLIPS keeps the record alive while it is
51    /// retained, so a deleted instance can still be queried rather than
52    /// dangling.
53    pub fn is_deleted(&self) -> bool {
54        unsafe { ffi::InstanceIsDeleted(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
55    }
56
57    /// Deletes the instance, running its `delete` handler.
58    pub fn unmake(&mut self) -> Result<()> {
59        match unsafe { ffi::UnmakeInstance(self.raw.as_ptr()) } {
60            0 => Ok(()),
61            code => Err(Error::UnmakeInstance(UnmakeInstanceError::from(code))),
62        }
63    }
64
65    /// The instance rendered as `make-instance` syntax.
66    ///
67    /// Empty if CLIPS could not allocate the string builder it prints through.
68    pub fn pretty_print(&self) -> String {
69        unsafe {
70            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
71            if builder.is_null() {
72                return String::new();
73            }
74            ffi::InstancePPForm(self.raw.as_ptr(), builder);
75            let output = CStr::from_ptr((*builder).contents)
76                .to_string_lossy()
77                .into_owned();
78            ffi::SBDispose(builder);
79            output
80        }
81    }
82    /// The class this instance belongs to.
83    pub fn class(&self) -> Option<Defclass<'env>> {
84        NonNull::new(unsafe { ffi::InstanceClass(self.raw.as_ptr()) }).map(|raw| Defclass {
85            raw,
86            _environment: self.environment,
87        })
88    }
89    /// Starts a message send to this instance.
90    ///
91    /// Arguments are appended with the typed methods of [`MessageCall`], so no
92    /// CLIPS argument text is assembled or parsed by the caller.
93    pub fn send(&self, message: &str) -> Result<MessageCall<'env>> {
94        MessageCall::new(self, message)
95    }
96    /// Starts a batched modification.
97    ///
98    /// Unlike the `put_*` methods, slot writes are collected and applied as one
99    /// change when [`InstanceModifier::modify`] is called, so daemons and
100    /// pattern matching run once rather than per slot.
101    pub fn modifier(&self) -> Result<InstanceModifier<'env>> {
102        InstanceModifier::new(self)
103    }
104    fn put(&self, slot: &str, operation: impl FnOnce(*const c_char) -> u32) -> Result<&Self> {
105        let slot = CString::new(slot)?;
106        match operation(slot.as_ptr()) {
107            0 => Ok(self),
108            code => Err(Error::PutSlot(PutSlotError::from(code))),
109        }
110    }
111    /// Writes a slot directly, bypassing message passing.
112    ///
113    /// Unlike [`InstanceModifier`], each call takes effect immediately, so
114    /// slot-level daemons and pattern matching run per assignment.
115    pub fn put_integer(&self, slot: &str, value: i64) -> Result<&Self> {
116        let raw = self.raw.as_ptr();
117        self.put(slot, |slot| unsafe {
118            ffi::DirectPutSlotInteger(raw, slot, value)
119        })
120    }
121    /// Writes a float slot directly. See [`Instance::put_integer`].
122    pub fn put_float(&self, slot: &str, value: f64) -> Result<&Self> {
123        let raw = self.raw.as_ptr();
124        self.put(slot, |slot| unsafe {
125            ffi::DirectPutSlotFloat(raw, slot, value)
126        })
127    }
128    /// Writes a symbol slot directly. See [`Instance::put_integer`].
129    pub fn put_symbol(&self, slot: &str, value: &str) -> Result<&Self> {
130        let value = CString::new(value)?;
131        let raw = self.raw.as_ptr();
132        self.put(slot, |slot| unsafe {
133            ffi::DirectPutSlotSymbol(raw, slot, value.as_ptr())
134        })
135    }
136    /// Writes a string slot directly. See [`Instance::put_integer`].
137    pub fn put_string(&self, slot: &str, value: &str) -> Result<&Self> {
138        let value = CString::new(value)?;
139        let raw = self.raw.as_ptr();
140        self.put(slot, |slot| unsafe {
141            ffi::DirectPutSlotString(raw, slot, value.as_ptr())
142        })
143    }
144    /// Writes an instance-name slot directly. See [`Instance::put_integer`].
145    pub fn put_instance_name(&self, slot: &str, value: &str) -> Result<&Self> {
146        let value = CString::new(value)?;
147        let raw = self.raw.as_ptr();
148        self.put(slot, |slot| unsafe {
149            ffi::DirectPutSlotInstanceName(raw, slot, value.as_ptr())
150        })
151    }
152    /// Writes a fact address to a slot directly. See [`Instance::put_integer`].
153    pub fn put_fact(&self, slot: &str, value: &Fact<'env>) -> Result<&Self> {
154        let raw = self.raw.as_ptr();
155        self.put(slot, |slot| unsafe {
156            ffi::DirectPutSlotFact(raw, slot, value.raw.as_ptr())
157        })
158    }
159    /// Writes an instance address to a slot directly. See
160    /// [`Instance::put_integer`].
161    pub fn put_instance(&self, slot: &str, value: &Instance<'env>) -> Result<&Self> {
162        let raw = self.raw.as_ptr();
163        self.put(slot, |slot| unsafe {
164            ffi::DirectPutSlotInstance(raw, slot, value.raw.as_ptr())
165        })
166    }
167    /// Writes a multifield slot directly. See [`Instance::put_integer`].
168    pub fn put_multifield(&self, slot: &str, value: &Multifield<'env>) -> Result<&Self> {
169        let raw = self.raw.as_ptr();
170        self.put(slot, |slot| unsafe {
171            ffi::DirectPutSlotMultifield(raw, slot, value.raw())
172        })
173    }
174    /// Writes an already existing CLIPS value to a slot.
175    ///
176    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
177    /// environment, since CLIPS atoms are interned per environment.
178    pub fn put_value(&self, slot: &str, value: &Value<'env>) -> Result<&Self> {
179        let mut cv = self.environment.check_value(value)?;
180        let raw = self.raw.as_ptr();
181        self.put(slot, |slot| unsafe {
182            ffi::DirectPutSlot(raw, slot, &mut cv)
183        })
184    }
185    /// Reads a slot, bypassing any `get-` accessor handler.
186    ///
187    /// The returned value is retained, so it stays valid independently of the
188    /// instance.
189    pub fn slot(&self, name: &str) -> Result<Value<'env>> {
190        let name = CString::new(name)?;
191        let mut raw = ffi::CLIPSValue {
192            value: std::ptr::null_mut(),
193        };
194        match unsafe { ffi::DirectGetSlot(self.raw.as_ptr(), name.as_ptr(), &mut raw) } {
195            0 => {
196                unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
197                Ok(Value::from_retained_raw(self.environment, raw))
198            }
199            code => Err(Error::GetSlot(GetSlotError::from(code))),
200        }
201    }
202}
203impl Drop for Instance<'_> {
204    fn drop(&mut self) {
205        unsafe { ffi::ReleaseInstance(self.raw.as_ptr()) }
206    }
207}
208
209/// Iterates every instance in the environment, in every module.
210pub struct Instances<'env> {
211    environment: &'env Environment,
212    next: *mut ffi::Instance,
213}
214impl<'env> Instances<'env> {
215    pub(crate) fn new(environment: &'env Environment) -> Self {
216        Self {
217            environment,
218            next: std::ptr::null_mut(),
219        }
220    }
221}
222impl<'env> Iterator for Instances<'env> {
223    type Item = Instance<'env>;
224    fn next(&mut self) -> Option<Self::Item> {
225        self.next = unsafe { ffi::GetNextInstance(self.environment.raw.as_ptr(), self.next) };
226        Instance::retained(self.environment, self.next)
227    }
228}
229
230/// A message send with typed arguments.
231///
232/// CLIPS's C `Send` entry point only accepts arguments as text, so this builds
233/// the call through the function-call builder instead, which takes real CLIPS
234/// values and needs no argument string to be assembled or parsed.
235pub struct MessageCall<'env> {
236    call: crate::FunctionCall<'env>,
237}
238impl<'env> MessageCall<'env> {
239    fn new(instance: &Instance<'env>, message: &str) -> Result<Self> {
240        let mut call = crate::FunctionCall::new(instance.environment, 4)?;
241        call.instance(instance);
242        call.symbol(message)?;
243        Ok(Self { call })
244    }
245    /// Appends an integer argument.
246    pub fn integer(&mut self, value: i64) -> &mut Self {
247        self.call.integer(value);
248        self
249    }
250    /// Appends a float argument.
251    pub fn float(&mut self, value: f64) -> &mut Self {
252        self.call.float(value);
253        self
254    }
255    /// Appends a symbol argument.
256    pub fn symbol(&mut self, value: &str) -> Result<&mut Self> {
257        self.call.symbol(value)?;
258        Ok(self)
259    }
260    /// Appends a string argument.
261    pub fn string(&mut self, value: &str) -> Result<&mut Self> {
262        self.call.string(value)?;
263        Ok(self)
264    }
265    /// Appends an instance-name argument.
266    pub fn instance_name(&mut self, value: &str) -> Result<&mut Self> {
267        self.call.instance_name(value)?;
268        Ok(self)
269    }
270    /// Appends a fact address as an argument.
271    pub fn fact(&mut self, value: &Fact<'env>) -> &mut Self {
272        self.call.fact(value);
273        self
274    }
275    /// Appends an instance address as an argument.
276    pub fn instance(&mut self, value: &Instance<'env>) -> &mut Self {
277        self.call.instance(value);
278        self
279    }
280    /// Appends a multifield argument.
281    pub fn multifield(&mut self, value: &Multifield<'env>) -> &mut Self {
282        self.call.multifield(value);
283        self
284    }
285    /// Appends an existing CLIPS value as an argument.
286    ///
287    /// Fails with [`Error::ForeignEnvironment`] if the value belongs to another
288    /// environment.
289    pub fn value(&mut self, value: &Value<'env>) -> Result<&mut Self> {
290        self.call.value(value)?;
291        Ok(self)
292    }
293    /// Sends the message and returns its retained result.
294    pub fn send(&mut self) -> Result<Value<'env>> {
295        self.call.call("send")
296    }
297}
298
299/// Iterator over the direct instances of one class.
300pub struct InstancesInClass<'env> {
301    environment: &'env Environment,
302    class: NonNull<ffi::Defclass>,
303    next: *mut ffi::Instance,
304}
305impl<'env> Iterator for InstancesInClass<'env> {
306    type Item = Instance<'env>;
307    fn next(&mut self) -> Option<Self::Item> {
308        self.next = unsafe { ffi::GetNextInstanceInClass(self.class.as_ptr(), self.next) };
309        Instance::retained(self.environment, self.next)
310    }
311}
312
313impl Environment {
314    /// Creates an instance from CLIPS `make-instance` syntax, for example
315    /// `([ada] of PERSON (age 36))`.
316    pub fn make_instance(&self, source: &str) -> Result<Instance<'_>> {
317        let source = CString::new(source)?;
318        let raw = unsafe { ffi::MakeInstance(self.raw.as_ptr(), source.as_ptr()) };
319        Instance::retained(self, raw).ok_or_else(|| {
320            // CLIPS can decline to create an instance while leaving the error
321            // code clear, so a null result is never reported as success.
322            let code = unsafe { ffi::GetMakeInstanceError(self.raw.as_ptr()) };
323            Error::MakeInstance(if code == 0 {
324                MakeInstanceError::CouldNotCreate
325            } else {
326                MakeInstanceError::from(code)
327            })
328        })
329    }
330    /// Looks an instance up by name.
331    ///
332    /// `module` selects the module to search; `None` searches the current
333    /// module. `search_imports` additionally searches the modules imported by
334    /// it, which is what CLIPS itself does when resolving an instance name.
335    pub fn find_instance<'env>(
336        &'env self,
337        name: &str,
338        module: Option<&crate::Defmodule<'env>>,
339        search_imports: bool,
340    ) -> Result<Option<Instance<'env>>> {
341        let name = CString::new(name)?;
342        let module = module.map_or(std::ptr::null_mut(), |module| module.raw.as_ptr());
343        Ok(Instance::retained(self, unsafe {
344            ffi::FindInstance(self.raw.as_ptr(), module, name.as_ptr(), search_imports)
345        }))
346    }
347    /// Iterates the direct instances of `class`, excluding its subclasses.
348    pub fn instances_in_class<'env>(&'env self, class: &Defclass<'env>) -> InstancesInClass<'env> {
349        InstancesInClass {
350            environment: self,
351            class: class.raw,
352            next: std::ptr::null_mut(),
353        }
354    }
355
356    /// Deletes every instance in every module.
357    pub fn unmake_all_instances(&mut self) -> Result<()> {
358        match unsafe { ffi::UnmakeAllInstances(self.raw.as_ptr()) } {
359            0 => Ok(()),
360            code => Err(Error::UnmakeInstance(UnmakeInstanceError::from(code))),
361        }
362    }
363
364    /// The number of instances in every module, which is what
365    /// [`Environment::instances`] would yield.
366    pub fn instance_count(&self) -> u64 {
367        unsafe { ffi::GetGlobalNumberOfInstances(self.raw.as_ptr()) as u64 }
368    }
369
370    /// Whether the instance list changed since this flag was last cleared.
371    pub fn instances_changed(&self) -> bool {
372        unsafe { ffi::GetInstancesChanged(self.raw.as_ptr()) }
373    }
374
375    /// Sets or clears the instances-changed flag.
376    pub fn set_instances_changed(&self, changed: bool) {
377        unsafe { ffi::SetInstancesChanged(self.raw.as_ptr(), changed) }
378    }
379}
380
381/// Builds an instance slot by slot, then creates it.
382///
383/// Slot values are passed as real CLIPS values rather than as `make-instance`
384/// text, so nothing has to be escaped or re-parsed.
385pub struct InstanceBuilder<'env> {
386    raw: NonNull<ffi::InstanceBuilder>,
387    environment: &'env Environment,
388    made: bool,
389}
390impl<'env> InstanceBuilder<'env> {
391    pub(crate) fn new(environment: &'env Environment, class: &str) -> Result<Self> {
392        let class = CString::new(class)?;
393        NonNull::new(unsafe {
394            ffi::CreateInstanceBuilder(environment.raw.as_ptr(), class.as_ptr())
395        })
396        .map(|raw| Self {
397            raw,
398            environment,
399            made: false,
400        })
401        .ok_or_else(|| {
402            Error::InstanceBuilder(InstanceBuilderError::from(unsafe {
403                ffi::IBError(environment.raw.as_ptr())
404            }))
405        })
406    }
407    fn put(
408        &mut self,
409        slot: &str,
410        operation: impl FnOnce(*const c_char) -> u32,
411    ) -> Result<&mut Self> {
412        let slot = CString::new(slot)?;
413        match operation(slot.as_ptr()) {
414            0 => Ok(self),
415            code => Err(Error::PutSlot(PutSlotError::from(code))),
416        }
417    }
418    /// Sets an integer slot.
419    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
420        let raw = self.raw.as_ptr();
421        self.put(slot, |slot| unsafe {
422            ffi::IBPutSlotInteger(raw, slot, value)
423        })
424    }
425    /// Sets a float slot.
426    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
427        let raw = self.raw.as_ptr();
428        self.put(slot, |slot| unsafe {
429            ffi::IBPutSlotFloat(raw, slot, value)
430        })
431    }
432    /// Sets a symbol slot.
433    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
434        let value = CString::new(value)?;
435        let raw = self.raw.as_ptr();
436        self.put(slot, |slot| unsafe {
437            ffi::IBPutSlotSymbol(raw, slot, value.as_ptr())
438        })
439    }
440    /// Sets a string slot.
441    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
442        let value = CString::new(value)?;
443        let raw = self.raw.as_ptr();
444        self.put(slot, |slot| unsafe {
445            ffi::IBPutSlotString(raw, slot, value.as_ptr())
446        })
447    }
448    /// Sets an instance-name slot.
449    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
450        let value = CString::new(value)?;
451        let raw = self.raw.as_ptr();
452        self.put(slot, |slot| unsafe {
453            ffi::IBPutSlotInstanceName(raw, slot, value.as_ptr())
454        })
455    }
456    /// Sets a slot to a fact address.
457    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
458        let raw = self.raw.as_ptr();
459        self.put(slot, |slot| unsafe {
460            ffi::IBPutSlotFact(raw, slot, value.raw.as_ptr())
461        })
462    }
463    /// Sets a slot to an instance address.
464    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
465        let raw = self.raw.as_ptr();
466        self.put(slot, |slot| unsafe {
467            ffi::IBPutSlotInstance(raw, slot, value.raw.as_ptr())
468        })
469    }
470    /// Sets a multifield slot.
471    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
472        let raw = self.raw.as_ptr();
473        self.put(slot, |slot| unsafe {
474            ffi::IBPutSlotMultifield(raw, slot, value.raw())
475        })
476    }
477    /// Assigns an already existing CLIPS value.
478    ///
479    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
480    /// environment, since CLIPS atoms are interned per environment.
481    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
482        let mut cv = self.environment.check_value(value)?;
483        let raw = self.raw.as_ptr();
484        self.put(slot, |slot| unsafe { ffi::IBPutSlot(raw, slot, &mut cv) })
485    }
486    /// Creates the instance and returns a retained handle to it.
487    ///
488    /// With `None`, CLIPS generates a name of the form `genN`. The builder is
489    /// reusable afterwards, so several instances of the class can be made
490    /// without recreating it.
491    pub fn make(&mut self, name: Option<&str>) -> Result<Instance<'env>> {
492        let name = name.map(CString::new).transpose()?;
493        let raw = unsafe {
494            ffi::IBMake(
495                self.raw.as_ptr(),
496                name.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
497            )
498        };
499        self.made = !raw.is_null();
500        Instance::retained(self.environment, raw).ok_or_else(|| {
501            Error::InstanceBuilder(InstanceBuilderError::from(unsafe {
502                ffi::IBError(self.environment.raw.as_ptr())
503            }))
504        })
505    }
506}
507impl Drop for InstanceBuilder<'_> {
508    fn drop(&mut self) {
509        unsafe {
510            if !self.made {
511                ffi::IBAbort(self.raw.as_ptr())
512            }
513            ffi::IBDispose(self.raw.as_ptr())
514        }
515    }
516}
517
518/// Collects slot changes and applies them as a single modification.
519///
520/// Aborts on drop unless [`InstanceModifier::modify`] was called. Unlike a
521/// fact modification, the instance keeps its identity: the same instance is
522/// updated in place rather than replaced.
523pub struct InstanceModifier<'env> {
524    raw: NonNull<ffi::InstanceModifier>,
525    environment: &'env Environment,
526}
527impl<'env> InstanceModifier<'env> {
528    fn new(instance: &Instance<'env>) -> Result<Self> {
529        NonNull::new(unsafe {
530            ffi::CreateInstanceModifier(instance.environment.raw.as_ptr(), instance.raw.as_ptr())
531        })
532        .map(|raw| Self {
533            raw,
534            environment: instance.environment,
535        })
536        .ok_or_else(|| {
537            Error::InstanceModifier(crate::error::InstanceModifierError::from(unsafe {
538                ffi::IMError(instance.environment.raw.as_ptr())
539            }))
540        })
541    }
542    fn put(
543        &mut self,
544        slot: &str,
545        operation: impl FnOnce(*const c_char) -> u32,
546    ) -> Result<&mut Self> {
547        let slot = CString::new(slot)?;
548        match operation(slot.as_ptr()) {
549            0 => Ok(self),
550            code => Err(Error::PutSlot(PutSlotError::from(code))),
551        }
552    }
553    /// Sets an integer slot.
554    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
555        let raw = self.raw.as_ptr();
556        self.put(slot, |slot| unsafe {
557            ffi::IMPutSlotInteger(raw, slot, value)
558        })
559    }
560    /// Sets a float slot.
561    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
562        let raw = self.raw.as_ptr();
563        self.put(slot, |slot| unsafe {
564            ffi::IMPutSlotFloat(raw, slot, value)
565        })
566    }
567    /// Sets a symbol slot.
568    pub fn symbol(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
569        let value = CString::new(value)?;
570        let raw = self.raw.as_ptr();
571        self.put(slot, |slot| unsafe {
572            ffi::IMPutSlotSymbol(raw, slot, value.as_ptr())
573        })
574    }
575    /// Sets a string slot.
576    pub fn string(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
577        let value = CString::new(value)?;
578        let raw = self.raw.as_ptr();
579        self.put(slot, |slot| unsafe {
580            ffi::IMPutSlotString(raw, slot, value.as_ptr())
581        })
582    }
583    /// Sets an instance-name slot.
584    pub fn instance_name(&mut self, slot: &str, value: &str) -> Result<&mut Self> {
585        let value = CString::new(value)?;
586        let raw = self.raw.as_ptr();
587        self.put(slot, |slot| unsafe {
588            ffi::IMPutSlotInstanceName(raw, slot, value.as_ptr())
589        })
590    }
591    /// Sets a slot to a fact address.
592    pub fn fact(&mut self, slot: &str, value: &Fact<'env>) -> Result<&mut Self> {
593        let raw = self.raw.as_ptr();
594        self.put(slot, |slot| unsafe {
595            ffi::IMPutSlotFact(raw, slot, value.raw.as_ptr())
596        })
597    }
598    /// Sets a slot to an instance address.
599    pub fn instance(&mut self, slot: &str, value: &Instance<'env>) -> Result<&mut Self> {
600        let raw = self.raw.as_ptr();
601        self.put(slot, |slot| unsafe {
602            ffi::IMPutSlotInstance(raw, slot, value.raw.as_ptr())
603        })
604    }
605    /// Sets a multifield slot.
606    pub fn multifield(&mut self, slot: &str, value: &Multifield<'env>) -> Result<&mut Self> {
607        let raw = self.raw.as_ptr();
608        self.put(slot, |slot| unsafe {
609            ffi::IMPutSlotMultifield(raw, slot, value.raw())
610        })
611    }
612    /// Assigns an already existing CLIPS value.
613    ///
614    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
615    /// environment, since CLIPS atoms are interned per environment.
616    pub fn value(&mut self, slot: &str, value: &Value<'env>) -> Result<&mut Self> {
617        let mut cv = self.environment.check_value(value)?;
618        let raw = self.raw.as_ptr();
619        self.put(slot, |slot| unsafe { ffi::IMPutSlot(raw, slot, &mut cv) })
620    }
621    /// Applies the collected changes, running slot daemons once for the batch.
622    ///
623    /// Slots left unset keep their current values.
624    pub fn modify(&mut self) -> Result<Instance<'env>> {
625        let raw = unsafe { ffi::IMModify(self.raw.as_ptr()) };
626        Instance::retained(self.environment, raw).ok_or_else(|| {
627            Error::InstanceModifier(crate::error::InstanceModifierError::from(unsafe {
628                ffi::IMError(self.environment.raw.as_ptr())
629            }))
630        })
631    }
632    /// Discards the collected changes, leaving the instance untouched.
633    pub fn abort(&mut self) {
634        unsafe { ffi::IMAbort(self.raw.as_ptr()) }
635    }
636}
637impl Drop for InstanceModifier<'_> {
638    fn drop(&mut self) {
639        unsafe {
640            ffi::IMAbort(self.raw.as_ptr());
641            ffi::IMDispose(self.raw.as_ptr())
642        }
643    }
644}