Skip to main content

clips_bindings/
error.rs

1//! Typed errors.
2//!
3//! Each CLIPS error enum becomes a Rust enum with the same variants plus an
4//! `Unknown` case, so a code this crate does not recognise is reported
5//! rather than silently treated as success.
6
7use crate::PersistenceError;
8use std::ffi::NulError;
9
10/// The result type used throughout the crate.
11pub type Result<T> = std::result::Result<T, Error>;
12
13/// Anything that can go wrong in a CLIPS operation.
14///
15/// Most variants wrap a CLIPS error enum unchanged, so the specific code CLIPS
16/// reported is preserved rather than flattened into one opaque failure.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Error {
19    /// A Rust string contained a NUL byte and so cannot cross into C.
20    InteriorNul,
21    /// CLIPS could not allocate a new environment.
22    EnvironmentCreation,
23    /// A clear-ready hook vetoed [`crate::Environment::clear`].
24    ClearRejected,
25    /// Defining a construct failed.
26    Build(BuildError),
27    /// Evaluating an expression failed.
28    Evaluation(EvaluationError),
29    /// Loading constructs from a file or string failed.
30    Load(LoadError),
31    /// Asserting a fact failed.
32    Assertion(AssertionError),
33    /// Retracting a fact failed.
34    Retraction(RetractionError),
35    /// Creating or asserting through a fact builder failed.
36    FactBuilder(FactBuilderError),
37    /// Creating or making through an instance builder failed.
38    InstanceBuilder(InstanceBuilderError),
39    /// Creating an instance from `make-instance` syntax failed.
40    MakeInstance(MakeInstanceError),
41    /// Deleting an instance failed.
42    UnmakeInstance(UnmakeInstanceError),
43    /// Calling a CLIPS function failed.
44    FunctionCall(FunctionCallError),
45    /// Modifying a fact failed.
46    FactModifier(FactModifierError),
47    /// Modifying an instance failed.
48    InstanceModifier(InstanceModifierError),
49    /// Saving or loading constructs, facts, or instances failed.
50    Persistence(PersistenceError),
51    /// Writing a slot failed.
52    PutSlot(PutSlotError),
53    /// Reading a slot failed.
54    GetSlot(GetSlotError),
55    /// A value carried a CLIPS type tag this crate does not model. The payload
56    /// is the raw tag from the value's `TypeHeader`.
57    UnexpectedValueType(u16),
58    /// A handle or value from a different CLIPS environment was supplied.
59    ForeignEnvironment,
60}
61
62impl From<NulError> for Error {
63    fn from(_: NulError) -> Self {
64        Self::InteriorNul
65    }
66}
67
68macro_rules! code_enum {
69    (
70        $(#[$enum_meta:meta])*
71        $name:ident { $($(#[$variant_meta:meta])* $variant:ident = $value:literal),+ $(,)? }
72    ) => {
73        $(#[$enum_meta])*
74        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75        pub enum $name {
76            $($(#[$variant_meta])* $variant,)+
77            /// A code this crate does not recognise, reported rather than
78            /// silently treated as success. Seeing one means CLIPS gained a
79            /// code since 6.4.2 or the declaration is wrong.
80            Unknown(u32),
81        }
82        impl From<u32> for $name {
83            fn from(value: u32) -> Self {
84                match value { $($value => Self::$variant,)+ value => Self::Unknown(value) }
85            }
86        }
87    };
88}
89
90// `NullPointer` appears throughout because CLIPS reports it when a required
91// argument is NULL. The safe API cannot produce one, so it indicates a bug in
92// this crate rather than in calling code.
93//
94// `RuleNetwork` likewise recurs: CLIPS raises it when an evaluation error
95// happens while the change propagates through the rule network — a failing
96// join test or right-hand side — so the operation itself was accepted but
97// something it triggered failed.
98
99code_enum!(
100    /// Why defining a construct failed.
101    BuildError {
102        /// CLIPS parsed the construct but declined to define it, for example
103        /// because a construct of that name exists and is not deletable.
104        CouldNotBuild = 1,
105        /// The text does not begin with a known construct keyword.
106        ConstructNotFound = 2,
107        /// The construct text is syntactically invalid.
108        Parsing = 3,
109    }
110);
111code_enum!(
112    /// Why evaluating an expression failed.
113    EvaluationError {
114        /// The expression text is syntactically invalid.
115        Parsing = 1,
116        /// The expression parsed but raised an error while running.
117        Processing = 2,
118    }
119);
120code_enum!(
121    /// Why loading constructs failed.
122    LoadError {
123        /// The file could not be opened.
124        OpenFile = 1,
125        /// The contents are syntactically invalid.
126        Parsing = 2,
127    }
128);
129code_enum!(
130    /// Why asserting a fact from text failed.
131    AssertionError {
132        /// A required argument was NULL; a bug in this crate.
133        NullPointer = 1,
134        /// The fact text is syntactically invalid.
135        Parsing = 2,
136        /// CLIPS declined the assertion, typically because an identical fact
137        /// already exists and duplicates are not allowed.
138        CouldNotAssert = 3,
139        /// An evaluation error occurred as the fact propagated through the
140        /// rule network.
141        RuleNetwork = 4,
142    }
143);
144code_enum!(
145    /// Why retracting a fact failed.
146    RetractionError {
147        /// A required argument was NULL; a bug in this crate.
148        NullPointer = 1,
149        /// CLIPS declined the retraction, for example because the fact was
150        /// already retracted.
151        CouldNotRetract = 2,
152        /// An evaluation error occurred as the retraction propagated through
153        /// the rule network.
154        RuleNetwork = 3,
155    }
156);
157code_enum!(
158    /// Why a fact builder could not produce a fact.
159    FactBuilderError {
160        /// A required argument was NULL; a bug in this crate.
161        NullPointer = 1,
162        /// No deftemplate of that name exists.
163        TemplateNotFound = 2,
164        /// The deftemplate is implied, so it has no named slots to fill.
165        ImpliedTemplate = 3,
166        /// CLIPS declined the assertion.
167        CouldNotAssert = 4,
168        /// An evaluation error occurred in the rule network.
169        RuleNetwork = 5,
170    }
171);
172code_enum!(
173    /// Why an instance builder could not produce an instance.
174    InstanceBuilderError {
175        /// A required argument was NULL; a bug in this crate.
176        NullPointer = 1,
177        /// No defclass of that name exists.
178        ClassNotFound = 2,
179        /// CLIPS declined to create the instance, for example because the
180        /// class is abstract.
181        CouldNotCreate = 3,
182        /// An evaluation error occurred in the rule network.
183        RuleNetwork = 4,
184    }
185);
186code_enum!(
187    /// Why deleting an instance failed.
188    UnmakeInstanceError {
189        /// A required argument was NULL; a bug in this crate.
190        NullPointer = 1,
191        /// CLIPS declined the deletion.
192        CouldNotDelete = 2,
193        /// The instance had already been deleted.
194        Deleted = 3,
195        /// An evaluation error occurred in the rule network.
196        RuleNetwork = 4,
197    }
198);
199code_enum!(
200    /// Why creating an instance from `make-instance` syntax failed.
201    MakeInstanceError {
202        /// A required argument was NULL; a bug in this crate.
203        NullPointer = 1,
204        /// The instance text is syntactically invalid.
205        Parsing = 2,
206        /// CLIPS declined to create the instance.
207        CouldNotCreate = 3,
208        /// An evaluation error occurred in the rule network.
209        RuleNetwork = 4,
210    }
211);
212code_enum!(
213    /// Why calling a CLIPS function failed.
214    FunctionCallError {
215        /// A required argument was NULL; a bug in this crate.
216        NullPointer = 1,
217        /// No function, deffunction, or generic of that name exists.
218        FunctionNotFound = 2,
219        /// The name resolves to something that cannot be called this way.
220        InvalidFunction = 3,
221        /// The number of arguments does not match the function's signature.
222        ArgumentCount = 4,
223        /// An argument's type is not allowed at that position.
224        ArgumentType = 5,
225        /// The function raised an error while running.
226        Processing = 6,
227    }
228);
229code_enum!(
230    /// Why modifying a fact failed.
231    FactModifierError {
232        /// A required argument was NULL; a bug in this crate.
233        NullPointer = 1,
234        /// The fact being modified has been retracted.
235        Retracted = 2,
236        /// The fact's deftemplate is implied, so it has no named slots.
237        ImpliedTemplate = 3,
238        /// CLIPS declined the modification.
239        CouldNotModify = 4,
240        /// An evaluation error occurred in the rule network.
241        RuleNetwork = 5,
242    }
243);
244code_enum!(
245    /// Why modifying an instance failed.
246    InstanceModifierError {
247        /// A required argument was NULL; a bug in this crate.
248        NullPointer = 1,
249        /// The instance being modified has been deleted.
250        Deleted = 2,
251        /// CLIPS declined the modification.
252        CouldNotModify = 3,
253        /// An evaluation error occurred in the rule network.
254        RuleNetwork = 4,
255    }
256);
257code_enum!(
258    /// Why writing a slot failed.
259    ///
260    /// The constraint variants report which facet of the slot's declared
261    /// constraints the value violated.
262    PutSlotError {
263        /// A required argument was NULL; a bug in this crate.
264        NullPointer = 1,
265        /// The builder, modifier, or instance is not in a state that accepts
266        /// slot writes.
267        InvalidTarget = 2,
268        /// The target has no slot of that name.
269        SlotNotFound = 3,
270        /// The value's type is not among the slot's allowed types.
271        Type = 4,
272        /// A numeric value falls outside the slot's declared range.
273        Range = 5,
274        /// The value is not among the slot's allowed values.
275        AllowedValues = 6,
276        /// A multifield value's length violates the slot's cardinality.
277        Cardinality = 7,
278        /// An instance value's class is not among the slot's allowed classes.
279        AllowedClasses = 8,
280        /// Evaluating the value raised an error.
281        Evaluation = 9,
282        /// An evaluation error occurred in the rule network.
283        RuleNetwork = 10,
284    }
285);
286code_enum!(
287    /// Why reading a slot failed.
288    GetSlotError {
289        /// A required argument was NULL; a bug in this crate.
290        NullPointer = 1,
291        /// The fact or instance is not in a state that can be read.
292        InvalidTarget = 2,
293        /// The target has no slot of that name.
294        SlotNotFound = 3,
295    }
296);
297
298impl std::fmt::Display for Error {
299    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
300        write!(formatter, "CLIPS error: {self:?}")
301    }
302}
303impl std::error::Error for Error {}