Skip to main content

clips_bindings/
environment.rs

1//! The CLIPS environment: creation, execution, value creation, and
2//! ownership of every Rust callback registered with it.
3
4use std::ffi::CString;
5use std::marker::PhantomData;
6use std::ptr::NonNull;
7use std::rc::Rc;
8
9use crate::error::{BuildError, Error, EvaluationError, LoadError, Result};
10use crate::{
11    data::EnvironmentData,
12    fact::{Fact, FactBuilder, Facts},
13    ffi,
14    function::FunctionCall,
15    hook::{
16        FactChange, FactEventKind, HookEntry, HookError, HookKind, ParserDiagnostic,
17        ParserErrorContext, ReadyHookKind, RuleFirePhase,
18    },
19    instance::{InstanceBuilder, Instances},
20    multifield::{Multifield, MultifieldBuilder},
21    router::{Router, RouterEntry, RouterError},
22    udf::{
23        UdfCallbackError, UdfRegistration, UdfRegistrationError, UdfReturn, UdfSignature, UdfValue,
24    },
25    value::Value,
26};
27
28/// An owning, single-thread-affine CLIPS environment.
29///
30/// CLIPS does not synchronize access to an environment, and registered Rust
31/// callbacks may capture thread-affine state. Consequently an environment and
32/// every handle borrowed from it must remain on the thread that created it.
33pub struct Environment {
34    pub(crate) raw: NonNull<ffi::Environment>,
35    pub(crate) routers: Vec<RouterEntry>,
36    // Each address is handed to CLIPS as callback context and must stay stable.
37    #[allow(clippy::vec_box)]
38    pub(crate) udfs: Vec<Box<UdfRegistration>>,
39    pub(crate) hooks: Vec<HookEntry>,
40    // CLIPS stores a single parser-error callback, not a named registry.
41    parser_error: Option<Box<ParserErrorContext>>,
42    // Per-environment Rust state, kept on the Rust side rather than in CLIPS's
43    // shared environment-data slots.
44    pub(crate) data: EnvironmentData,
45    thread_affinity: PhantomData<Rc<()>>,
46}
47
48impl Environment {
49    /// Creates a CLIPS environment, destroyed when the value is dropped.
50    ///
51    /// Environments are independent: constructs, facts, and interned atoms
52    /// belong to exactly one, and mixing handles between them is refused with
53    /// [`Error::ForeignEnvironment`].
54    pub fn new() -> Result<Self> {
55        NonNull::new(unsafe { ffi::CreateEnvironment() })
56            .map(|raw| Self {
57                raw,
58                routers: Vec::new(),
59                udfs: Vec::new(),
60                hooks: Vec::new(),
61                parser_error: None,
62                data: EnvironmentData::default(),
63                thread_affinity: PhantomData,
64            })
65            .ok_or(Error::EnvironmentCreation)
66    }
67    /// Removes every construct, fact, and instance.
68    ///
69    /// Fails with [`Error::ClearRejected`] if a clear-ready hook vetoes it.
70    /// Taking `&mut self` is what makes this safe: no handle into the
71    /// environment can be alive across it.
72    pub fn clear(&mut self) -> Result<()> {
73        unsafe { ffi::Clear(self.raw.as_ptr()) }
74            .then_some(())
75            .ok_or(Error::ClearRejected)
76    }
77
78    /// Removes all facts and instances, then asserts the deffacts and creates
79    /// the definstances. Constructs are kept.
80    pub fn reset(&mut self) {
81        unsafe { ffi::Reset(self.raw.as_ptr()) }
82    }
83
84    /// Fires rules until the agenda empties, returning how many fired.
85    ///
86    /// `limit` caps the number of firings; `None` means no limit.
87    pub fn run(&mut self, limit: Option<u64>) -> u64 {
88        unsafe {
89            ffi::Run(
90                self.raw.as_ptr(),
91                limit.map_or(-1, |n| n.min(i64::MAX as u64) as i64),
92            ) as u64
93        }
94    }
95    /// Whether evaluation is currently halted.
96    ///
97    /// This is set when [`Environment::eval`] fails, and reads `true` until the
98    /// next evaluation, which clears it. It does **not** report that a run was
99    /// stopped by `(halt)`: [`Environment::run`] clears the flag on entry and
100    /// `(halt)` sets the separate rule-halt flag, so neither survives a run.
101    ///
102    /// The flag exists so an embedding application can interrupt CLIPS from a
103    /// signal handler or another thread of control. This crate cannot offer
104    /// that: setting it takes `&mut self` and so cannot overlap a run, and
105    /// CLIPS 6.4.2 hands Rust callbacks no environment to reach it through.
106    pub fn halt_execution(&self) -> bool {
107        unsafe { ffi::GetHaltExecution(self.raw.as_ptr()) }
108    }
109
110    /// Sets or clears the evaluation-halt flag.
111    ///
112    /// Its only useful direction is clearing. Setting it does **not** stop the
113    /// next [`Environment::run`], which clears the flag on entry — see
114    /// [`Environment::halt_execution`] for why no safe API can interrupt a run.
115    pub fn set_halt_execution(&mut self, halt: bool) {
116        unsafe { ffi::SetHaltExecution(self.raw.as_ptr(), halt) }
117    }
118
119    /// Whether rule firing is halted, as `(halt)` sets during a run.
120    ///
121    /// [`Environment::run`] clears this both on entry and on return, so outside
122    /// a run it always reads `false`.
123    pub fn halt_rules(&self) -> bool {
124        unsafe { ffi::GetHaltRules(self.raw.as_ptr()) }
125    }
126
127    /// Sets or clears the rule-halt flag.
128    ///
129    /// `Run` overwrites it on entry, so this cannot stop the next run; it is
130    /// bound for completeness against the CLIPS API rather than as a working
131    /// interruption mechanism. CLIPS's `Halt` function is deliberately not
132    /// bound: it does exactly `set_halt_rules(true)` and so is equally inert,
133    /// under a name that promises otherwise.
134    pub fn set_halt_rules(&mut self, halt: bool) {
135        unsafe { ffi::SetHaltRules(self.raw.as_ptr(), halt) }
136    }
137
138    /// Whether the rule network resizes its beta memories dynamically.
139    pub fn beta_memory_resizing(&self) -> bool {
140        unsafe { ffi::GetBetaMemoryResizing(self.raw.as_ptr()) }
141    }
142
143    /// Sets beta-memory resizing and returns the previous setting.
144    pub fn set_beta_memory_resizing(&mut self, resize: bool) -> bool {
145        unsafe { ffi::SetBetaMemoryResizing(self.raw.as_ptr(), resize) }
146    }
147
148    /// Writes `text` to the `stdout` logical name, without a trailing newline.
149    ///
150    /// Output reaches whichever [`crate::Router`] claims the name, so this is
151    /// how Rust emits into the same stream CLIPS constructs print to.
152    pub fn write(&self, text: &str) -> Result<()> {
153        let text = CString::new(text)?;
154        unsafe { ffi::Write(self.raw.as_ptr(), text.as_ptr()) };
155        Ok(())
156    }
157
158    /// Writes `text` to `stdout` followed by a newline.
159    pub fn writeln(&self, text: &str) -> Result<()> {
160        let text = CString::new(text)?;
161        unsafe { ffi::Writeln(self.raw.as_ptr(), text.as_ptr()) };
162        Ok(())
163    }
164
165    /// Writes `text` to an arbitrary logical name, such as `werror` or a name
166    /// a registered router claims.
167    pub fn write_to(&self, logical_name: &str, text: &str) -> Result<()> {
168        let logical_name = CString::new(logical_name)?;
169        let text = CString::new(text)?;
170        unsafe { ffi::WriteString(self.raw.as_ptr(), logical_name.as_ptr(), text.as_ptr()) };
171        Ok(())
172    }
173
174    /// Defines one construct from CLIPS source text, for example
175    /// `"(deftemplate person (slot name))"`.
176    ///
177    /// CLIPS's own diagnostics go to the `werror` logical name; register a
178    /// [`Router`] for it to capture them.
179    pub fn build(&mut self, construct: &str) -> Result<()> {
180        let construct = CString::new(construct)?;
181        match unsafe { ffi::Build(self.raw.as_ptr(), construct.as_ptr()) } {
182            0 => Ok(()),
183            code => Err(Error::Build(BuildError::from(code))),
184        }
185    }
186
187    /// Loads constructs from a file.
188    pub fn load(&mut self, path: &str) -> Result<()> {
189        let path = CString::new(path)?;
190        match unsafe { ffi::Load(self.raw.as_ptr(), path.as_ptr()) } {
191            0 => Ok(()),
192            code => Err(Error::Load(LoadError::from(code))),
193        }
194    }
195    /// Loads constructs from CLIPS source text.
196    ///
197    /// CLIPS reports only success or failure here, with no error detail, so a
198    /// failure is always [`LoadError::Parsing`]. Install a parser-error hook
199    /// with [`Environment::set_parser_error_hook`] for the diagnostics.
200    pub fn load_str(&mut self, source: &str) -> Result<()> {
201        let source = CString::new(source)?;
202        if unsafe {
203            ffi::LoadFromString(self.raw.as_ptr(), source.as_ptr(), source.as_bytes().len())
204        } {
205            Ok(())
206        } else {
207            Err(Error::Load(LoadError::Parsing))
208        }
209    }
210    /// Evaluates a CLIPS expression and returns its retained result.
211    ///
212    /// This takes `&mut self` because an expression can assert, retract, or
213    /// redefine anything, which would invalidate outstanding handles.
214    pub fn eval(&mut self, expression: &str) -> Result<Value<'_>> {
215        let expression = CString::new(expression)?;
216        let mut raw = ffi::CLIPSValue {
217            value: std::ptr::null_mut(),
218        };
219        match unsafe { ffi::Eval(self.raw.as_ptr(), expression.as_ptr(), &mut raw) } {
220            0 => {
221                unsafe { ffi::RetainCV(self.raw.as_ptr(), &mut raw) };
222                Ok(Value::new(self, raw))
223            }
224            code => Err(Error::Evaluation(EvaluationError::from(code))),
225        }
226    }
227    /// True when `other` wraps the same CLIPS environment as `self`.
228    ///
229    /// Handles carry the environment they came from, so this is what the
230    /// generic value-accepting APIs use to refuse cross-environment values.
231    pub(crate) fn is_same(&self, other: &Environment) -> bool {
232        self.raw == other.raw
233    }
234    /// Returns the raw form of `value` after confirming it belongs to this
235    /// environment.
236    pub(crate) fn check_value(&self, value: &Value<'_>) -> Result<ffi::CLIPSValue> {
237        if self.is_same(value.environment()) {
238            Ok(value.raw())
239        } else {
240            Err(Error::ForeignEnvironment)
241        }
242    }
243    /// Creates a retained CLIPS integer.
244    pub fn create_integer(&self, value: i64) -> Value<'_> {
245        Value::retaining(
246            self,
247            ffi::CLIPSValue {
248                integer: unsafe { ffi::CreateInteger(self.raw.as_ptr(), value) },
249            },
250        )
251    }
252    /// Creates a retained CLIPS float.
253    pub fn create_float(&self, value: f64) -> Value<'_> {
254        Value::retaining(
255            self,
256            ffi::CLIPSValue {
257                float: unsafe { ffi::CreateFloat(self.raw.as_ptr(), value) },
258            },
259        )
260    }
261    /// Creates the retained CLIPS `TRUE` or `FALSE` symbol.
262    pub fn create_boolean(&self, value: bool) -> Value<'_> {
263        Value::retaining(
264            self,
265            ffi::CLIPSValue {
266                lexeme: unsafe { ffi::CreateBoolean(self.raw.as_ptr(), value) },
267            },
268        )
269    }
270    /// Creates a retained CLIPS symbol.
271    pub fn create_symbol(&self, value: &str) -> Result<Value<'_>> {
272        self.create_lexeme(value, ffi::CreateSymbol)
273    }
274    /// Creates a retained CLIPS string.
275    pub fn create_string(&self, value: &str) -> Result<Value<'_>> {
276        self.create_lexeme(value, ffi::CreateString)
277    }
278    /// Creates a retained CLIPS instance name.
279    pub fn create_instance_name(&self, value: &str) -> Result<Value<'_>> {
280        self.create_lexeme(value, ffi::CreateInstanceName)
281    }
282    fn create_lexeme(
283        &self,
284        value: &str,
285        create: unsafe extern "C" fn(
286            *mut ffi::Environment,
287            *const std::ffi::c_char,
288        ) -> *mut ffi::CLIPSLexeme,
289    ) -> Result<Value<'_>> {
290        let value = CString::new(value)?;
291        Ok(Value::retaining(
292            self,
293            ffi::CLIPSValue {
294                lexeme: unsafe { create(self.raw.as_ptr(), value.as_ptr()) },
295            },
296        ))
297    }
298    /// Parses `source` as a sequence of CLIPS fields and returns them as a
299    /// retained multifield.
300    pub fn string_to_multifield(&self, source: &str) -> Result<Multifield<'_>> {
301        let source = CString::new(source)?;
302        let raw = unsafe { ffi::StringToMultifield(self.raw.as_ptr(), source.as_ptr()) };
303        if raw.is_null() {
304            return Err(Error::Evaluation(EvaluationError::Parsing));
305        }
306        Ok(Multifield::from_value(Value::retaining(
307            self,
308            ffi::CLIPSValue { multifield: raw },
309        )))
310    }
311    /// Asserts a fact from CLIPS text, for example `"(person (name ada))"`.
312    ///
313    /// Use [`Environment::fact_builder`] to avoid formatting and re-parsing
314    /// slot values.
315    pub fn assert_string(&self, source: &str) -> Result<Fact<'_>> {
316        let source = CString::new(source)?;
317        let raw = unsafe { ffi::AssertString(self.raw.as_ptr(), source.as_ptr()) };
318        Fact::from_result(self, raw, unsafe {
319            ffi::GetAssertStringError(self.raw.as_ptr())
320        })
321    }
322    // Builders take a shared borrow: several may exist at once, and values
323    // created from the same environment stay usable while they live. The shared
324    // borrow still blocks `clear`, `reset`, `run`, and every other `&mut self`
325    // operation that could invalidate what a builder is about to produce.
326    /// Starts building a fact of the named deftemplate.
327    pub fn fact_builder(&self, template: &str) -> Result<FactBuilder<'_>> {
328        FactBuilder::new(self, template)
329    }
330
331    /// Iterates every fact in index order.
332    pub fn facts(&self) -> Facts<'_> {
333        Facts::new(self)
334    }
335
336    /// The number of facts currently asserted.
337    pub fn fact_count(&self) -> usize {
338        unsafe { ffi::GetNumberOfFacts(self.raw.as_ptr()) as usize }
339    }
340
341    /// Starts building an instance of the named defclass.
342    pub fn instance_builder(&self, class: &str) -> Result<InstanceBuilder<'_>> {
343        InstanceBuilder::new(self, class)
344    }
345
346    /// Iterates every instance in every module.
347    pub fn instances(&self) -> Instances<'_> {
348        Instances::new(self)
349    }
350
351    /// Starts building a multifield. `capacity` is a hint; the builder grows
352    /// as needed.
353    pub fn multifield_builder(&self, capacity: usize) -> Result<MultifieldBuilder<'_>> {
354        MultifieldBuilder::new(self, capacity)
355    }
356
357    /// Starts building a call to a CLIPS function. `capacity` is a hint for
358    /// the number of arguments.
359    pub fn function_call(&self, capacity: usize) -> Result<FunctionCall<'_>> {
360        FunctionCall::new(self, capacity)
361    }
362    /// Registers a router, which is how Rust captures CLIPS output and
363    /// supplies its input.
364    ///
365    /// Higher `priority` wins when several routers claim the same logical
366    /// name; CLIPS's own console routers sit at priority 0 to 30. The router
367    /// is owned by the environment and dropped when removed or when the
368    /// environment is.
369    pub fn register_router<R: Router>(
370        &mut self,
371        name: &str,
372        priority: i32,
373        router: R,
374    ) -> std::result::Result<(), RouterError> {
375        let entry = RouterEntry::register(self.raw, name, priority, router)?;
376        self.routers.push(entry);
377        Ok(())
378    }
379    /// Unregisters a router and drops it.
380    ///
381    /// If CLIPS refuses the removal the router is kept, so the registration
382    /// and the owned callback never disagree.
383    pub fn remove_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
384        let position = self
385            .routers
386            .iter()
387            .position(|entry| entry.name().to_bytes() == name.as_bytes())
388            .ok_or(RouterError::NotFound)?;
389        let entry = self.routers.remove(position);
390        match entry.unregister(self.raw) {
391            Ok(()) => Ok(()),
392            Err((entry, error)) => {
393                self.routers.insert(position, entry);
394                Err(error)
395            }
396        }
397    }
398    /// Re-enables a deactivated router.
399    pub fn activate_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
400        self.router_entry(name)?.activate(self.raw)
401    }
402
403    /// Stops CLIPS dispatching to a router without unregistering it.
404    pub fn deactivate_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
405        self.router_entry(name)?.deactivate(self.raw)
406    }
407    fn router_entry(&self, name: &str) -> std::result::Result<&RouterEntry, RouterError> {
408        self.routers
409            .iter()
410            .find(|entry| entry.name().to_bytes() == name.as_bytes())
411            .ok_or(RouterError::NotFound)
412    }
413    /// Registers a Rust function callable from CLIPS code under `name`.
414    ///
415    /// The callback is owned by the environment. It runs inside CLIPS, so a
416    /// panic is caught at the boundary rather than unwinding through C, and
417    /// re-entering the same function is refused instead of aliasing its state;
418    /// both become a [`UdfCallbackError`] retrievable with
419    /// [`Environment::take_udf_error`].
420    ///
421    /// The callback is `'static` but its arguments are borrowed for the call
422    /// only, so fact, instance, and external addresses can be passed back as
423    /// results but cannot be stored.
424    pub fn add_udf<F>(
425        &mut self,
426        name: &str,
427        signature: UdfSignature,
428        callback: F,
429    ) -> std::result::Result<(), UdfRegistrationError>
430    where
431        F: for<'call> FnMut(
432                &[UdfValue<'call>],
433            ) -> std::result::Result<UdfReturn<'call>, UdfCallbackError>
434            + 'static,
435    {
436        let name = CString::new(name).map_err(UdfRegistrationError::from)?;
437        let mut registration = UdfRegistration::new(name, signature, callback);
438        let context = registration.context();
439        let argument_types = registration
440            .signature
441            .arguments
442            .as_ref()
443            .map_or(std::ptr::null(), |value| value.as_ptr());
444        let code = unsafe {
445            ffi::AddUDF(
446                self.raw.as_ptr(),
447                registration.name.as_ptr(),
448                registration.signature.returns.as_ptr(),
449                registration.signature.min_args,
450                registration.signature.max_args,
451                argument_types,
452                Some(crate::udf::trampoline),
453                registration.name.as_ptr(),
454                context,
455            )
456        };
457        if code != 0 {
458            return Err(UdfRegistrationError::from_code(code));
459        }
460        self.udfs.push(registration);
461        Ok(())
462    }
463    /// Unregisters a user-defined function and drops its callback.
464    pub fn remove_udf(&mut self, name: &str) -> std::result::Result<(), UdfRegistrationError> {
465        let position = self
466            .udfs
467            .iter()
468            .position(|entry| entry.name.to_bytes() == name.as_bytes())
469            .ok_or(UdfRegistrationError::NotFound)?;
470        if unsafe { ffi::RemoveUDF(self.raw.as_ptr(), self.udfs[position].name.as_ptr()) } {
471            self.udfs.remove(position);
472            Ok(())
473        } else {
474            Err(UdfRegistrationError::NotFound)
475        }
476    }
477    /// Takes the error a user-defined function last reported, clearing it.
478    ///
479    /// CLIPS only learns that a UDF failed, not why, so the reason is kept
480    /// here and retrieved by name after the call that triggered it.
481    pub fn take_udf_error(&self, name: &str) -> Option<UdfCallbackError> {
482        self.udfs
483            .iter()
484            .find(|entry| entry.name.to_bytes() == name.as_bytes())
485            .and_then(|entry| entry.take_error())
486    }
487    /// Registers a lifecycle callback, run when CLIPS reaches the given point.
488    ///
489    /// Lower `priority` runs earlier. Names must be unique: CLIPS would accept
490    /// a duplicate but could not then remove it reliably, so one is refused.
491    /// Not every kind can be unregistered before the environment is dropped;
492    /// see [`HookKind::is_removable`].
493    pub fn add_hook<F>(
494        &mut self,
495        name: &str,
496        kind: HookKind,
497        priority: i32,
498        callback: F,
499    ) -> std::result::Result<(), HookError>
500    where
501        F: FnMut() + 'static,
502    {
503        self.reject_duplicate_hook(name)?;
504        let entry = HookEntry::void(self.raw.as_ptr(), name, kind, priority, callback)?;
505        self.hooks.push(entry);
506        Ok(())
507    }
508    /// Registers a veto hook. Returning `false` from `callback` refuses the
509    /// operation.
510    pub fn add_veto_hook<F>(
511        &mut self,
512        name: &str,
513        kind: ReadyHookKind,
514        priority: i32,
515        callback: F,
516    ) -> std::result::Result<(), HookError>
517    where
518        F: FnMut() -> bool + 'static,
519    {
520        self.reject_duplicate_hook(name)?;
521        let entry = HookEntry::ready(self.raw.as_ptr(), name, kind, priority, callback)?;
522        self.hooks.push(entry);
523        Ok(())
524    }
525    /// Registers a veto hook for [`Environment::clear`], which fails with
526    /// [`Error::ClearRejected`] if the callback returns `false`.
527    ///
528    /// Shorthand for [`Environment::add_veto_hook`] with
529    /// [`ReadyHookKind::Clear`].
530    pub fn add_clear_ready_hook<F>(
531        &mut self,
532        name: &str,
533        priority: i32,
534        callback: F,
535    ) -> std::result::Result<(), HookError>
536    where
537        F: FnMut() -> bool + 'static,
538    {
539        self.add_veto_hook(name, ReadyHookKind::Clear, priority, callback)
540    }
541    /// Registers a hook called with the rule name each time a rule fires.
542    pub fn add_rule_fire_hook<F>(
543        &mut self,
544        name: &str,
545        phase: RuleFirePhase,
546        priority: i32,
547        callback: F,
548    ) -> std::result::Result<(), HookError>
549    where
550        F: FnMut(&str) + 'static,
551    {
552        self.reject_duplicate_hook(name)?;
553        let entry = HookEntry::rule_fired(self.raw.as_ptr(), name, phase, priority, callback)?;
554        self.hooks.push(entry);
555        Ok(())
556    }
557    /// Registers a hook called when a fact is asserted, retracted, or modified.
558    ///
559    /// The callback receives a [`FactChange`] describing what happened. A
560    /// modification arrives as two calls, one for the replaced fact and one for
561    /// its replacement, matching how CLIPS reports it.
562    pub fn add_fact_hook<F>(
563        &mut self,
564        name: &str,
565        kind: FactEventKind,
566        priority: i32,
567        callback: F,
568    ) -> std::result::Result<(), HookError>
569    where
570        F: FnMut(&FactChange) + 'static,
571    {
572        self.reject_duplicate_hook(name)?;
573        let entry = HookEntry::fact(self.raw.as_ptr(), name, kind, priority, callback)?;
574        self.hooks.push(entry);
575        Ok(())
576    }
577    /// Registers a hook called for each module while constructs are saved.
578    ///
579    /// The callback receives the module name and the logical name being written
580    /// to, which is a router name rather than a file path.
581    pub fn add_save_hook<F>(
582        &mut self,
583        name: &str,
584        priority: i32,
585        callback: F,
586    ) -> std::result::Result<(), HookError>
587    where
588        F: FnMut(&str, &str) + 'static,
589    {
590        self.reject_duplicate_hook(name)?;
591        let entry = HookEntry::save(self.raw.as_ptr(), name, priority, callback)?;
592        self.hooks.push(entry);
593        Ok(())
594    }
595    /// Installs the parser-error callback, replacing any previous one.
596    ///
597    /// CLIPS keeps exactly one such callback per environment, so this is a
598    /// single slot rather than a named registry.
599    ///
600    /// CLIPS installs its error-capture router only on the load path, so
601    /// diagnostics are reported for [`Environment::load`] and
602    /// [`Environment::load_str`], not for [`Environment::build`]. Install the
603    /// callback before the parsing you want it to observe.
604    pub fn set_parser_error_hook<F>(&mut self, callback: F)
605    where
606        F: FnMut(&ParserDiagnostic) + 'static,
607    {
608        // The previous context stays alive until CLIPS has been pointed at the
609        // new one.
610        let context = ParserErrorContext::install(self.raw.as_ptr(), callback);
611        self.parser_error = Some(context);
612    }
613    /// Removes the parser-error callback, if one is installed.
614    pub fn clear_parser_error_hook(&mut self) {
615        ParserErrorContext::clear(self.raw.as_ptr());
616        self.parser_error = None;
617    }
618    /// Refuses a name already used by one of this environment's hooks.
619    ///
620    /// Several CLIPS hook lists accept duplicate names without complaint, which
621    /// would leave a registration that `remove_hook` could not fully undo.
622    fn reject_duplicate_hook(&self, name: &str) -> std::result::Result<(), HookError> {
623        if self
624            .hooks
625            .iter()
626            .any(|entry| entry.name() == name.as_bytes())
627        {
628            return Err(HookError::NameInUse);
629        }
630        Ok(())
631    }
632    /// Unregisters a hook and drops its callback.
633    ///
634    /// Some CLIPS hook lists have no removal entry point; a hook of such a kind
635    /// stays registered until the environment is destroyed. See
636    /// [`HookKind::is_removable`].
637    pub fn remove_hook(&mut self, name: &str) -> std::result::Result<(), HookError> {
638        let position = self
639            .hooks
640            .iter()
641            .position(|entry| entry.name() == name.as_bytes())
642            .ok_or(HookError::NotFound)?;
643        if self.hooks[position].unregister(self.raw.as_ptr()) {
644            self.hooks.remove(position);
645            Ok(())
646        } else {
647            Err(HookError::NotFound)
648        }
649    }
650}
651
652impl Default for Environment {
653    fn default() -> Self {
654        Self::new().expect("CLIPS environment creation failed")
655    }
656}
657impl Drop for Environment {
658    fn drop(&mut self) {
659        // CLIPS must stop pointing at the parser-error context before it is
660        // dropped.
661        if self.parser_error.is_some() {
662            ParserErrorContext::clear(self.raw.as_ptr());
663        }
664        let parser_error = self.parser_error.take();
665
666        let mut hooks = std::mem::take(&mut self.hooks);
667        hooks.retain(|entry| !entry.unregister(self.raw.as_ptr()));
668
669        let mut udfs = std::mem::take(&mut self.udfs);
670        udfs.retain(|registration| unsafe {
671            !ffi::RemoveUDF(self.raw.as_ptr(), registration.name.as_ptr())
672        });
673
674        let mut routers = Vec::new();
675        for entry in std::mem::take(&mut self.routers) {
676            if let Err((entry, _)) = entry.unregister(self.raw) {
677                routers.push(entry);
678            }
679        }
680
681        if !unsafe { ffi::DestroyEnvironment(self.raw.as_ptr()) } {
682            // CLIPS may still hold these callback pointers if both removal and
683            // destruction failed. Leaking is the only safe fallback.
684            std::mem::forget(hooks);
685            std::mem::forget(udfs);
686            std::mem::forget(routers);
687            std::mem::forget(parser_error);
688        }
689    }
690}