Skip to main content

rstm_core/rules/
rule.rs

1/*
2    Appellation: rule <module>
3    Created At: 2025.08.30:01:04:10
4    Contrib: @FL03
5*/
6use crate::{Direction, Head, Tail};
7use rstm_state::{RawState, State};
8
9/// The [`Rule`] implementation is a concrete representation of a single instruction, or rule,
10/// within a given Turing machine program. It encapsulates the necessary components to define
11/// the behavior of the Turing machine when it encounters a specific state and symbol.
12///
13/// **Note**: The inner fields are flattened for serialization purposes when using `serde`;
14/// this means that the fields of the [`Head`] and [`Tail`] structs will be serialized as if they
15/// were direct fields of the `Rule` struct itself.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Ord, PartialOrd)]
17#[cfg_attr(
18    feature = "serde",
19    derive(serde::Deserialize, serde::Serialize),
20    serde(rename_all = "snake_case")
21)]
22#[repr(C)]
23pub struct Rule<Q1 = String, A = char, Q2 = Q1, B = A>
24where
25    Q1: RawState,
26    Q2: RawState,
27{
28    #[cfg_attr(feature = "serde", serde(flatten))]
29    pub head: Head<Q1, A>,
30    #[cfg_attr(feature = "serde", serde(flatten))]
31    pub tail: Tail<Q2, B>,
32}
33
34/// A [`LearnedRule`] is an extension of the basic [`Rule`] structure, incorporating a
35/// confidence metric to quantify the reliability or certainty of the rule within the scope of
36/// a learning context. This is particularly useful in scenarios where rules are derived from
37/// data or experience, allowing for a more nuanced application of rules based on their
38/// confidence levels.
39#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
40#[cfg_attr(
41    feature = "serde",
42    derive(serde::Deserialize, serde::Serialize),
43    serde(rename_all = "snake_case")
44)]
45#[repr(C)]
46pub struct LearnedRule<C = f32, Q = usize, S = usize>
47where
48    Q: RawState,
49{
50    pub confidence: C,
51    #[cfg_attr(feature = "serde", serde(flatten))]
52    pub rule: Rule<Q, S>,
53}
54
55/// [`RuleBuilder`] is a utilitarian structure designed to facilitate the construction of
56/// new [`Rule`] instances through a step-by-step approach. This builder pattern allows for
57/// incremental specification of rule components, enhancing code readability and
58/// maintainability.
59#[derive(Default)]
60pub struct RuleBuilder<Q1, A, Q2, B>
61where
62    Q1: RawState,
63    Q2: RawState,
64{
65    pub(crate) direction: Direction,
66    pub(crate) state: Option<State<Q1>>,
67    pub(crate) symbol: Option<A>,
68    pub(crate) next_state: Option<State<Q2>>,
69    pub(crate) write_symbol: Option<B>,
70}
71
72#[cfg(test)]
73mod tests {}