Skip to main content

clips_bindings/
agenda.rs

1//! Agenda inspection and control.
2//!
3//! Activations borrow the environment, so the agenda cannot be reordered or
4//! emptied while one is held.
5
6use std::ffi::CStr;
7use std::marker::PhantomData;
8use std::ptr::NonNull;
9
10use crate::{Environment, ModuleError, ffi};
11
12/// When CLIPS evaluates a rule's salience expression.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[repr(u32)]
15pub enum SalienceEvaluation {
16    /// Once, when the rule is defined.
17    WhenDefined = 0,
18    /// Each time the rule is activated.
19    WhenActivated = 1,
20    /// Before every rule firing, re-sorting the agenda each cycle.
21    EveryCycle = 2,
22}
23
24/// How CLIPS orders activations of equal salience on the agenda.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[repr(u32)]
27pub enum Strategy {
28    /// Newest activation first.
29    Depth = 0,
30    /// Oldest activation first.
31    Breadth = 1,
32    /// Ordered by the recency of the matched facts, as in OPS5 `lex`.
33    Lex = 2,
34    /// Like `Lex`, but dominated by the first pattern's recency.
35    Mea = 3,
36    /// Most specific rule, by number of comparisons, first.
37    Complexity = 4,
38    /// Least specific rule first.
39    Simplicity = 5,
40    /// Arbitrary but stable order.
41    Random = 6,
42}
43
44/// A rule activation on the agenda.
45pub struct Activation<'env> {
46    raw: NonNull<ffi::Activation>,
47    environment: &'env Environment,
48}
49impl Activation<'_> {
50    /// The name of the rule this activation would fire.
51    pub fn rule_name(&self) -> &str {
52        unsafe { CStr::from_ptr(ffi::ActivationRuleName(self.raw.as_ptr())) }
53            .to_str()
54            .unwrap_or("")
55    }
56
57    /// The activation's salience, which decides its place on the agenda.
58    pub fn salience(&self) -> i32 {
59        unsafe { ffi::ActivationGetSalience(self.raw.as_ptr()) }
60    }
61
62    /// Sets this activation's salience and returns the previous value.
63    ///
64    /// The value is clamped to CLIPS's range of -10000 to 10000. The agenda is
65    /// not re-sorted until [`Environment::reorder_agendas`] runs.
66    pub fn set_salience(&mut self, salience: i32) -> i32 {
67        unsafe { ffi::ActivationSetSalience(self.raw.as_ptr(), salience.clamp(-10_000, 10_000)) }
68    }
69
70    /// Moves this activation to the top of its salience group, so it fires
71    /// next. Returns whether CLIPS moved it.
72    pub fn move_to_top(&mut self) -> bool {
73        unsafe { ffi::MoveActivationToTop(self.environment.raw.as_ptr(), self.raw.as_ptr()) }
74    }
75
76    /// The activation rendered as CLIPS prints it on the agenda, with its
77    /// salience, rule name, and matched facts.
78    pub fn pretty_print(&self) -> String {
79        unsafe {
80            let builder = ffi::CreateStringBuilder(self.environment.raw.as_ptr(), 128);
81            if builder.is_null() {
82                return String::new();
83            }
84            ffi::ActivationPPForm(self.raw.as_ptr(), builder);
85            let output = CStr::from_ptr((*builder).contents)
86                .to_string_lossy()
87                .into_owned();
88            ffi::SBDispose(builder);
89            output
90        }
91    }
92    /// Removes this activation from the agenda so it never fires.
93    ///
94    /// Consumes the handle, since CLIPS frees the activation.
95    pub fn delete(self) {
96        unsafe { ffi::DeleteActivation(self.raw.as_ptr()) }
97    }
98}
99
100/// Iterates the agenda of the module in focus, highest priority first.
101pub struct Activations<'env> {
102    environment: &'env Environment,
103    current: *mut ffi::Activation,
104    marker: PhantomData<&'env Environment>,
105}
106impl<'env> Iterator for Activations<'env> {
107    type Item = Activation<'env>;
108    fn next(&mut self) -> Option<Self::Item> {
109        self.current =
110            unsafe { ffi::GetNextActivation(self.environment.raw.as_ptr(), self.current) };
111        NonNull::new(self.current).map(|raw| Activation {
112            raw,
113            environment: self.environment,
114        })
115    }
116}
117
118impl Environment {
119    /// Iterates the agenda in firing order.
120    pub fn activations(&self) -> Activations<'_> {
121        Activations {
122            environment: self,
123            current: std::ptr::null_mut(),
124            marker: PhantomData,
125        }
126    }
127
128    /// The number of activations on the agenda.
129    pub fn activation_count(&self) -> usize {
130        unsafe { ffi::GetNumberOfActivations(self.raw.as_ptr()) as usize }
131    }
132
133    /// The current conflict-resolution strategy.
134    pub fn strategy(&self) -> Strategy {
135        match unsafe { ffi::GetStrategy(self.raw.as_ptr()) } {
136            0 => Strategy::Depth,
137            1 => Strategy::Breadth,
138            2 => Strategy::Lex,
139            3 => Strategy::Mea,
140            4 => Strategy::Complexity,
141            5 => Strategy::Simplicity,
142            _ => Strategy::Random,
143        }
144    }
145    /// Sets the conflict-resolution strategy and returns the previous one.
146    ///
147    /// CLIPS reorders every agenda to match.
148    pub fn set_strategy(&mut self, strategy: Strategy) -> Strategy {
149        let previous = unsafe { ffi::SetStrategy(self.raw.as_ptr(), strategy as u32) };
150        match previous {
151            0 => Strategy::Depth,
152            1 => Strategy::Breadth,
153            2 => Strategy::Lex,
154            3 => Strategy::Mea,
155            4 => Strategy::Complexity,
156            5 => Strategy::Simplicity,
157            _ => Strategy::Random,
158        }
159    }
160    /// When rule saliences are evaluated.
161    pub fn salience_evaluation(&self) -> SalienceEvaluation {
162        match unsafe { ffi::GetSalienceEvaluation(self.raw.as_ptr()) } {
163            0 => SalienceEvaluation::WhenDefined,
164            1 => SalienceEvaluation::WhenActivated,
165            _ => SalienceEvaluation::EveryCycle,
166        }
167    }
168    /// Sets when saliences are evaluated and returns the previous setting.
169    pub fn set_salience_evaluation(&mut self, value: SalienceEvaluation) -> SalienceEvaluation {
170        match unsafe { ffi::SetSalienceEvaluation(self.raw.as_ptr(), value as u32) } {
171            0 => SalienceEvaluation::WhenDefined,
172            1 => SalienceEvaluation::WhenActivated,
173            _ => SalienceEvaluation::EveryCycle,
174        }
175    }
176    /// Re-adds every module's satisfied matches to its agenda, so matches that
177    /// already fired can fire again.
178    pub fn refresh_agendas(&mut self) {
179        unsafe { ffi::RefreshAllAgendas(self.raw.as_ptr()) }
180    }
181
182    /// Re-sorts every agenda, which is needed after changing saliences.
183    pub fn reorder_agendas(&mut self) {
184        unsafe { ffi::ReorderAllAgendas(self.raw.as_ptr()) }
185    }
186    /// Removes every activation from every agenda.
187    pub fn remove_all_activations(&mut self) {
188        unsafe { ffi::RemoveAllActivations(self.raw.as_ptr()) }
189    }
190    /// Whether the agenda changed since this flag was last cleared.
191    pub fn agenda_changed(&self) -> bool {
192        unsafe { ffi::GetAgendaChanged(self.raw.as_ptr()) }
193    }
194    /// Sets or clears the agenda-changed flag.
195    pub fn set_agenda_changed(&self, changed: bool) {
196        unsafe { ffi::SetAgendaChanged(self.raw.as_ptr(), changed) }
197    }
198    /// Refreshes one module's agenda instead of every module's.
199    ///
200    /// Named rather than handle-based so a module from another environment can
201    /// never be passed to CLIPS.
202    pub fn refresh_module_agenda(&mut self, module: &str) -> std::result::Result<(), ModuleError> {
203        self.with_module(module, |module| unsafe { ffi::RefreshAgenda(module) })
204    }
205    /// Reorders one module's agenda instead of every module's.
206    pub fn reorder_module_agenda(&mut self, module: &str) -> std::result::Result<(), ModuleError> {
207        self.with_module(module, |module| unsafe { ffi::ReorderAgenda(module) })
208    }
209    fn with_module(
210        &mut self,
211        name: &str,
212        operation: impl FnOnce(*mut ffi::Defmodule),
213    ) -> std::result::Result<(), ModuleError> {
214        let c_name = std::ffi::CString::new(name).map_err(|_| ModuleError::InteriorNul)?;
215        let module = unsafe { ffi::FindDefmodule(self.raw.as_ptr(), c_name.as_ptr()) };
216        if module.is_null() {
217            return Err(ModuleError::NotFound(name.to_owned()));
218        }
219        operation(module);
220        Ok(())
221    }
222    /// Empties the focus stack, so a run fires nothing until a module is
223    /// focused again.
224    pub fn clear_focus_stack(&mut self) {
225        unsafe { ffi::ClearFocusStack(self.raw.as_ptr()) }
226    }
227}