Skip to main content

clips_bindings/
udf.rs

1//! Safe user-defined functions callable from CLIPS.
2//!
3//! Registrations are owned by [`Environment`](crate::Environment). CLIPS receives
4//! a stable pointer to the boxed registration and all unwinding is stopped at
5//! the C ABI boundary.
6
7use std::cell::RefCell;
8use std::ffi::{CStr, CString, c_void};
9use std::marker::PhantomData;
10use std::panic::{AssertUnwindSafe, catch_unwind};
11use std::ptr::NonNull;
12
13use crate::ffi;
14
15const ANY_TYPE_BITS: u32 = (1 << 11) - 1;
16
17/// Generates the opaque address tokens a UDF can receive and hand back.
18macro_rules! address_token {
19    ($($name:ident($target:ty)),+ $(,)?) => {$(
20        /// An address CLIPS passed into the current UDF invocation.
21        ///
22        /// The token is opaque and has no accessors: it exists so a UDF can
23        /// hand an address CLIPS gave it straight back as its result. Its
24        /// lifetime is the invocation that produced it, which is what stops a
25        /// `'static` callback from storing one and returning it after CLIPS
26        /// has freed the referent.
27        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
28        pub struct $name<'call> {
29            pub(crate) raw: NonNull<$target>,
30            pub(crate) marker: PhantomData<&'call ()>,
31        }
32        impl<'call> $name<'call> {
33            fn new(raw: *mut $target) -> Option<Self> {
34                NonNull::new(raw).map(|raw| Self { raw, marker: PhantomData })
35            }
36        }
37    )+};
38}
39address_token!(
40    UdfFact(ffi::Fact),
41    UdfInstance(ffi::Instance),
42    UdfExternalAddress(c_void),
43);
44
45/// A value supplied to a Rust UDF by CLIPS.
46///
47/// `'call` is the invocation the value was decoded for. Address-valued
48/// variants borrow it so they cannot outlive the call.
49#[derive(Clone, Debug, PartialEq)]
50#[non_exhaustive]
51pub enum UdfValue<'call> {
52    /// A CLIPS float.
53    Float(f64),
54    /// A CLIPS integer.
55    Integer(i64),
56    /// A symbol other than `TRUE` or `FALSE`.
57    Symbol(String),
58    /// A string.
59    String(String),
60    /// The symbol `TRUE` or `FALSE`, which CLIPS stores as a symbol.
61    Boolean(bool),
62    /// An instance name, the `[name]` form.
63    InstanceName(String),
64    /// A multifield's elements. CLIPS multifields do not nest, so a nested
65    /// value here only arises from a slot holding a multifield.
66    Multifield(Vec<UdfValue<'call>>),
67    /// A fact address, as an opaque token valid for this call.
68    FactAddress(UdfFact<'call>),
69    /// An instance address, as an opaque token valid for this call.
70    InstanceAddress(UdfInstance<'call>),
71    /// An external address, as an opaque token valid for this call.
72    ExternalAddress(UdfExternalAddress<'call>),
73    /// The void value, which CLIPS uses for functions returning nothing.
74    Void,
75}
76
77/// A value returned from a Rust UDF to CLIPS.
78///
79/// Address-valued variants can only be built from the tokens CLIPS supplied to
80/// the same invocation, so a UDF can pass a fact, instance, or external address
81/// through, but cannot fabricate one.
82#[derive(Clone, Debug, PartialEq)]
83#[non_exhaustive]
84pub enum UdfReturn<'call> {
85    /// Return a float.
86    Float(f64),
87    /// Return an integer.
88    Integer(i64),
89    /// Return a symbol. An interior NUL makes the call fail.
90    Symbol(String),
91    /// Return a string. An interior NUL makes the call fail.
92    String(String),
93    /// Return `TRUE` or `FALSE`.
94    Boolean(bool),
95    /// Return an instance name. An interior NUL makes the call fail.
96    InstanceName(String),
97    /// A multifield result. Nested [`UdfReturn::Multifield`] values are spliced
98    /// in, because CLIPS multifields cannot contain multifields.
99    Multifield(Vec<UdfReturn<'call>>),
100    /// Return a fact CLIPS supplied to this same call.
101    FactAddress(UdfFact<'call>),
102    /// Return an instance CLIPS supplied to this same call.
103    InstanceAddress(UdfInstance<'call>),
104    /// Return an external address CLIPS supplied to this same call.
105    ExternalAddress(UdfExternalAddress<'call>),
106    /// Leave CLIPS's pre-initialized void return value unchanged.
107    Void,
108}
109
110/// CLIPS types used to describe UDF arguments and results.
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
112pub enum UdfType {
113    /// Any type, CLIPS's `*` code.
114    Any,
115    /// The symbols `TRUE` and `FALSE`.
116    Boolean,
117    /// A float.
118    Float,
119    /// An external address.
120    ExternalAddress,
121    /// A fact address.
122    FactAddress,
123    /// An instance address.
124    InstanceAddress,
125    /// An integer.
126    Integer,
127    /// A multifield.
128    Multifield,
129    /// An instance name.
130    InstanceName,
131    /// A string.
132    String,
133    /// A symbol.
134    Symbol,
135    /// No value, valid only as a return type.
136    Void,
137}
138
139impl UdfType {
140    fn code(self) -> char {
141        match self {
142            Self::Any => '*',
143            Self::Boolean => 'b',
144            Self::Float => 'd',
145            Self::ExternalAddress => 'e',
146            Self::FactAddress => 'f',
147            Self::InstanceAddress => 'i',
148            Self::Integer => 'l',
149            Self::Multifield => 'm',
150            Self::InstanceName => 'n',
151            Self::String => 's',
152            Self::Symbol => 'y',
153            Self::Void => 'v',
154        }
155    }
156}
157
158/// Arity and type restrictions passed to CLIPS when registering a UDF.
159#[derive(Clone, Debug)]
160pub struct UdfSignature {
161    pub(crate) returns: CString,
162    pub(crate) min_args: u16,
163    pub(crate) max_args: u16,
164    pub(crate) arguments: Option<CString>,
165}
166
167impl UdfSignature {
168    /// Starts building a signature whose function may return any of `returns`.
169    pub fn builder(returns: &[UdfType]) -> UdfSignatureBuilder {
170        UdfSignatureBuilder {
171            returns: type_codes(returns),
172            min_args: 0,
173            max_args: 0,
174            default_arguments: Vec::new(),
175            positional_arguments: Vec::new(),
176        }
177    }
178}
179
180/// Builder for [`UdfSignature`].
181#[derive(Clone, Debug)]
182pub struct UdfSignatureBuilder {
183    returns: String,
184    min_args: u16,
185    max_args: u16,
186    default_arguments: Vec<UdfType>,
187    positional_arguments: Vec<Vec<UdfType>>,
188}
189
190impl UdfSignatureBuilder {
191    /// Requires between `min` and `max` arguments inclusive.
192    pub fn arity(mut self, min: u16, max: u16) -> Self {
193        self.min_args = min;
194        self.max_args = max;
195        self
196    }
197
198    /// Requires at least `min` arguments and accepts any number beyond that.
199    pub fn unbounded(mut self, min: u16) -> Self {
200        self.min_args = min;
201        self.max_args = u16::MAX;
202        self
203    }
204
205    /// Restricts every argument position that has no specific restriction from
206    /// [`UdfSignatureBuilder::argument`].
207    pub fn default_arguments(mut self, types: &[UdfType]) -> Self {
208        self.default_arguments = types.to_vec();
209        self
210    }
211
212    /// Sets the restriction for a one-based argument position.
213    ///
214    /// # Panics
215    ///
216    /// Panics if `position` is zero: CLIPS numbers arguments from one.
217    pub fn argument(mut self, position: usize, types: &[UdfType]) -> Self {
218        assert!(position > 0, "UDF argument positions are one-based");
219        self.positional_arguments.resize(position, Vec::new());
220        self.positional_arguments[position - 1] = types.to_vec();
221        self
222    }
223
224    /// Produces the signature to pass to
225    /// [`Environment::add_udf`](crate::Environment::add_udf).
226    pub fn build(self) -> UdfSignature {
227        let arguments = if self.default_arguments.is_empty()
228            && self.positional_arguments.iter().all(Vec::is_empty)
229        {
230            None
231        } else {
232            let mut restrictions = type_codes(&self.default_arguments);
233            for argument in self.positional_arguments {
234                restrictions.push(';');
235                restrictions.push_str(&type_codes(&argument));
236            }
237            Some(CString::new(restrictions).expect("type codes contain no NUL"))
238        };
239        UdfSignature {
240            returns: CString::new(self.returns).expect("type codes contain no NUL"),
241            min_args: self.min_args,
242            max_args: self.max_args,
243            arguments,
244        }
245    }
246}
247
248fn type_codes(types: &[UdfType]) -> String {
249    types.iter().map(|ty| ty.code()).collect()
250}
251
252/// Error produced by a Rust UDF invocation.
253#[derive(Clone, Debug, Eq, PartialEq)]
254pub enum UdfCallbackError {
255    /// The callback returned an error with this description, or the crate could
256    /// not convert a value it produced.
257    Message(String),
258    /// CLIPS re-entered the same UDF while it was already running, which would
259    /// require two simultaneous mutable borrows of the callback. The call is
260    /// refused rather than aliasing it.
261    ReentrantCall,
262    /// The callback panicked. The unwind was stopped at the C boundary, since
263    /// unwinding through CLIPS would be undefined behaviour.
264    Panic,
265    /// CLIPS supplied an argument whose type tag this crate does not model.
266    UnsupportedArgumentType(u16),
267}
268
269/// Why registering or removing a user-defined function failed.
270#[derive(Clone, Debug, Eq, PartialEq)]
271pub enum UdfRegistrationError {
272    /// The name or a type code contained a NUL byte.
273    InteriorNul,
274    /// The signature's minimum arity is greater than its maximum.
275    MinimumExceedsMaximum,
276    /// A function of that name is already registered.
277    NameInUse,
278    /// An argument restriction contains an invalid type code.
279    InvalidArgumentType,
280    /// The return restriction contains an invalid type code.
281    InvalidReturnType,
282    /// No function of that name is registered, reported when removing.
283    NotFound,
284    /// A code this crate does not recognise.
285    Unknown(u32),
286}
287impl From<std::ffi::NulError> for UdfRegistrationError {
288    fn from(_: std::ffi::NulError) -> Self {
289        Self::InteriorNul
290    }
291}
292impl UdfRegistrationError {
293    pub(crate) fn from_code(code: u32) -> Self {
294        match code {
295            1 => Self::MinimumExceedsMaximum,
296            2 => Self::NameInUse,
297            3 => Self::InvalidArgumentType,
298            4 => Self::InvalidReturnType,
299            code => Self::Unknown(code),
300        }
301    }
302}
303impl std::fmt::Display for UdfRegistrationError {
304    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305        write!(formatter, "CLIPS UDF registration error: {self:?}")
306    }
307}
308impl std::error::Error for UdfRegistrationError {}
309
310impl From<String> for UdfCallbackError {
311    fn from(value: String) -> Self {
312        Self::Message(value)
313    }
314}
315
316impl From<&str> for UdfCallbackError {
317    fn from(value: &str) -> Self {
318        Self::Message(value.to_owned())
319    }
320}
321
322type Callback = dyn for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
323    + 'static;
324
325/// Stable callback allocation stored by the owning environment.
326pub(crate) struct UdfRegistration {
327    pub(crate) name: CString,
328    pub(crate) signature: UdfSignature,
329    callback: RefCell<Box<Callback>>,
330    last_error: RefCell<Option<UdfCallbackError>>,
331}
332
333impl UdfRegistration {
334    pub(crate) fn new<F>(name: CString, signature: UdfSignature, callback: F) -> Box<Self>
335    where
336        F: for<'call> FnMut(&[UdfValue<'call>]) -> Result<UdfReturn<'call>, UdfCallbackError>
337            + 'static,
338    {
339        Box::new(Self {
340            name,
341            signature,
342            callback: RefCell::new(Box::new(callback)),
343            last_error: RefCell::new(None),
344        })
345    }
346
347    pub(crate) fn context(&mut self) -> *mut c_void {
348        self as *mut Self as *mut c_void
349    }
350
351    pub(crate) fn take_error(&self) -> Option<UdfCallbackError> {
352        self.last_error.borrow_mut().take()
353    }
354}
355
356/// The single C ABI entry point used by every Rust UDF registration.
357pub(crate) unsafe extern "C" fn trampoline(
358    environment: *mut ffi::Environment,
359    context: *mut ffi::UDFContext,
360    output: *mut ffi::UDFValue,
361) {
362    let result = catch_unwind(AssertUnwindSafe(|| {
363        // SAFETY: Environment registers a pointer to a boxed UdfRegistration as
364        // the AddUDF context and keeps that allocation alive until removal.
365        let registration = unsafe { &*((*context).context as *const UdfRegistration) };
366        let argument_count = unsafe { ffi::UDFArgumentCount(context) } as usize;
367        let mut arguments = Vec::with_capacity(argument_count);
368        for position in 1..=argument_count {
369            let mut raw = ffi::UDFValue {
370                supplemental_info: std::ptr::null_mut(),
371                value: ffi::CLIPSValue {
372                    value: std::ptr::null_mut(),
373                },
374                begin: 0,
375                range: usize::MAX,
376                next: std::ptr::null_mut(),
377            };
378            if !unsafe { ffi::UDFNthArgument(context, position as u32, ANY_TYPE_BITS, &mut raw) } {
379                return Err(UdfCallbackError::Message(format!(
380                    "CLIPS rejected UDF argument {position}"
381                )));
382            }
383            arguments.push(unsafe { decode_value(&raw)? });
384        }
385
386        let mut callback = registration
387            .callback
388            .try_borrow_mut()
389            .map_err(|_| UdfCallbackError::ReentrantCall)?;
390        let returned = callback(&arguments)?;
391        unsafe { encode_return(environment, output, returned) }
392    }));
393
394    let error = match result {
395        Ok(Ok(())) => return,
396        Ok(Err(error)) => error,
397        Err(_) => UdfCallbackError::Panic,
398    };
399    let registration = unsafe { &*((*context).context as *const UdfRegistration) };
400    *registration.last_error.borrow_mut() = Some(error);
401    unsafe { ffi::UDFThrowError(context) };
402}
403
404unsafe fn decode_value<'call>(raw: &ffi::UDFValue) -> Result<UdfValue<'call>, UdfCallbackError> {
405    let type_code = unsafe { (*raw.value.header).type_ };
406    Ok(match type_code {
407        0 => UdfValue::Float(unsafe { (*raw.value.float).contents }),
408        1 => UdfValue::Integer(unsafe { (*raw.value.integer).contents }),
409        2 => {
410            let text = unsafe { lexeme(raw) };
411            if text == "TRUE" || text == "FALSE" {
412                UdfValue::Boolean(text == "TRUE")
413            } else {
414                UdfValue::Symbol(text)
415            }
416        }
417        3 => UdfValue::String(unsafe { lexeme(raw) }),
418        4 => {
419            let multifield = unsafe { &*raw.value.multifield };
420            let end = raw
421                .begin
422                .checked_add(raw.range)
423                .filter(|&end| end <= multifield.length)
424                .ok_or_else(|| {
425                    UdfCallbackError::Message("CLIPS returned an invalid multifield slice".into())
426                })?;
427            let mut values = Vec::with_capacity(raw.range);
428            for index in raw.begin..end {
429                let cell = unsafe { &*multifield.contents.as_ptr().add(index) };
430                let range = if unsafe { (*cell.header).type_ } == 4 {
431                    unsafe { (*cell.multifield).length }
432                } else {
433                    0
434                };
435                let nested = ffi::UDFValue {
436                    supplemental_info: std::ptr::null_mut(),
437                    value: *cell,
438                    begin: 0,
439                    range,
440                    next: std::ptr::null_mut(),
441                };
442                values.push(unsafe { decode_value(&nested)? });
443            }
444            UdfValue::Multifield(values)
445        }
446        5 => UdfExternalAddress::new(unsafe { raw.value.value })
447            .map(UdfValue::ExternalAddress)
448            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
449        6 => UdfFact::new(unsafe { raw.value.fact })
450            .map(UdfValue::FactAddress)
451            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
452        7 => UdfInstance::new(unsafe { raw.value.instance })
453            .map(UdfValue::InstanceAddress)
454            .ok_or_else(|| UdfCallbackError::Message("CLIPS passed a null address".into()))?,
455        8 => UdfValue::InstanceName(unsafe { lexeme(raw) }),
456        9 => UdfValue::Void,
457        other => return Err(UdfCallbackError::UnsupportedArgumentType(other)),
458    })
459}
460
461unsafe fn lexeme(raw: &ffi::UDFValue) -> String {
462    unsafe { CStr::from_ptr((*raw.value.lexeme).contents) }
463        .to_string_lossy()
464        .into_owned()
465}
466
467unsafe fn encode_return(
468    environment: *mut ffi::Environment,
469    output: *mut ffi::UDFValue,
470    value: UdfReturn<'_>,
471) -> Result<(), UdfCallbackError> {
472    match value {
473        UdfReturn::Float(value) => unsafe {
474            (*output).value.float = ffi::CreateFloat(environment, value)
475        },
476        UdfReturn::Integer(value) => unsafe {
477            (*output).value.integer = ffi::CreateInteger(environment, value)
478        },
479        UdfReturn::Boolean(value) => unsafe {
480            (*output).value.lexeme = ffi::CreateBoolean(environment, value)
481        },
482        UdfReturn::Symbol(value) => {
483            let value = CString::new(value)
484                .map_err(|_| UdfCallbackError::Message("symbol contains NUL".into()))?;
485            unsafe { (*output).value.lexeme = ffi::CreateSymbol(environment, value.as_ptr()) };
486        }
487        UdfReturn::String(value) => {
488            let value = CString::new(value)
489                .map_err(|_| UdfCallbackError::Message("string contains NUL".into()))?;
490            unsafe { (*output).value.lexeme = ffi::CreateString(environment, value.as_ptr()) };
491        }
492        UdfReturn::InstanceName(value) => {
493            let value = CString::new(value)
494                .map_err(|_| UdfCallbackError::Message("instance name contains NUL".into()))?;
495            unsafe {
496                (*output).value.lexeme = ffi::CreateInstanceName(environment, value.as_ptr())
497            };
498        }
499        UdfReturn::Multifield(values) => {
500            let multifield = unsafe { build_multifield(environment, values)? };
501            unsafe {
502                (*output).value.multifield = multifield;
503                (*output).begin = 0;
504                (*output).range = (*multifield).length;
505            }
506        }
507        UdfReturn::FactAddress(fact) => unsafe { (*output).value.fact = fact.raw.as_ptr() },
508        UdfReturn::InstanceAddress(instance) => unsafe {
509            (*output).value.instance = instance.raw.as_ptr()
510        },
511        UdfReturn::ExternalAddress(address) => unsafe {
512            (*output).value.value = address.raw.as_ptr()
513        },
514        UdfReturn::Void => {}
515    }
516    Ok(())
517}
518
519/// Disposes a CLIPS multifield builder on every exit path, including the error
520/// paths taken when a returned lexeme contains an interior NUL.
521struct MultifieldBuilderGuard(*mut ffi::MultifieldBuilder);
522impl Drop for MultifieldBuilderGuard {
523    fn drop(&mut self) {
524        unsafe { ffi::MBDispose(self.0) }
525    }
526}
527
528unsafe fn build_multifield(
529    environment: *mut ffi::Environment,
530    values: Vec<UdfReturn<'_>>,
531) -> Result<*mut ffi::Multifield, UdfCallbackError> {
532    let builder = unsafe { ffi::CreateMultifieldBuilder(environment, values.len()) };
533    if builder.is_null() {
534        return Err(UdfCallbackError::Message(
535            "CLIPS could not create a multifield builder".into(),
536        ));
537    }
538    let guard = MultifieldBuilderGuard(builder);
539
540    for value in values {
541        match value {
542            UdfReturn::Float(value) => unsafe { ffi::MBAppendFloat(builder, value) },
543            UdfReturn::Integer(value) => unsafe { ffi::MBAppendInteger(builder, value) },
544            UdfReturn::Boolean(value) => {
545                let mut raw = ffi::CLIPSValue {
546                    lexeme: unsafe { ffi::CreateBoolean(environment, value) },
547                };
548                unsafe { ffi::MBAppend(builder, &mut raw) };
549            }
550            UdfReturn::Symbol(value) => {
551                let value = nul_free(value, "symbol")?;
552                unsafe { ffi::MBAppendSymbol(builder, value.as_ptr()) };
553            }
554            UdfReturn::String(value) => {
555                let value = nul_free(value, "string")?;
556                unsafe { ffi::MBAppendString(builder, value.as_ptr()) };
557            }
558            UdfReturn::InstanceName(value) => {
559                let value = nul_free(value, "instance name")?;
560                unsafe { ffi::MBAppendInstanceName(builder, value.as_ptr()) };
561            }
562            // CLIPS multifields do not nest: `MBAppend` splices a multifield's
563            // fields into the one being built. The nested value is still built
564            // first so its own elements are validated the same way.
565            UdfReturn::Multifield(values) => {
566                let nested = unsafe { build_multifield(environment, values)? };
567                unsafe { ffi::MBAppendMultifield(builder, nested) };
568            }
569            UdfReturn::FactAddress(fact) => unsafe {
570                ffi::MBAppendFact(builder, fact.raw.as_ptr())
571            },
572            UdfReturn::InstanceAddress(instance) => unsafe {
573                ffi::MBAppendInstance(builder, instance.raw.as_ptr())
574            },
575            UdfReturn::ExternalAddress(address) => {
576                let mut raw = ffi::CLIPSValue {
577                    value: address.raw.as_ptr(),
578                };
579                unsafe { ffi::MBAppend(builder, &mut raw) };
580            }
581            // A void field cannot be stored in a multifield; CLIPS has no
582            // representation for it, so it is dropped rather than guessed at.
583            UdfReturn::Void => {}
584        }
585    }
586
587    let multifield = unsafe { ffi::MBCreate(builder) };
588    drop(guard);
589    if multifield.is_null() {
590        return Err(UdfCallbackError::Message(
591            "CLIPS could not create the returned multifield".into(),
592        ));
593    }
594    Ok(multifield)
595}
596
597fn nul_free(value: String, kind: &str) -> Result<CString, UdfCallbackError> {
598    CString::new(value).map_err(|_| UdfCallbackError::Message(format!("{kind} contains NUL")))
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604
605    #[test]
606    fn decodes_nested_multifields_with_their_own_bounds() {
607        let mut integer = ffi::CLIPSInteger {
608            header: ffi::TypeHeader { type_: 1 },
609            next: std::ptr::null_mut(),
610            count: 0,
611            flags: 0,
612            contents: 42,
613        };
614        let mut inner = ffi::Multifield {
615            header: ffi::TypeHeader { type_: 4 },
616            busy_count: 0,
617            length: 1,
618            next: std::ptr::null_mut(),
619            contents: [ffi::CLIPSValue {
620                integer: &mut integer,
621            }],
622        };
623        let mut outer = ffi::Multifield {
624            header: ffi::TypeHeader { type_: 4 },
625            busy_count: 0,
626            length: 1,
627            next: std::ptr::null_mut(),
628            contents: [ffi::CLIPSValue {
629                multifield: &mut inner,
630            }],
631        };
632        let raw = ffi::UDFValue {
633            supplemental_info: std::ptr::null_mut(),
634            value: ffi::CLIPSValue {
635                multifield: &mut outer,
636            },
637            begin: 0,
638            range: 1,
639            next: std::ptr::null_mut(),
640        };
641
642        assert_eq!(
643            unsafe { decode_value(&raw) }.unwrap(),
644            UdfValue::Multifield(vec![UdfValue::Multifield(vec![UdfValue::Integer(42)])])
645        );
646    }
647
648    #[test]
649    fn rejects_out_of_bounds_multifield_slices() {
650        let mut multifield = ffi::Multifield {
651            header: ffi::TypeHeader { type_: 4 },
652            busy_count: 0,
653            length: 0,
654            next: std::ptr::null_mut(),
655            contents: [ffi::CLIPSValue {
656                value: std::ptr::null_mut(),
657            }],
658        };
659        let raw = ffi::UDFValue {
660            supplemental_info: std::ptr::null_mut(),
661            value: ffi::CLIPSValue {
662                multifield: &mut multifield,
663            },
664            begin: 1,
665            range: 1,
666            next: std::ptr::null_mut(),
667        };
668
669        assert!(matches!(
670            unsafe { decode_value(&raw) },
671            Err(UdfCallbackError::Message(message))
672                if message == "CLIPS returned an invalid multifield slice"
673        ));
674    }
675}