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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! The CLIPS environment: creation, execution, value creation, and
//! ownership of every Rust callback registered with it.

use std::ffi::CString;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::rc::Rc;

use crate::error::{BuildError, Error, EvaluationError, LoadError, Result};
use crate::{
    data::EnvironmentData,
    fact::{Fact, FactBuilder, Facts},
    ffi,
    function::FunctionCall,
    hook::{
        FactChange, FactEventKind, HookEntry, HookError, HookKind, ParserDiagnostic,
        ParserErrorContext, ReadyHookKind, RuleFirePhase,
    },
    instance::{InstanceBuilder, Instances},
    multifield::{Multifield, MultifieldBuilder},
    router::{Router, RouterEntry, RouterError},
    udf::{
        UdfCallbackError, UdfRegistration, UdfRegistrationError, UdfReturn, UdfSignature, UdfValue,
    },
    value::Value,
};

/// An owning, single-thread-affine CLIPS environment.
///
/// CLIPS does not synchronize access to an environment, and registered Rust
/// callbacks may capture thread-affine state. Consequently an environment and
/// every handle borrowed from it must remain on the thread that created it.
pub struct Environment {
    pub(crate) raw: NonNull<ffi::Environment>,
    pub(crate) routers: Vec<RouterEntry>,
    // Each address is handed to CLIPS as callback context and must stay stable.
    #[allow(clippy::vec_box)]
    pub(crate) udfs: Vec<Box<UdfRegistration>>,
    pub(crate) hooks: Vec<HookEntry>,
    // CLIPS stores a single parser-error callback, not a named registry.
    parser_error: Option<Box<ParserErrorContext>>,
    // Per-environment Rust state, kept on the Rust side rather than in CLIPS's
    // shared environment-data slots.
    pub(crate) data: EnvironmentData,
    thread_affinity: PhantomData<Rc<()>>,
}

impl Environment {
    /// Creates a CLIPS environment, destroyed when the value is dropped.
    ///
    /// Environments are independent: constructs, facts, and interned atoms
    /// belong to exactly one, and mixing handles between them is refused with
    /// [`Error::ForeignEnvironment`].
    pub fn new() -> Result<Self> {
        NonNull::new(unsafe { ffi::CreateEnvironment() })
            .map(|raw| Self {
                raw,
                routers: Vec::new(),
                udfs: Vec::new(),
                hooks: Vec::new(),
                parser_error: None,
                data: EnvironmentData::default(),
                thread_affinity: PhantomData,
            })
            .ok_or(Error::EnvironmentCreation)
    }
    /// Removes every construct, fact, and instance.
    ///
    /// Fails with [`Error::ClearRejected`] if a clear-ready hook vetoes it.
    /// Taking `&mut self` is what makes this safe: no handle into the
    /// environment can be alive across it.
    pub fn clear(&mut self) -> Result<()> {
        unsafe { ffi::Clear(self.raw.as_ptr()) }
            .then_some(())
            .ok_or(Error::ClearRejected)
    }

    /// Removes all facts and instances, then asserts the deffacts and creates
    /// the definstances. Constructs are kept.
    pub fn reset(&mut self) {
        unsafe { ffi::Reset(self.raw.as_ptr()) }
    }

    /// Fires rules until the agenda empties, returning how many fired.
    ///
    /// `limit` caps the number of firings; `None` means no limit.
    pub fn run(&mut self, limit: Option<u64>) -> u64 {
        unsafe {
            ffi::Run(
                self.raw.as_ptr(),
                limit.map_or(-1, |n| n.min(i64::MAX as u64) as i64),
            ) as u64
        }
    }
    /// Whether evaluation is currently halted.
    ///
    /// This is set when [`Environment::eval`] fails, and reads `true` until the
    /// next evaluation, which clears it. It does **not** report that a run was
    /// stopped by `(halt)`: [`Environment::run`] clears the flag on entry and
    /// `(halt)` sets the separate rule-halt flag, so neither survives a run.
    ///
    /// The flag exists so an embedding application can interrupt CLIPS from a
    /// signal handler or another thread of control. This crate cannot offer
    /// that: setting it takes `&mut self` and so cannot overlap a run, and
    /// CLIPS 6.4.2 hands Rust callbacks no environment to reach it through.
    pub fn halt_execution(&self) -> bool {
        unsafe { ffi::GetHaltExecution(self.raw.as_ptr()) }
    }

    /// Sets or clears the evaluation-halt flag.
    ///
    /// Its only useful direction is clearing. Setting it does **not** stop the
    /// next [`Environment::run`], which clears the flag on entry — see
    /// [`Environment::halt_execution`] for why no safe API can interrupt a run.
    pub fn set_halt_execution(&mut self, halt: bool) {
        unsafe { ffi::SetHaltExecution(self.raw.as_ptr(), halt) }
    }

    /// Whether rule firing is halted, as `(halt)` sets during a run.
    ///
    /// [`Environment::run`] clears this both on entry and on return, so outside
    /// a run it always reads `false`.
    pub fn halt_rules(&self) -> bool {
        unsafe { ffi::GetHaltRules(self.raw.as_ptr()) }
    }

    /// Sets or clears the rule-halt flag.
    ///
    /// `Run` overwrites it on entry, so this cannot stop the next run; it is
    /// bound for completeness against the CLIPS API rather than as a working
    /// interruption mechanism. CLIPS's `Halt` function is deliberately not
    /// bound: it does exactly `set_halt_rules(true)` and so is equally inert,
    /// under a name that promises otherwise.
    pub fn set_halt_rules(&mut self, halt: bool) {
        unsafe { ffi::SetHaltRules(self.raw.as_ptr(), halt) }
    }

    /// Whether the rule network resizes its beta memories dynamically.
    pub fn beta_memory_resizing(&self) -> bool {
        unsafe { ffi::GetBetaMemoryResizing(self.raw.as_ptr()) }
    }

    /// Sets beta-memory resizing and returns the previous setting.
    pub fn set_beta_memory_resizing(&mut self, resize: bool) -> bool {
        unsafe { ffi::SetBetaMemoryResizing(self.raw.as_ptr(), resize) }
    }

    /// Writes `text` to the `stdout` logical name, without a trailing newline.
    ///
    /// Output reaches whichever [`crate::Router`] claims the name, so this is
    /// how Rust emits into the same stream CLIPS constructs print to.
    pub fn write(&self, text: &str) -> Result<()> {
        let text = CString::new(text)?;
        unsafe { ffi::Write(self.raw.as_ptr(), text.as_ptr()) };
        Ok(())
    }

    /// Writes `text` to `stdout` followed by a newline.
    pub fn writeln(&self, text: &str) -> Result<()> {
        let text = CString::new(text)?;
        unsafe { ffi::Writeln(self.raw.as_ptr(), text.as_ptr()) };
        Ok(())
    }

    /// Writes `text` to an arbitrary logical name, such as `werror` or a name
    /// a registered router claims.
    pub fn write_to(&self, logical_name: &str, text: &str) -> Result<()> {
        let logical_name = CString::new(logical_name)?;
        let text = CString::new(text)?;
        unsafe { ffi::WriteString(self.raw.as_ptr(), logical_name.as_ptr(), text.as_ptr()) };
        Ok(())
    }

    /// Defines one construct from CLIPS source text, for example
    /// `"(deftemplate person (slot name))"`.
    ///
    /// CLIPS's own diagnostics go to the `werror` logical name; register a
    /// [`Router`] for it to capture them.
    pub fn build(&mut self, construct: &str) -> Result<()> {
        let construct = CString::new(construct)?;
        match unsafe { ffi::Build(self.raw.as_ptr(), construct.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::Build(BuildError::from(code))),
        }
    }

    /// Loads constructs from a file.
    pub fn load(&mut self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        match unsafe { ffi::Load(self.raw.as_ptr(), path.as_ptr()) } {
            0 => Ok(()),
            code => Err(Error::Load(LoadError::from(code))),
        }
    }
    /// Loads constructs from CLIPS source text.
    ///
    /// CLIPS reports only success or failure here, with no error detail, so a
    /// failure is always [`LoadError::Parsing`]. Install a parser-error hook
    /// with [`Environment::set_parser_error_hook`] for the diagnostics.
    pub fn load_str(&mut self, source: &str) -> Result<()> {
        let source = CString::new(source)?;
        if unsafe {
            ffi::LoadFromString(self.raw.as_ptr(), source.as_ptr(), source.as_bytes().len())
        } {
            Ok(())
        } else {
            Err(Error::Load(LoadError::Parsing))
        }
    }
    /// Evaluates a CLIPS expression and returns its retained result.
    ///
    /// This takes `&mut self` because an expression can assert, retract, or
    /// redefine anything, which would invalidate outstanding handles.
    pub fn eval(&mut self, expression: &str) -> Result<Value<'_>> {
        let expression = CString::new(expression)?;
        let mut raw = ffi::CLIPSValue {
            value: std::ptr::null_mut(),
        };
        match unsafe { ffi::Eval(self.raw.as_ptr(), expression.as_ptr(), &mut raw) } {
            0 => {
                unsafe { ffi::RetainCV(self.raw.as_ptr(), &mut raw) };
                Ok(Value::new(self, raw))
            }
            code => Err(Error::Evaluation(EvaluationError::from(code))),
        }
    }
    /// True when `other` wraps the same CLIPS environment as `self`.
    ///
    /// Handles carry the environment they came from, so this is what the
    /// generic value-accepting APIs use to refuse cross-environment values.
    pub(crate) fn is_same(&self, other: &Environment) -> bool {
        self.raw == other.raw
    }
    /// Returns the raw form of `value` after confirming it belongs to this
    /// environment.
    pub(crate) fn check_value(&self, value: &Value<'_>) -> Result<ffi::CLIPSValue> {
        if self.is_same(value.environment()) {
            Ok(value.raw())
        } else {
            Err(Error::ForeignEnvironment)
        }
    }
    /// Creates a retained CLIPS integer.
    pub fn create_integer(&self, value: i64) -> Value<'_> {
        Value::retaining(
            self,
            ffi::CLIPSValue {
                integer: unsafe { ffi::CreateInteger(self.raw.as_ptr(), value) },
            },
        )
    }
    /// Creates a retained CLIPS float.
    pub fn create_float(&self, value: f64) -> Value<'_> {
        Value::retaining(
            self,
            ffi::CLIPSValue {
                float: unsafe { ffi::CreateFloat(self.raw.as_ptr(), value) },
            },
        )
    }
    /// Creates the retained CLIPS `TRUE` or `FALSE` symbol.
    pub fn create_boolean(&self, value: bool) -> Value<'_> {
        Value::retaining(
            self,
            ffi::CLIPSValue {
                lexeme: unsafe { ffi::CreateBoolean(self.raw.as_ptr(), value) },
            },
        )
    }
    /// Creates a retained CLIPS symbol.
    pub fn create_symbol(&self, value: &str) -> Result<Value<'_>> {
        self.create_lexeme(value, ffi::CreateSymbol)
    }
    /// Creates a retained CLIPS string.
    pub fn create_string(&self, value: &str) -> Result<Value<'_>> {
        self.create_lexeme(value, ffi::CreateString)
    }
    /// Creates a retained CLIPS instance name.
    pub fn create_instance_name(&self, value: &str) -> Result<Value<'_>> {
        self.create_lexeme(value, ffi::CreateInstanceName)
    }
    fn create_lexeme(
        &self,
        value: &str,
        create: unsafe extern "C" fn(
            *mut ffi::Environment,
            *const std::ffi::c_char,
        ) -> *mut ffi::CLIPSLexeme,
    ) -> Result<Value<'_>> {
        let value = CString::new(value)?;
        Ok(Value::retaining(
            self,
            ffi::CLIPSValue {
                lexeme: unsafe { create(self.raw.as_ptr(), value.as_ptr()) },
            },
        ))
    }
    /// Parses `source` as a sequence of CLIPS fields and returns them as a
    /// retained multifield.
    pub fn string_to_multifield(&self, source: &str) -> Result<Multifield<'_>> {
        let source = CString::new(source)?;
        let raw = unsafe { ffi::StringToMultifield(self.raw.as_ptr(), source.as_ptr()) };
        if raw.is_null() {
            return Err(Error::Evaluation(EvaluationError::Parsing));
        }
        Ok(Multifield::from_value(Value::retaining(
            self,
            ffi::CLIPSValue { multifield: raw },
        )))
    }
    /// Asserts a fact from CLIPS text, for example `"(person (name ada))"`.
    ///
    /// Use [`Environment::fact_builder`] to avoid formatting and re-parsing
    /// slot values.
    pub fn assert_string(&self, source: &str) -> Result<Fact<'_>> {
        let source = CString::new(source)?;
        let raw = unsafe { ffi::AssertString(self.raw.as_ptr(), source.as_ptr()) };
        Fact::from_result(self, raw, unsafe {
            ffi::GetAssertStringError(self.raw.as_ptr())
        })
    }
    // Builders take a shared borrow: several may exist at once, and values
    // created from the same environment stay usable while they live. The shared
    // borrow still blocks `clear`, `reset`, `run`, and every other `&mut self`
    // operation that could invalidate what a builder is about to produce.
    /// Starts building a fact of the named deftemplate.
    pub fn fact_builder(&self, template: &str) -> Result<FactBuilder<'_>> {
        FactBuilder::new(self, template)
    }

    /// Iterates every fact in index order.
    pub fn facts(&self) -> Facts<'_> {
        Facts::new(self)
    }

    /// The number of facts currently asserted.
    pub fn fact_count(&self) -> usize {
        unsafe { ffi::GetNumberOfFacts(self.raw.as_ptr()) as usize }
    }

    /// Starts building an instance of the named defclass.
    pub fn instance_builder(&self, class: &str) -> Result<InstanceBuilder<'_>> {
        InstanceBuilder::new(self, class)
    }

    /// Iterates every instance in every module.
    pub fn instances(&self) -> Instances<'_> {
        Instances::new(self)
    }

    /// Starts building a multifield. `capacity` is a hint; the builder grows
    /// as needed.
    pub fn multifield_builder(&self, capacity: usize) -> Result<MultifieldBuilder<'_>> {
        MultifieldBuilder::new(self, capacity)
    }

    /// Starts building a call to a CLIPS function. `capacity` is a hint for
    /// the number of arguments.
    pub fn function_call(&self, capacity: usize) -> Result<FunctionCall<'_>> {
        FunctionCall::new(self, capacity)
    }
    /// Registers a router, which is how Rust captures CLIPS output and
    /// supplies its input.
    ///
    /// Higher `priority` wins when several routers claim the same logical
    /// name; CLIPS's own console routers sit at priority 0 to 30. The router
    /// is owned by the environment and dropped when removed or when the
    /// environment is.
    pub fn register_router<R: Router>(
        &mut self,
        name: &str,
        priority: i32,
        router: R,
    ) -> std::result::Result<(), RouterError> {
        let entry = RouterEntry::register(self.raw, name, priority, router)?;
        self.routers.push(entry);
        Ok(())
    }
    /// Unregisters a router and drops it.
    ///
    /// If CLIPS refuses the removal the router is kept, so the registration
    /// and the owned callback never disagree.
    pub fn remove_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
        let position = self
            .routers
            .iter()
            .position(|entry| entry.name().to_bytes() == name.as_bytes())
            .ok_or(RouterError::NotFound)?;
        let entry = self.routers.remove(position);
        match entry.unregister(self.raw) {
            Ok(()) => Ok(()),
            Err((entry, error)) => {
                self.routers.insert(position, entry);
                Err(error)
            }
        }
    }
    /// Re-enables a deactivated router.
    pub fn activate_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
        self.router_entry(name)?.activate(self.raw)
    }

    /// Stops CLIPS dispatching to a router without unregistering it.
    pub fn deactivate_router(&mut self, name: &str) -> std::result::Result<(), RouterError> {
        self.router_entry(name)?.deactivate(self.raw)
    }
    fn router_entry(&self, name: &str) -> std::result::Result<&RouterEntry, RouterError> {
        self.routers
            .iter()
            .find(|entry| entry.name().to_bytes() == name.as_bytes())
            .ok_or(RouterError::NotFound)
    }
    /// Registers a Rust function callable from CLIPS code under `name`.
    ///
    /// The callback is owned by the environment. It runs inside CLIPS, so a
    /// panic is caught at the boundary rather than unwinding through C, and
    /// re-entering the same function is refused instead of aliasing its state;
    /// both become a [`UdfCallbackError`] retrievable with
    /// [`Environment::take_udf_error`].
    ///
    /// The callback is `'static` but its arguments are borrowed for the call
    /// only, so fact, instance, and external addresses can be passed back as
    /// results but cannot be stored.
    pub fn add_udf<F>(
        &mut self,
        name: &str,
        signature: UdfSignature,
        callback: F,
    ) -> std::result::Result<(), UdfRegistrationError>
    where
        F: for<'call> FnMut(
                &[UdfValue<'call>],
            ) -> std::result::Result<UdfReturn<'call>, UdfCallbackError>
            + 'static,
    {
        let name = CString::new(name).map_err(UdfRegistrationError::from)?;
        let mut registration = UdfRegistration::new(name, signature, callback);
        let context = registration.context();
        let argument_types = registration
            .signature
            .arguments
            .as_ref()
            .map_or(std::ptr::null(), |value| value.as_ptr());
        let code = unsafe {
            ffi::AddUDF(
                self.raw.as_ptr(),
                registration.name.as_ptr(),
                registration.signature.returns.as_ptr(),
                registration.signature.min_args,
                registration.signature.max_args,
                argument_types,
                Some(crate::udf::trampoline),
                registration.name.as_ptr(),
                context,
            )
        };
        if code != 0 {
            return Err(UdfRegistrationError::from_code(code));
        }
        self.udfs.push(registration);
        Ok(())
    }
    /// Unregisters a user-defined function and drops its callback.
    pub fn remove_udf(&mut self, name: &str) -> std::result::Result<(), UdfRegistrationError> {
        let position = self
            .udfs
            .iter()
            .position(|entry| entry.name.to_bytes() == name.as_bytes())
            .ok_or(UdfRegistrationError::NotFound)?;
        if unsafe { ffi::RemoveUDF(self.raw.as_ptr(), self.udfs[position].name.as_ptr()) } {
            self.udfs.remove(position);
            Ok(())
        } else {
            Err(UdfRegistrationError::NotFound)
        }
    }
    /// Takes the error a user-defined function last reported, clearing it.
    ///
    /// CLIPS only learns that a UDF failed, not why, so the reason is kept
    /// here and retrieved by name after the call that triggered it.
    pub fn take_udf_error(&self, name: &str) -> Option<UdfCallbackError> {
        self.udfs
            .iter()
            .find(|entry| entry.name.to_bytes() == name.as_bytes())
            .and_then(|entry| entry.take_error())
    }
    /// Registers a lifecycle callback, run when CLIPS reaches the given point.
    ///
    /// Lower `priority` runs earlier. Names must be unique: CLIPS would accept
    /// a duplicate but could not then remove it reliably, so one is refused.
    /// Not every kind can be unregistered before the environment is dropped;
    /// see [`HookKind::is_removable`].
    pub fn add_hook<F>(
        &mut self,
        name: &str,
        kind: HookKind,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut() + 'static,
    {
        self.reject_duplicate_hook(name)?;
        let entry = HookEntry::void(self.raw.as_ptr(), name, kind, priority, callback)?;
        self.hooks.push(entry);
        Ok(())
    }
    /// Registers a veto hook. Returning `false` from `callback` refuses the
    /// operation.
    pub fn add_veto_hook<F>(
        &mut self,
        name: &str,
        kind: ReadyHookKind,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut() -> bool + 'static,
    {
        self.reject_duplicate_hook(name)?;
        let entry = HookEntry::ready(self.raw.as_ptr(), name, kind, priority, callback)?;
        self.hooks.push(entry);
        Ok(())
    }
    /// Registers a veto hook for [`Environment::clear`], which fails with
    /// [`Error::ClearRejected`] if the callback returns `false`.
    ///
    /// Shorthand for [`Environment::add_veto_hook`] with
    /// [`ReadyHookKind::Clear`].
    pub fn add_clear_ready_hook<F>(
        &mut self,
        name: &str,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut() -> bool + 'static,
    {
        self.add_veto_hook(name, ReadyHookKind::Clear, priority, callback)
    }
    /// Registers a hook called with the rule name each time a rule fires.
    pub fn add_rule_fire_hook<F>(
        &mut self,
        name: &str,
        phase: RuleFirePhase,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut(&str) + 'static,
    {
        self.reject_duplicate_hook(name)?;
        let entry = HookEntry::rule_fired(self.raw.as_ptr(), name, phase, priority, callback)?;
        self.hooks.push(entry);
        Ok(())
    }
    /// Registers a hook called when a fact is asserted, retracted, or modified.
    ///
    /// The callback receives a [`FactChange`] describing what happened. A
    /// modification arrives as two calls, one for the replaced fact and one for
    /// its replacement, matching how CLIPS reports it.
    pub fn add_fact_hook<F>(
        &mut self,
        name: &str,
        kind: FactEventKind,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut(&FactChange) + 'static,
    {
        self.reject_duplicate_hook(name)?;
        let entry = HookEntry::fact(self.raw.as_ptr(), name, kind, priority, callback)?;
        self.hooks.push(entry);
        Ok(())
    }
    /// Registers a hook called for each module while constructs are saved.
    ///
    /// The callback receives the module name and the logical name being written
    /// to, which is a router name rather than a file path.
    pub fn add_save_hook<F>(
        &mut self,
        name: &str,
        priority: i32,
        callback: F,
    ) -> std::result::Result<(), HookError>
    where
        F: FnMut(&str, &str) + 'static,
    {
        self.reject_duplicate_hook(name)?;
        let entry = HookEntry::save(self.raw.as_ptr(), name, priority, callback)?;
        self.hooks.push(entry);
        Ok(())
    }
    /// Installs the parser-error callback, replacing any previous one.
    ///
    /// CLIPS keeps exactly one such callback per environment, so this is a
    /// single slot rather than a named registry.
    ///
    /// CLIPS installs its error-capture router only on the load path, so
    /// diagnostics are reported for [`Environment::load`] and
    /// [`Environment::load_str`], not for [`Environment::build`]. Install the
    /// callback before the parsing you want it to observe.
    pub fn set_parser_error_hook<F>(&mut self, callback: F)
    where
        F: FnMut(&ParserDiagnostic) + 'static,
    {
        // The previous context stays alive until CLIPS has been pointed at the
        // new one.
        let context = ParserErrorContext::install(self.raw.as_ptr(), callback);
        self.parser_error = Some(context);
    }
    /// Removes the parser-error callback, if one is installed.
    pub fn clear_parser_error_hook(&mut self) {
        ParserErrorContext::clear(self.raw.as_ptr());
        self.parser_error = None;
    }
    /// Refuses a name already used by one of this environment's hooks.
    ///
    /// Several CLIPS hook lists accept duplicate names without complaint, which
    /// would leave a registration that `remove_hook` could not fully undo.
    fn reject_duplicate_hook(&self, name: &str) -> std::result::Result<(), HookError> {
        if self
            .hooks
            .iter()
            .any(|entry| entry.name() == name.as_bytes())
        {
            return Err(HookError::NameInUse);
        }
        Ok(())
    }
    /// Unregisters a hook and drops its callback.
    ///
    /// Some CLIPS hook lists have no removal entry point; a hook of such a kind
    /// stays registered until the environment is destroyed. See
    /// [`HookKind::is_removable`].
    pub fn remove_hook(&mut self, name: &str) -> std::result::Result<(), HookError> {
        let position = self
            .hooks
            .iter()
            .position(|entry| entry.name() == name.as_bytes())
            .ok_or(HookError::NotFound)?;
        if self.hooks[position].unregister(self.raw.as_ptr()) {
            self.hooks.remove(position);
            Ok(())
        } else {
            Err(HookError::NotFound)
        }
    }
}

impl Default for Environment {
    fn default() -> Self {
        Self::new().expect("CLIPS environment creation failed")
    }
}
impl Drop for Environment {
    fn drop(&mut self) {
        // CLIPS must stop pointing at the parser-error context before it is
        // dropped.
        if self.parser_error.is_some() {
            ParserErrorContext::clear(self.raw.as_ptr());
        }
        let parser_error = self.parser_error.take();

        let mut hooks = std::mem::take(&mut self.hooks);
        hooks.retain(|entry| !entry.unregister(self.raw.as_ptr()));

        let mut udfs = std::mem::take(&mut self.udfs);
        udfs.retain(|registration| unsafe {
            !ffi::RemoveUDF(self.raw.as_ptr(), registration.name.as_ptr())
        });

        let mut routers = Vec::new();
        for entry in std::mem::take(&mut self.routers) {
            if let Err((entry, _)) = entry.unregister(self.raw) {
                routers.push(entry);
            }
        }

        if !unsafe { ffi::DestroyEnvironment(self.raw.as_ptr()) } {
            // CLIPS may still hold these callback pointers if both removal and
            // destruction failed. Leaking is the only safe fallback.
            std::mem::forget(hooks);
            std::mem::forget(udfs);
            std::mem::forget(routers);
            std::mem::forget(parser_error);
        }
    }
}