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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Safe user-defined functions callable from CLIPS.
//!
//! Registrations are owned by [`Environment`](crate::Environment). CLIPS receives
//! a stable pointer to the boxed registration and all unwinding is stopped at
//! the C ABI boundary.

use std::cell::RefCell;
use std::ffi::{CStr, CString, c_void};
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr::NonNull;

use crate::ffi;

const ANY_TYPE_BITS: u32 = (1 << 11) - 1;

/// Generates the opaque address tokens a UDF can receive and hand back.
macro_rules! address_token {
    ($($name:ident($target:ty)),+ $(,)?) => {$(
        /// An address CLIPS passed into the current UDF invocation.
        ///
        /// The token is opaque and has no accessors: it exists so a UDF can
        /// hand an address CLIPS gave it straight back as its result. Its
        /// lifetime is the invocation that produced it, which is what stops a
        /// `'static` callback from storing one and returning it after CLIPS
        /// has freed the referent.
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub struct $name<'call> {
            pub(crate) raw: NonNull<$target>,
            pub(crate) marker: PhantomData<&'call ()>,
        }
        impl<'call> $name<'call> {
            fn new(raw: *mut $target) -> Option<Self> {
                NonNull::new(raw).map(|raw| Self { raw, marker: PhantomData })
            }
        }
    )+};
}
address_token!(
    UdfFact(ffi::Fact),
    UdfInstance(ffi::Instance),
    UdfExternalAddress(c_void),
);

/// A value supplied to a Rust UDF by CLIPS.
///
/// `'call` is the invocation the value was decoded for. Address-valued
/// variants borrow it so they cannot outlive the call.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum UdfValue<'call> {
    /// A CLIPS float.
    Float(f64),
    /// A CLIPS integer.
    Integer(i64),
    /// A symbol other than `TRUE` or `FALSE`.
    Symbol(String),
    /// A string.
    String(String),
    /// The symbol `TRUE` or `FALSE`, which CLIPS stores as a symbol.
    Boolean(bool),
    /// An instance name, the `[name]` form.
    InstanceName(String),
    /// A multifield's elements. CLIPS multifields do not nest, so a nested
    /// value here only arises from a slot holding a multifield.
    Multifield(Vec<UdfValue<'call>>),
    /// A fact address, as an opaque token valid for this call.
    FactAddress(UdfFact<'call>),
    /// An instance address, as an opaque token valid for this call.
    InstanceAddress(UdfInstance<'call>),
    /// An external address, as an opaque token valid for this call.
    ExternalAddress(UdfExternalAddress<'call>),
    /// The void value, which CLIPS uses for functions returning nothing.
    Void,
}

/// A value returned from a Rust UDF to CLIPS.
///
/// Address-valued variants can only be built from the tokens CLIPS supplied to
/// the same invocation, so a UDF can pass a fact, instance, or external address
/// through, but cannot fabricate one.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum UdfReturn<'call> {
    /// Return a float.
    Float(f64),
    /// Return an integer.
    Integer(i64),
    /// Return a symbol. An interior NUL makes the call fail.
    Symbol(String),
    /// Return a string. An interior NUL makes the call fail.
    String(String),
    /// Return `TRUE` or `FALSE`.
    Boolean(bool),
    /// Return an instance name. An interior NUL makes the call fail.
    InstanceName(String),
    /// A multifield result. Nested [`UdfReturn::Multifield`] values are spliced
    /// in, because CLIPS multifields cannot contain multifields.
    Multifield(Vec<UdfReturn<'call>>),
    /// Return a fact CLIPS supplied to this same call.
    FactAddress(UdfFact<'call>),
    /// Return an instance CLIPS supplied to this same call.
    InstanceAddress(UdfInstance<'call>),
    /// Return an external address CLIPS supplied to this same call.
    ExternalAddress(UdfExternalAddress<'call>),
    /// Leave CLIPS's pre-initialized void return value unchanged.
    Void,
}

/// CLIPS types used to describe UDF arguments and results.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UdfType {
    /// Any type, CLIPS's `*` code.
    Any,
    /// The symbols `TRUE` and `FALSE`.
    Boolean,
    /// A float.
    Float,
    /// An external address.
    ExternalAddress,
    /// A fact address.
    FactAddress,
    /// An instance address.
    InstanceAddress,
    /// An integer.
    Integer,
    /// A multifield.
    Multifield,
    /// An instance name.
    InstanceName,
    /// A string.
    String,
    /// A symbol.
    Symbol,
    /// No value, valid only as a return type.
    Void,
}

impl UdfType {
    fn code(self) -> char {
        match self {
            Self::Any => '*',
            Self::Boolean => 'b',
            Self::Float => 'd',
            Self::ExternalAddress => 'e',
            Self::FactAddress => 'f',
            Self::InstanceAddress => 'i',
            Self::Integer => 'l',
            Self::Multifield => 'm',
            Self::InstanceName => 'n',
            Self::String => 's',
            Self::Symbol => 'y',
            Self::Void => 'v',
        }
    }
}

/// Arity and type restrictions passed to CLIPS when registering a UDF.
#[derive(Clone, Debug)]
pub struct UdfSignature {
    pub(crate) returns: CString,
    pub(crate) min_args: u16,
    pub(crate) max_args: u16,
    pub(crate) arguments: Option<CString>,
}

impl UdfSignature {
    /// Starts building a signature whose function may return any of `returns`.
    pub fn builder(returns: &[UdfType]) -> UdfSignatureBuilder {
        UdfSignatureBuilder {
            returns: type_codes(returns),
            min_args: 0,
            max_args: 0,
            default_arguments: Vec::new(),
            positional_arguments: Vec::new(),
        }
    }
}

/// Builder for [`UdfSignature`].
#[derive(Clone, Debug)]
pub struct UdfSignatureBuilder {
    returns: String,
    min_args: u16,
    max_args: u16,
    default_arguments: Vec<UdfType>,
    positional_arguments: Vec<Vec<UdfType>>,
}

impl UdfSignatureBuilder {
    /// Requires between `min` and `max` arguments inclusive.
    pub fn arity(mut self, min: u16, max: u16) -> Self {
        self.min_args = min;
        self.max_args = max;
        self
    }

    /// Requires at least `min` arguments and accepts any number beyond that.
    pub fn unbounded(mut self, min: u16) -> Self {
        self.min_args = min;
        self.max_args = u16::MAX;
        self
    }

    /// Restricts every argument position that has no specific restriction from
    /// [`UdfSignatureBuilder::argument`].
    pub fn default_arguments(mut self, types: &[UdfType]) -> Self {
        self.default_arguments = types.to_vec();
        self
    }

    /// Sets the restriction for a one-based argument position.
    ///
    /// # Panics
    ///
    /// Panics if `position` is zero: CLIPS numbers arguments from one.
    pub fn argument(mut self, position: usize, types: &[UdfType]) -> Self {
        assert!(position > 0, "UDF argument positions are one-based");
        self.positional_arguments.resize(position, Vec::new());
        self.positional_arguments[position - 1] = types.to_vec();
        self
    }

    /// Produces the signature to pass to
    /// [`Environment::add_udf`](crate::Environment::add_udf).
    pub fn build(self) -> UdfSignature {
        let arguments = if self.default_arguments.is_empty()
            && self.positional_arguments.iter().all(Vec::is_empty)
        {
            None
        } else {
            let mut restrictions = type_codes(&self.default_arguments);
            for argument in self.positional_arguments {
                restrictions.push(';');
                restrictions.push_str(&type_codes(&argument));
            }
            Some(CString::new(restrictions).expect("type codes contain no NUL"))
        };
        UdfSignature {
            returns: CString::new(self.returns).expect("type codes contain no NUL"),
            min_args: self.min_args,
            max_args: self.max_args,
            arguments,
        }
    }
}

fn type_codes(types: &[UdfType]) -> String {
    types.iter().map(|ty| ty.code()).collect()
}

/// Error produced by a Rust UDF invocation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UdfCallbackError {
    /// The callback returned an error with this description, or the crate could
    /// not convert a value it produced.
    Message(String),
    /// CLIPS re-entered the same UDF while it was already running, which would
    /// require two simultaneous mutable borrows of the callback. The call is
    /// refused rather than aliasing it.
    ReentrantCall,
    /// The callback panicked. The unwind was stopped at the C boundary, since
    /// unwinding through CLIPS would be undefined behaviour.
    Panic,
    /// CLIPS supplied an argument whose type tag this crate does not model.
    UnsupportedArgumentType(u16),
}

/// Why registering or removing a user-defined function failed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UdfRegistrationError {
    /// The name or a type code contained a NUL byte.
    InteriorNul,
    /// The signature's minimum arity is greater than its maximum.
    MinimumExceedsMaximum,
    /// A function of that name is already registered.
    NameInUse,
    /// An argument restriction contains an invalid type code.
    InvalidArgumentType,
    /// The return restriction contains an invalid type code.
    InvalidReturnType,
    /// No function of that name is registered, reported when removing.
    NotFound,
    /// A code this crate does not recognise.
    Unknown(u32),
}
impl From<std::ffi::NulError> for UdfRegistrationError {
    fn from(_: std::ffi::NulError) -> Self {
        Self::InteriorNul
    }
}
impl UdfRegistrationError {
    pub(crate) fn from_code(code: u32) -> Self {
        match code {
            1 => Self::MinimumExceedsMaximum,
            2 => Self::NameInUse,
            3 => Self::InvalidArgumentType,
            4 => Self::InvalidReturnType,
            code => Self::Unknown(code),
        }
    }
}
impl std::fmt::Display for UdfRegistrationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "CLIPS UDF registration error: {self:?}")
    }
}
impl std::error::Error for UdfRegistrationError {}

impl From<String> for UdfCallbackError {
    fn from(value: String) -> Self {
        Self::Message(value)
    }
}

impl From<&str> for UdfCallbackError {
    fn from(value: &str) -> Self {
        Self::Message(value.to_owned())
    }
}

type Callback = dyn for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
    + 'static;

/// Stable callback allocation stored by the owning environment.
pub(crate) struct UdfRegistration {
    pub(crate) name: CString,
    pub(crate) signature: UdfSignature,
    callback: RefCell<Box<Callback>>,
    last_error: RefCell<Option<UdfCallbackError>>,
}

impl UdfRegistration {
    pub(crate) fn new<F>(name: CString, signature: UdfSignature, callback: F) -> Box<Self>
    where
        F: for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
            + 'static,
    {
        Box::new(Self {
            name,
            signature,
            callback: RefCell::new(Box::new(callback)),
            last_error: RefCell::new(None),
        })
    }

    pub(crate) fn context(&mut self) -> *mut c_void {
        self as *mut Self as *mut c_void
    }

    pub(crate) fn take_error(&self) -> Option<UdfCallbackError> {
        self.last_error.borrow_mut().take()
    }
}

/// The single C ABI entry point used by every Rust UDF registration.
pub(crate) unsafe extern "C" fn trampoline(
    environment: *mut ffi::Environment,
    context: *mut ffi::UDFContext,
    output: *mut ffi::UDFValue,
) {
    let result = catch_unwind(AssertUnwindSafe(|| {
        // SAFETY: Environment registers a pointer to a boxed UdfRegistration as
        // the AddUDF context and keeps that allocation alive until removal.
        let registration = unsafe { &*((*context).context as *const UdfRegistration) };
        let argument_count = unsafe { ffi::UDFArgumentCount(context) } as usize;
        let mut arguments = Vec::with_capacity(argument_count);
        for position in 1..=argument_count {
            let mut raw = ffi::UDFValue {
                supplemental_info: std::ptr::null_mut(),
                value: ffi::CLIPSValue {
                    value: std::ptr::null_mut(),
                },
                begin: 0,
                range: usize::MAX,
                next: std::ptr::null_mut(),
            };
            if !unsafe { ffi::UDFNthArgument(context, position as u32, ANY_TYPE_BITS, &mut raw) } {
                return Err(UdfCallbackError::Message(format!(
                    "CLIPS rejected UDF argument {position}"
                )));
            }
            arguments.push(unsafe { decode_value(&raw)? });
        }

        let mut callback = registration
            .callback
            .try_borrow_mut()
            .map_err(|_| UdfCallbackError::ReentrantCall)?;
        let returned = callback(&arguments)?;
        unsafe { encode_return(environment, output, returned) }
    }));

    let error = match result {
        Ok(Ok(())) => return,
        Ok(Err(error)) => error,
        Err(_) => UdfCallbackError::Panic,
    };
    let registration = unsafe { &*((*context).context as *const UdfRegistration) };
    *registration.last_error.borrow_mut() = Some(error);
    unsafe { ffi::UDFThrowError(context) };
}

unsafe fn decode_value<'call>(raw: &ffi::UDFValue) -> Result<UdfValue<'call>, UdfCallbackError> {
    let type_code = unsafe { (*raw.value.header).type_ };
    Ok(match type_code {
        0 => UdfValue::Float(unsafe { (*raw.value.float).contents }),
        1 => UdfValue::Integer(unsafe { (*raw.value.integer).contents }),
        2 => {
            let text = unsafe { lexeme(raw) };
            if text == "TRUE" || text == "FALSE" {
                UdfValue::Boolean(text == "TRUE")
            } else {
                UdfValue::Symbol(text)
            }
        }
        3 => UdfValue::String(unsafe { lexeme(raw) }),
        4 => {
            let multifield = unsafe { &*raw.value.multifield };
            let end = raw
                .begin
                .checked_add(raw.range)
                .filter(|&end| end <= multifield.length)
                .ok_or_else(|| {
                    UdfCallbackError::Message("CLIPS returned an invalid multifield slice".into())
                })?;
            let mut values = Vec::with_capacity(raw.range);
            for index in raw.begin..end {
                let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
                let range = if unsafe { (*cell.header).type_ } == 4 {
                    unsafe { (*cell.multifield).length }
                } else {
                    0
                };
                let nested = ffi::UDFValue {
                    supplemental_info: std::ptr::null_mut(),
                    value: *cell,
                    begin: 0,
                    range,
                    next: std::ptr::null_mut(),
                };
                values.push(unsafe { decode_value(&nested)? });
            }
            UdfValue::Multifield(values)
        }
        5 => UdfExternalAddress::new(unsafe { raw.value.value })
            .map(UdfValue::ExternalAddress)
            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
        6 => UdfFact::new(unsafe { raw.value.fact })
            .map(UdfValue::FactAddress)
            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
        7 => UdfInstance::new(unsafe { raw.value.instance })
            .map(UdfValue::InstanceAddress)
            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
        8 => UdfValue::InstanceName(unsafe { lexeme(raw) }),
        9 => UdfValue::Void,
        other => return Err(UdfCallbackError::UnsupportedArgumentType(other)),
    })
}

unsafe fn lexeme(raw: &ffi::UDFValue) -> String {
    unsafe { CStr::from_ptr((*raw.value.lexeme).contents) }
        .to_string_lossy()
        .into_owned()
}

unsafe fn encode_return(
    environment: *mut ffi::Environment,
    output: *mut ffi::UDFValue,
    value: UdfReturn<'_>,
) -> Result<(), UdfCallbackError> {
    match value {
        UdfReturn::Float(value) => unsafe {
            (*output).value.float = ffi::CreateFloat(environment, value)
        },
        UdfReturn::Integer(value) => unsafe {
            (*output).value.integer = ffi::CreateInteger(environment, value)
        },
        UdfReturn::Boolean(value) => unsafe {
            (*output).value.lexeme = ffi::CreateBoolean(environment, value)
        },
        UdfReturn::Symbol(value) => {
            let value = CString::new(value)
                .map_err(|_| UdfCallbackError::Message("symbol contains NUL".into()))?;
            unsafe { (*output).value.lexeme = ffi::CreateSymbol(environment, value.as_ptr()) };
        }
        UdfReturn::String(value) => {
            let value = CString::new(value)
                .map_err(|_| UdfCallbackError::Message("string contains NUL".into()))?;
            unsafe { (*output).value.lexeme = ffi::CreateString(environment, value.as_ptr()) };
        }
        UdfReturn::InstanceName(value) => {
            let value = CString::new(value)
                .map_err(|_| UdfCallbackError::Message("instance name contains NUL".into()))?;
            unsafe {
                (*output).value.lexeme = ffi::CreateInstanceName(environment, value.as_ptr())
            };
        }
        UdfReturn::Multifield(values) => {
            let multifield = unsafe { build_multifield(environment, values)? };
            unsafe {
                (*output).value.multifield = multifield;
                (*output).begin = 0;
                (*output).range = (*multifield).length;
            }
        }
        UdfReturn::FactAddress(fact) => unsafe { (*output).value.fact = fact.raw.as_ptr() },
        UdfReturn::InstanceAddress(instance) => unsafe {
            (*output).value.instance = instance.raw.as_ptr()
        },
        UdfReturn::ExternalAddress(address) => unsafe {
            (*output).value.value = address.raw.as_ptr()
        },
        UdfReturn::Void => {}
    }
    Ok(())
}

/// Disposes a CLIPS multifield builder on every exit path, including the error
/// paths taken when a returned lexeme contains an interior NUL.
struct MultifieldBuilderGuard(*mut ffi::MultifieldBuilder);
impl Drop for MultifieldBuilderGuard {
    fn drop(&mut self) {
        unsafe { ffi::MBDispose(self.0) }
    }
}

unsafe fn build_multifield(
    environment: *mut ffi::Environment,
    values: Vec<UdfReturn<'_>>,
) -> Result<*mut ffi::Multifield, UdfCallbackError> {
    let builder = unsafe { ffi::CreateMultifieldBuilder(environment, values.len()) };
    if builder.is_null() {
        return Err(UdfCallbackError::Message(
            "CLIPS could not create a multifield builder".into(),
        ));
    }
    let guard = MultifieldBuilderGuard(builder);

    for value in values {
        match value {
            UdfReturn::Float(value) => unsafe { ffi::MBAppendFloat(builder, value) },
            UdfReturn::Integer(value) => unsafe { ffi::MBAppendInteger(builder, value) },
            UdfReturn::Boolean(value) => {
                let mut raw = ffi::CLIPSValue {
                    lexeme: unsafe { ffi::CreateBoolean(environment, value) },
                };
                unsafe { ffi::MBAppend(builder, &mut raw) };
            }
            UdfReturn::Symbol(value) => {
                let value = nul_free(value, "symbol")?;
                unsafe { ffi::MBAppendSymbol(builder, value.as_ptr()) };
            }
            UdfReturn::String(value) => {
                let value = nul_free(value, "string")?;
                unsafe { ffi::MBAppendString(builder, value.as_ptr()) };
            }
            UdfReturn::InstanceName(value) => {
                let value = nul_free(value, "instance name")?;
                unsafe { ffi::MBAppendInstanceName(builder, value.as_ptr()) };
            }
            // CLIPS multifields do not nest: `MBAppend` splices a multifield's
            // fields into the one being built. The nested value is still built
            // first so its own elements are validated the same way.
            UdfReturn::Multifield(values) => {
                let nested = unsafe { build_multifield(environment, values)? };
                unsafe { ffi::MBAppendMultifield(builder, nested) };
            }
            UdfReturn::FactAddress(fact) => unsafe {
                ffi::MBAppendFact(builder, fact.raw.as_ptr())
            },
            UdfReturn::InstanceAddress(instance) => unsafe {
                ffi::MBAppendInstance(builder, instance.raw.as_ptr())
            },
            UdfReturn::ExternalAddress(address) => {
                let mut raw = ffi::CLIPSValue {
                    value: address.raw.as_ptr(),
                };
                unsafe { ffi::MBAppend(builder, &mut raw) };
            }
            // A void field cannot be stored in a multifield; CLIPS has no
            // representation for it, so it is dropped rather than guessed at.
            UdfReturn::Void => {}
        }
    }

    let multifield = unsafe { ffi::MBCreate(builder) };
    drop(guard);
    if multifield.is_null() {
        return Err(UdfCallbackError::Message(
            "CLIPS could not create the returned multifield".into(),
        ));
    }
    Ok(multifield)
}

fn nul_free(value: String, kind: &str) -> Result<CString, UdfCallbackError> {
    CString::new(value).map_err(|_| UdfCallbackError::Message(format!("{kind} contains NUL")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_nested_multifields_with_their_own_bounds() {
        let mut integer = ffi::CLIPSInteger {
            header: ffi::TypeHeader { type_: 1 },
            next: std::ptr::null_mut(),
            count: 0,
            flags: 0,
            contents: 42,
        };
        let mut inner = ffi::Multifield {
            header: ffi::TypeHeader { type_: 4 },
            busy_count: 0,
            length: 1,
            next: std::ptr::null_mut(),
            contents: [ffi::CLIPSValue {
                integer: &mut integer,
            }],
        };
        let mut outer = ffi::Multifield {
            header: ffi::TypeHeader { type_: 4 },
            busy_count: 0,
            length: 1,
            next: std::ptr::null_mut(),
            contents: [ffi::CLIPSValue {
                multifield: &mut inner,
            }],
        };
        let raw = ffi::UDFValue {
            supplemental_info: std::ptr::null_mut(),
            value: ffi::CLIPSValue {
                multifield: &mut outer,
            },
            begin: 0,
            range: 1,
            next: std::ptr::null_mut(),
        };

        assert_eq!(
            unsafe { decode_value(&raw) }.unwrap(),
            UdfValue::Multifield(vec![UdfValue::Multifield(vec![UdfValue::Integer(42)])])
        );
    }

    #[test]
    fn rejects_out_of_bounds_multifield_slices() {
        let mut multifield = ffi::Multifield {
            header: ffi::TypeHeader { type_: 4 },
            busy_count: 0,
            length: 0,
            next: std::ptr::null_mut(),
            contents: [ffi::CLIPSValue {
                value: std::ptr::null_mut(),
            }],
        };
        let raw = ffi::UDFValue {
            supplemental_info: std::ptr::null_mut(),
            value: ffi::CLIPSValue {
                multifield: &mut multifield,
            },
            begin: 1,
            range: 1,
            next: std::ptr::null_mut(),
        };

        assert!(matches!(
            unsafe { decode_value(&raw) },
            Err(UdfCallbackError::Message(message))
                if message == "CLIPS returned an invalid multifield slice"
        ));
    }
}