clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Typed errors.
//!
//! Each CLIPS error enum becomes a Rust enum with the same variants plus an
//! `Unknown` case, so a code this crate does not recognise is reported
//! rather than silently treated as success.

use crate::PersistenceError;
use std::ffi::NulError;

/// The result type used throughout the crate.
pub type Result<T> = std::result::Result<T, Error>;

/// Anything that can go wrong in a CLIPS operation.
///
/// Most variants wrap a CLIPS error enum unchanged, so the specific code CLIPS
/// reported is preserved rather than flattened into one opaque failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
    /// A Rust string contained a NUL byte and so cannot cross into C.
    InteriorNul,
    /// CLIPS could not allocate a new environment.
    EnvironmentCreation,
    /// A clear-ready hook vetoed [`crate::Environment::clear`].
    ClearRejected,
    /// Defining a construct failed.
    Build(BuildError),
    /// Evaluating an expression failed.
    Evaluation(EvaluationError),
    /// Loading constructs from a file or string failed.
    Load(LoadError),
    /// Asserting a fact failed.
    Assertion(AssertionError),
    /// Retracting a fact failed.
    Retraction(RetractionError),
    /// Creating or asserting through a fact builder failed.
    FactBuilder(FactBuilderError),
    /// Creating or making through an instance builder failed.
    InstanceBuilder(InstanceBuilderError),
    /// Creating an instance from `make-instance` syntax failed.
    MakeInstance(MakeInstanceError),
    /// Deleting an instance failed.
    UnmakeInstance(UnmakeInstanceError),
    /// Calling a CLIPS function failed.
    FunctionCall(FunctionCallError),
    /// Modifying a fact failed.
    FactModifier(FactModifierError),
    /// Modifying an instance failed.
    InstanceModifier(InstanceModifierError),
    /// Saving or loading constructs, facts, or instances failed.
    Persistence(PersistenceError),
    /// Writing a slot failed.
    PutSlot(PutSlotError),
    /// Reading a slot failed.
    GetSlot(GetSlotError),
    /// A value carried a CLIPS type tag this crate does not model. The payload
    /// is the raw tag from the value's `TypeHeader`.
    UnexpectedValueType(u16),
    /// A handle or value from a different CLIPS environment was supplied.
    ForeignEnvironment,
}

impl From<NulError> for Error {
    fn from(_: NulError) -> Self {
        Self::InteriorNul
    }
}

macro_rules! code_enum {
    (
        $(#[$enum_meta:meta])*
        $name:ident { $($(#[$variant_meta:meta])* $variant:ident = $value:literal),+ $(,)? }
    ) => {
        $(#[$enum_meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum $name {
            $($(#[$variant_meta])* $variant,)+
            /// A code this crate does not recognise, reported rather than
            /// silently treated as success. Seeing one means CLIPS gained a
            /// code since 6.4.2 or the declaration is wrong.
            Unknown(u32),
        }
        impl From<u32> for $name {
            fn from(value: u32) -> Self {
                match value { $($value => Self::$variant,)+ value => Self::Unknown(value) }
            }
        }
    };
}

// `NullPointer` appears throughout because CLIPS reports it when a required
// argument is NULL. The safe API cannot produce one, so it indicates a bug in
// this crate rather than in calling code.
//
// `RuleNetwork` likewise recurs: CLIPS raises it when an evaluation error
// happens while the change propagates through the rule network — a failing
// join test or right-hand side — so the operation itself was accepted but
// something it triggered failed.

code_enum!(
    /// Why defining a construct failed.
    BuildError {
        /// CLIPS parsed the construct but declined to define it, for example
        /// because a construct of that name exists and is not deletable.
        CouldNotBuild = 1,
        /// The text does not begin with a known construct keyword.
        ConstructNotFound = 2,
        /// The construct text is syntactically invalid.
        Parsing = 3,
    }
);
code_enum!(
    /// Why evaluating an expression failed.
    EvaluationError {
        /// The expression text is syntactically invalid.
        Parsing = 1,
        /// The expression parsed but raised an error while running.
        Processing = 2,
    }
);
code_enum!(
    /// Why loading constructs failed.
    LoadError {
        /// The file could not be opened.
        OpenFile = 1,
        /// The contents are syntactically invalid.
        Parsing = 2,
    }
);
code_enum!(
    /// Why asserting a fact from text failed.
    AssertionError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The fact text is syntactically invalid.
        Parsing = 2,
        /// CLIPS declined the assertion, typically because an identical fact
        /// already exists and duplicates are not allowed.
        CouldNotAssert = 3,
        /// An evaluation error occurred as the fact propagated through the
        /// rule network.
        RuleNetwork = 4,
    }
);
code_enum!(
    /// Why retracting a fact failed.
    RetractionError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// CLIPS declined the retraction, for example because the fact was
        /// already retracted.
        CouldNotRetract = 2,
        /// An evaluation error occurred as the retraction propagated through
        /// the rule network.
        RuleNetwork = 3,
    }
);
code_enum!(
    /// Why a fact builder could not produce a fact.
    FactBuilderError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// No deftemplate of that name exists.
        TemplateNotFound = 2,
        /// The deftemplate is implied, so it has no named slots to fill.
        ImpliedTemplate = 3,
        /// CLIPS declined the assertion.
        CouldNotAssert = 4,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 5,
    }
);
code_enum!(
    /// Why an instance builder could not produce an instance.
    InstanceBuilderError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// No defclass of that name exists.
        ClassNotFound = 2,
        /// CLIPS declined to create the instance, for example because the
        /// class is abstract.
        CouldNotCreate = 3,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 4,
    }
);
code_enum!(
    /// Why deleting an instance failed.
    UnmakeInstanceError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// CLIPS declined the deletion.
        CouldNotDelete = 2,
        /// The instance had already been deleted.
        Deleted = 3,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 4,
    }
);
code_enum!(
    /// Why creating an instance from `make-instance` syntax failed.
    MakeInstanceError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The instance text is syntactically invalid.
        Parsing = 2,
        /// CLIPS declined to create the instance.
        CouldNotCreate = 3,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 4,
    }
);
code_enum!(
    /// Why calling a CLIPS function failed.
    FunctionCallError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// No function, deffunction, or generic of that name exists.
        FunctionNotFound = 2,
        /// The name resolves to something that cannot be called this way.
        InvalidFunction = 3,
        /// The number of arguments does not match the function's signature.
        ArgumentCount = 4,
        /// An argument's type is not allowed at that position.
        ArgumentType = 5,
        /// The function raised an error while running.
        Processing = 6,
    }
);
code_enum!(
    /// Why modifying a fact failed.
    FactModifierError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The fact being modified has been retracted.
        Retracted = 2,
        /// The fact's deftemplate is implied, so it has no named slots.
        ImpliedTemplate = 3,
        /// CLIPS declined the modification.
        CouldNotModify = 4,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 5,
    }
);
code_enum!(
    /// Why modifying an instance failed.
    InstanceModifierError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The instance being modified has been deleted.
        Deleted = 2,
        /// CLIPS declined the modification.
        CouldNotModify = 3,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 4,
    }
);
code_enum!(
    /// Why writing a slot failed.
    ///
    /// The constraint variants report which facet of the slot's declared
    /// constraints the value violated.
    PutSlotError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The builder, modifier, or instance is not in a state that accepts
        /// slot writes.
        InvalidTarget = 2,
        /// The target has no slot of that name.
        SlotNotFound = 3,
        /// The value's type is not among the slot's allowed types.
        Type = 4,
        /// A numeric value falls outside the slot's declared range.
        Range = 5,
        /// The value is not among the slot's allowed values.
        AllowedValues = 6,
        /// A multifield value's length violates the slot's cardinality.
        Cardinality = 7,
        /// An instance value's class is not among the slot's allowed classes.
        AllowedClasses = 8,
        /// Evaluating the value raised an error.
        Evaluation = 9,
        /// An evaluation error occurred in the rule network.
        RuleNetwork = 10,
    }
);
code_enum!(
    /// Why reading a slot failed.
    GetSlotError {
        /// A required argument was NULL; a bug in this crate.
        NullPointer = 1,
        /// The fact or instance is not in a state that can be read.
        InvalidTarget = 2,
        /// The target has no slot of that name.
        SlotNotFound = 3,
    }
);

impl std::fmt::Display for Error {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "CLIPS error: {self:?}")
    }
}
impl std::error::Error for Error {}