clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! COOL instances, builders, modifiers, and message dispatch.
//!
//! An `Instance` is a retained handle: it stays valid while held, and
//! reports deletion through [`Instance::is_deleted`] rather than dangling.

use std::ffi::{CStr, CString, c_char};
use std::ptr::NonNull;

use crate::error::{
    Error, GetSlotError, InstanceBuilderError, MakeInstanceError, PutSlotError, Result,
    UnmakeInstanceError,
};
use crate::{Defclass, Environment, Fact, Multifield, Value, ffi};

/// A COOL instance, retained for as long as the handle lives.
///
/// Borrowing the environment is what keeps the handle sound: operations that
/// could invalidate it, such as `clear` or `reset`, take `&mut Environment` and
/// so cannot run while one exists.
pub struct Instance<'env> {
    pub(crate) raw: NonNull<ffi::Instance>,
    environment: &'env Environment,
}

impl<'env> Instance<'env> {
    pub(crate) fn retained(
        environment: &'env Environment,
        raw: *mut ffi::Instance,
    ) -> Option<Self> {
        NonNull::new(raw).map(|raw| {
            unsafe { ffi::RetainInstance(raw.as_ptr()) };
            Self { raw, environment }
        })
    }
    /// The instance's name, or `""` once the instance has been unmade.
    ///
    /// Retaining an instance keeps its record alive but not its name symbol,
    /// which CLIPS releases on `unmake-instance`; reading the name afterwards
    /// would dereference freed memory, so it is checked first.
    pub fn name(&self) -> &str {
        if self.is_deleted() {
            return "";
        }
        unsafe { CStr::from_ptr(ffi::InstanceName(self.raw.as_ptr())) }
            .to_str()
            .unwrap_or("")
    }
    /// Whether the instance has been deleted.
    ///
    /// The handle stays valid: CLIPS keeps the record alive while it is
    /// retained, so a deleted instance can still be queried rather than
    /// dangling.
    pub fn is_deleted(&self) -> bool {
        unsafe { ffi::InstanceIsDeleted(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
    }

    /// Deletes the instance, running its `delete` handler.
    pub fn unmake(&mut self) -> Result<()> {
        match unsafe { ffi::UnmakeInstance(self.raw.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::UnmakeInstance(UnmakeInstanceError::from(code))),
        }
    }

    /// The instance rendered as `make-instance` syntax.
    ///
    /// Empty if CLIPS could not allocate the string builder it prints through.
    pub fn pretty_print(&self) -> String {
        unsafe {
            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
            if builder.is_null() {
                return String::new();
            }
            ffi::InstancePPForm(self.raw.as_ptr(), builder);
            let output = CStr::from_ptr((*builder).contents)
                .to_string_lossy()
                .into_owned();
            ffi::SBDispose(builder);
            output
        }
    }
    /// The class this instance belongs to.
    pub fn class(&self) -> Option<Defclass<'env>> {
        NonNull::new(unsafe { ffi::InstanceClass(self.raw.as_ptr()) }).map(|raw| Defclass {
            raw,
            _environment: self.environment,
        })
    }
    /// Starts a message send to this instance.
    ///
    /// Arguments are appended with the typed methods of [`MessageCall`], so no
    /// CLIPS argument text is assembled or parsed by the caller.
    pub fn send(&self, message: &str) -> Result<MessageCall<'env>> {
        MessageCall::new(self, message)
    }
    /// Starts a batched modification.
    ///
    /// Unlike the `put_*` methods, slot writes are collected and applied as one
    /// change when [`InstanceModifier::modify`] is called, so daemons and
    /// pattern matching run once rather than per slot.
    pub fn modifier(&self) -> Result<InstanceModifier<'env>> {
        InstanceModifier::new(self)
    }
    fn put(&self, slot: &str, operation: impl FnOnce(*const c_char) -> u32) -> Result<&Self> {
        let slot = CString::new(slot)?;
        match operation(slot.as_ptr()) {
            0 => Ok(self),
            code => Err(Error::PutSlot(PutSlotError::from(code))),
        }
    }
    /// Writes a slot directly, bypassing message passing.
    ///
    /// Unlike [`InstanceModifier`], each call takes effect immediately, so
    /// slot-level daemons and pattern matching run per assignment.
    pub fn put_integer(&self, slot: &str, value: i64) -> Result<&Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotInteger(raw, slot, value)
        })
    }
    /// Writes a float slot directly. See [`Instance::put_integer`].
    pub fn put_float(&self, slot: &str, value: f64) -> Result<&Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotFloat(raw, slot, value)
        })
    }
    /// Writes a symbol slot directly. See [`Instance::put_integer`].
    pub fn put_symbol(&self, slot: &str, value: &str) -> Result<&Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotSymbol(raw, slot, value.as_ptr())
        })
    }
    /// Writes a string slot directly. See [`Instance::put_integer`].
    pub fn put_string(&self, slot: &str, value: &str) -> Result<&Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotString(raw, slot, value.as_ptr())
        })
    }
    /// Writes an instance-name slot directly. See [`Instance::put_integer`].
    pub fn put_instance_name(&self, slot: &str, value: &str) -> Result<&Self> {
        let value = CString::new(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotInstanceName(raw, slot, value.as_ptr())
        })
    }
    /// Writes a fact address to a slot directly. See [`Instance::put_integer`].
    pub fn put_fact(&self, slot: &str, value: &Fact<'env>) -> Result<&Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotFact(raw, slot, value.raw.as_ptr())
        })
    }
    /// Writes an instance address to a slot directly. See
    /// [`Instance::put_integer`].
    pub fn put_instance(&self, slot: &str, value: &Instance<'env>) -> Result<&Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotInstance(raw, slot, value.raw.as_ptr())
        })
    }
    /// Writes a multifield slot directly. See [`Instance::put_integer`].
    pub fn put_multifield(&self, slot: &str, value: &Multifield<'env>) -> Result<&Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlotMultifield(raw, slot, value.raw())
        })
    }
    /// Writes an already existing CLIPS value to a slot.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
    /// environment, since CLIPS atoms are interned per environment.
    pub fn put_value(&self, slot: &str, value: &Value<'env>) -> Result<&Self> {
        let mut cv = self.environment.check_value(value)?;
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::DirectPutSlot(raw, slot, &mut cv)
        })
    }
    /// Reads a slot, bypassing any `get-` accessor handler.
    ///
    /// The returned value is retained, so it stays valid independently of the
    /// instance.
    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::DirectGetSlot(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 Instance<'_> {
    fn drop(&mut self) {
        unsafe { ffi::ReleaseInstance(self.raw.as_ptr()) }
    }
}

/// Iterates every instance in the environment, in every module.
pub struct Instances<'env> {
    environment: &'env Environment,
    next: *mut ffi::Instance,
}
impl<'env> Instances<'env> {
    pub(crate) fn new(environment: &'env Environment) -> Self {
        Self {
            environment,
            next: std::ptr::null_mut(),
        }
    }
}
impl<'env> Iterator for Instances<'env> {
    type Item = Instance<'env>;
    fn next(&mut self) -> Option<Self::Item> {
        self.next = unsafe { ffi::GetNextInstance(self.environment.raw.as_ptr(), self.next) };
        Instance::retained(self.environment, self.next)
    }
}

/// A message send with typed arguments.
///
/// CLIPS's C `Send` entry point only accepts arguments as text, so this builds
/// the call through the function-call builder instead, which takes real CLIPS
/// values and needs no argument string to be assembled or parsed.
pub struct MessageCall<'env> {
    call: crate::FunctionCall<'env>,
}
impl<'env> MessageCall<'env> {
    fn new(instance: &Instance<'env>, message: &str) -> Result<Self> {
        let mut call = crate::FunctionCall::new(instance.environment, 4)?;
        call.instance(instance);
        call.symbol(message)?;
        Ok(Self { call })
    }
    /// Appends an integer argument.
    pub fn integer(&mut self, value: i64) -> &mut Self {
        self.call.integer(value);
        self
    }
    /// Appends a float argument.
    pub fn float(&mut self, value: f64) -> &mut Self {
        self.call.float(value);
        self
    }
    /// Appends a symbol argument.
    pub fn symbol(&mut self, value: &str) -> Result<&mut Self> {
        self.call.symbol(value)?;
        Ok(self)
    }
    /// Appends a string argument.
    pub fn string(&mut self, value: &str) -> Result<&mut Self> {
        self.call.string(value)?;
        Ok(self)
    }
    /// Appends an instance-name argument.
    pub fn instance_name(&mut self, value: &str) -> Result<&mut Self> {
        self.call.instance_name(value)?;
        Ok(self)
    }
    /// Appends a fact address as an argument.
    pub fn fact(&mut self, value: &Fact<'env>) -> &mut Self {
        self.call.fact(value);
        self
    }
    /// Appends an instance address as an argument.
    pub fn instance(&mut self, value: &Instance<'env>) -> &mut Self {
        self.call.instance(value);
        self
    }
    /// Appends a multifield argument.
    pub fn multifield(&mut self, value: &Multifield<'env>) -> &mut Self {
        self.call.multifield(value);
        self
    }
    /// Appends an existing CLIPS value as an argument.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if the value belongs to another
    /// environment.
    pub fn value(&mut self, value: &Value<'env>) -> Result<&mut Self> {
        self.call.value(value)?;
        Ok(self)
    }
    /// Sends the message and returns its retained result.
    pub fn send(&mut self) -> Result<Value<'env>> {
        self.call.call("send")
    }
}

/// Iterator over the direct instances of one class.
pub struct InstancesInClass<'env> {
    environment: &'env Environment,
    class: NonNull<ffi::Defclass>,
    next: *mut ffi::Instance,
}
impl<'env> Iterator for InstancesInClass<'env> {
    type Item = Instance<'env>;
    fn next(&mut self) -> Option<Self::Item> {
        self.next = unsafe { ffi::GetNextInstanceInClass(self.class.as_ptr(), self.next) };
        Instance::retained(self.environment, self.next)
    }
}

impl Environment {
    /// Creates an instance from CLIPS `make-instance` syntax, for example
    /// `([ada] of PERSON (age 36))`.
    pub fn make_instance(&self, source: &str) -> Result<Instance<'_>> {
        let source = CString::new(source)?;
        let raw = unsafe { ffi::MakeInstance(self.raw.as_ptr(), source.as_ptr()) };
        Instance::retained(self, raw).ok_or_else(|| {
            // CLIPS can decline to create an instance while leaving the error
            // code clear, so a null result is never reported as success.
            let code = unsafe { ffi::GetMakeInstanceError(self.raw.as_ptr()) };
            Error::MakeInstance(if code == 0 {
                MakeInstanceError::CouldNotCreate
            } else {
                MakeInstanceError::from(code)
            })
        })
    }
    /// Looks an instance up by name.
    ///
    /// `module` selects the module to search; `None` searches the current
    /// module. `search_imports` additionally searches the modules imported by
    /// it, which is what CLIPS itself does when resolving an instance name.
    pub fn find_instance<'env>(
        &'env self,
        name: &str,
        module: Option<&crate::Defmodule<'env>>,
        search_imports: bool,
    ) -> Result<Option<Instance<'env>>> {
        let name = CString::new(name)?;
        let module = module.map_or(std::ptr::null_mut(), |module| module.raw.as_ptr());
        Ok(Instance::retained(self, unsafe {
            ffi::FindInstance(self.raw.as_ptr(), module, name.as_ptr(), search_imports)
        }))
    }
    /// Iterates the direct instances of `class`, excluding its subclasses.
    pub fn instances_in_class<'env>(&'env self, class: &Defclass<'env>) -> InstancesInClass<'env> {
        InstancesInClass {
            environment: self,
            class: class.raw,
            next: std::ptr::null_mut(),
        }
    }

    /// Deletes every instance in every module.
    pub fn unmake_all_instances(&mut self) -> Result<()> {
        match unsafe { ffi::UnmakeAllInstances(self.raw.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::UnmakeInstance(UnmakeInstanceError::from(code))),
        }
    }

    /// The number of instances in every module, which is what
    /// [`Environment::instances`] would yield.
    pub fn instance_count(&self) -> u64 {
        unsafe { ffi::GetGlobalNumberOfInstances(self.raw.as_ptr()) as u64 }
    }

    /// Whether the instance list changed since this flag was last cleared.
    pub fn instances_changed(&self) -> bool {
        unsafe { ffi::GetInstancesChanged(self.raw.as_ptr()) }
    }

    /// Sets or clears the instances-changed flag.
    pub fn set_instances_changed(&self, changed: bool) {
        unsafe { ffi::SetInstancesChanged(self.raw.as_ptr(), changed) }
    }
}

/// Builds an instance slot by slot, then creates it.
///
/// Slot values are passed as real CLIPS values rather than as `make-instance`
/// text, so nothing has to be escaped or re-parsed.
pub struct InstanceBuilder<'env> {
    raw: NonNull<ffi::InstanceBuilder>,
    environment: &'env Environment,
    made: bool,
}
impl<'env> InstanceBuilder<'env> {
    pub(crate) fn new(environment: &'env Environment, class: &str) -> Result<Self> {
        let class = CString::new(class)?;
        NonNull::new(unsafe {
            ffi::CreateInstanceBuilder(environment.raw.as_ptr(), class.as_ptr())
        })
        .map(|raw| Self {
            raw,
            environment,
            made: false,
        })
        .ok_or_else(|| {
            Error::InstanceBuilder(InstanceBuilderError::from(unsafe {
                ffi::IBError(environment.raw.as_ptr())
            }))
        })
    }
    fn put(
        &mut self,
        slot: &str,
        operation: impl FnOnce(*const 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))),
        }
    }
    /// Sets an integer slot.
    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::IBPutSlotInteger(raw, slot, value)
        })
    }
    /// Sets a float slot.
    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::IBPutSlotFloat(raw, slot, value)
        })
    }
    /// Sets a symbol slot.
    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::IBPutSlotSymbol(raw, slot, value.as_ptr())
        })
    }
    /// Sets a string slot.
    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::IBPutSlotString(raw, slot, value.as_ptr())
        })
    }
    /// Sets an instance-name slot.
    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::IBPutSlotInstanceName(raw, slot, value.as_ptr())
        })
    }
    /// Sets a slot to a fact address.
    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::IBPutSlotFact(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a slot to an instance address.
    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::IBPutSlotInstance(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a multifield slot.
    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::IBPutSlotMultifield(raw, slot, value.raw())
        })
    }
    /// Assigns an already existing CLIPS value.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
    /// environment, since CLIPS atoms are interned per environment.
    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::IBPutSlot(raw, slot, &mut cv) })
    }
    /// Creates the instance and returns a retained handle to it.
    ///
    /// With `None`, CLIPS generates a name of the form `genN`. The builder is
    /// reusable afterwards, so several instances of the class can be made
    /// without recreating it.
    pub fn make(&mut self, name: Option<&str>) -> Result<Instance<'env>> {
        let name = name.map(CString::new).transpose()?;
        let raw = unsafe {
            ffi::IBMake(
                self.raw.as_ptr(),
                name.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
            )
        };
        self.made = !raw.is_null();
        Instance::retained(self.environment, raw).ok_or_else(|| {
            Error::InstanceBuilder(InstanceBuilderError::from(unsafe {
                ffi::IBError(self.environment.raw.as_ptr())
            }))
        })
    }
}
impl Drop for InstanceBuilder<'_> {
    fn drop(&mut self) {
        unsafe {
            if !self.made {
                ffi::IBAbort(self.raw.as_ptr())
            }
            ffi::IBDispose(self.raw.as_ptr())
        }
    }
}

/// Collects slot changes and applies them as a single modification.
///
/// Aborts on drop unless [`InstanceModifier::modify`] was called. Unlike a
/// fact modification, the instance keeps its identity: the same instance is
/// updated in place rather than replaced.
pub struct InstanceModifier<'env> {
    raw: NonNull<ffi::InstanceModifier>,
    environment: &'env Environment,
}
impl<'env> InstanceModifier<'env> {
    fn new(instance: &Instance<'env>) -> Result<Self> {
        NonNull::new(unsafe {
            ffi::CreateInstanceModifier(instance.environment.raw.as_ptr(), instance.raw.as_ptr())
        })
        .map(|raw| Self {
            raw,
            environment: instance.environment,
        })
        .ok_or_else(|| {
            Error::InstanceModifier(crate::error::InstanceModifierError::from(unsafe {
                ffi::IMError(instance.environment.raw.as_ptr())
            }))
        })
    }
    fn put(
        &mut self,
        slot: &str,
        operation: impl FnOnce(*const 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))),
        }
    }
    /// Sets an integer slot.
    pub fn integer(&mut self, slot: &str, value: i64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::IMPutSlotInteger(raw, slot, value)
        })
    }
    /// Sets a float slot.
    pub fn float(&mut self, slot: &str, value: f64) -> Result<&mut Self> {
        let raw = self.raw.as_ptr();
        self.put(slot, |slot| unsafe {
            ffi::IMPutSlotFloat(raw, slot, value)
        })
    }
    /// Sets a symbol slot.
    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::IMPutSlotSymbol(raw, slot, value.as_ptr())
        })
    }
    /// Sets a string slot.
    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::IMPutSlotString(raw, slot, value.as_ptr())
        })
    }
    /// Sets an instance-name slot.
    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::IMPutSlotInstanceName(raw, slot, value.as_ptr())
        })
    }
    /// Sets a slot to a fact address.
    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::IMPutSlotFact(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a slot to an instance address.
    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::IMPutSlotInstance(raw, slot, value.raw.as_ptr())
        })
    }
    /// Sets a multifield slot.
    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::IMPutSlotMultifield(raw, slot, value.raw())
        })
    }
    /// Assigns an already existing CLIPS value.
    ///
    /// Fails with [`Error::ForeignEnvironment`] if `value` belongs to another
    /// environment, since CLIPS atoms are interned per environment.
    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::IMPutSlot(raw, slot, &mut cv) })
    }
    /// Applies the collected changes, running slot daemons once for the batch.
    ///
    /// Slots left unset keep their current values.
    pub fn modify(&mut self) -> Result<Instance<'env>> {
        let raw = unsafe { ffi::IMModify(self.raw.as_ptr()) };
        Instance::retained(self.environment, raw).ok_or_else(|| {
            Error::InstanceModifier(crate::error::InstanceModifierError::from(unsafe {
                ffi::IMError(self.environment.raw.as_ptr())
            }))
        })
    }
    /// Discards the collected changes, leaving the instance untouched.
    pub fn abort(&mut self) {
        unsafe { ffi::IMAbort(self.raw.as_ptr()) }
    }
}
impl Drop for InstanceModifier<'_> {
    fn drop(&mut self) {
        unsafe {
            ffi::IMAbort(self.raw.as_ptr());
            ffi::IMDispose(self.raw.as_ptr())
        }
    }
}