Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-plan/src/machine.rs

//! A state machine from a graph with labels ([`Plan::state_machine`]): the subset
//! construction as rules of the plan. The helper only adds relations and rules (set numbers
//! into a table of sets, in a group of rounds); the engine runs them as any rules, so
//! every row keeps its proof.

use crate::rules::{Aggregate, Atom, Literal, Part, Plan, RelId, Term, Var};
use crate::typed::Type;
use crate::{PlanError, Result};

/// The plain tables a state machine is made from ([`Plan::state_machine`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MachineGraph {
    /// The edges with a label: `edge(from, label, to)`.
    pub edge: RelId,
    /// The edges without a label: `eps(from, to)`; `None`: there are none.
    pub eps: Option<RelId>,
    /// The start nodes by key: `start(key, node)`; the nodes of one key make one start set.
    pub start: RelId,
}

/// The relations of a state machine ([`Plan::state_machine`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Machine {
    /// The table of sets `member(state, node)`: each state's nodes.
    pub member: RelId,
    /// `step(state, label, next)`: the state a label leads to.
    pub step: RelId,
    /// `start(key, state)`: the state of each start key.
    pub start: RelId,
    /// `state(state)`: each state once.
    pub state: RelId,
}

impl Plan {
    /// The state machine of a graph with labels (the subset construction), as relations and
    /// rules added to this plan, named `{name}.member`, `{name}.step`, `{name}.start`,
    /// `{name}.state` and `{name}.closure`:
    ///
    /// ```text
    /// sets member/2.
    /// closure(X, X) :- start_in(_, X).
    /// closure(Z, Z) :- edge(_, _, Z).
    /// closure(X, Z) :- closure(X, Y), eps(Y, Z).
    /// start(K, N)   :- N = set (X) by (K) in member: start_in(K, S), closure(S, X).
    /// step(P, A, N) :- N = set (Y) by (P, A) in member: member(P, X), edge(X, A, Z), closure(Z, Y).
    /// state(N)      :- member(N, X).
    /// rounds start: keep, step: keep, member: keep.
    /// ```
    ///
    /// A state is a set of nodes closed under `eps`; its number comes from the table of
    /// sets ([`Plan::sets`], `limit` sets at most: over it the run stops with
    /// [`PlanError::SetLimit`] naming `{name}.member`), the start sets first, then the
    /// states one step further, and so on, each such level's new sets in rising order of
    /// their sorted nodes: the same graph gives the same numbers on every run. Equal start
    /// sets share a state. The graph's relations may be of any kind (inputs, externals, or
    /// derived by the caller's own rules). In a typed plan the nodes are of the type of
    /// `edge`'s column 0, which `edge`'s column 2, both columns of `eps` and `start`'s
    /// column 1 must have; labels and keys may be of any type. Refused, by the relation and
    /// column: a relation not in the plan or of the wrong width, a node column of another
    /// type; nothing is added then.
    ///
    /// ```
    /// use kleene_plan::{MachineGraph, Plan};
    /// let mut p = Plan::new();
    /// let edge = p.input("edge", 3);
    /// let eps = p.input("eps", 2);
    /// let start = p.input("start", 2);
    /// let m = p
    ///     .state_machine("nfa", MachineGraph { edge, eps: Some(eps), start }, None)
    ///     .unwrap();
    /// assert_eq!(p.relation_info(m.step).name, "nfa.step");
    /// assert_eq!(p.set_limit(m.member), Some(kleene_plan::DEFAULT_SET_LIMIT));
    /// ```
    pub fn state_machine(
        &mut self,
        name: &str,
        graph: MachineGraph,
        limit: Option<u64>,
    ) -> Result<Machine> {
        let MachineGraph { edge, eps, start } = graph;
        let refuse = |m: String| Err(PlanError::Program(format!("state machine `{name}`: {m}")));
        let rels = [(edge, "edge", 3), (start, "start", 2)]
            .into_iter()
            .chain(eps.map(|e| (e, "eps", 2)));
        for (r, what, width) in rels.clone() {
            let Some(info) = self.relations().get(r.index()) else {
                return refuse(format!(
                    "its {what} relation {} is not in this plan",
                    r.index()
                ));
            };
            if info.arity != width {
                return refuse(format!(
                    "its {what} relation `{}` has {} columns, not {width}",
                    info.name, info.arity
                ));
            }
        }
        let node = self.col_type(edge, 0);
        let mut nodes = vec![(edge, 2), (start, 1)];
        if let Some(e) = eps {
            nodes.extend([(e, 0), (e, 1)]);
        }
        for (r, c) in nodes {
            let ty = self.col_type(r, c);
            if ty != node {
                return refuse(format!(
                    "column {c} of `{}` is a {ty}; the nodes (column 0 of `{}`) are {node}",
                    self.relation_info(r).name,
                    self.relation_info(edge).name
                ));
            }
        }
        let typed = rels.clone().any(|(r, _, _)| self.is_typed(r));
        let (label, key) = (self.col_type(edge, 1), self.col_type(start, 0));
        let n = format!("{name}.");
        let u = Type::U64;
        let (closure, member, step, out, state) = if typed {
            (
                self.derived_typed(&format!("{n}closure"), &[node, node]),
                self.sets_typed(&format!("{n}member"), &[u, node], limit),
                self.derived_typed(&format!("{n}step"), &[u, label, u]),
                self.derived_typed(&format!("{n}start"), &[key, u]),
                self.derived_typed(&format!("{n}state"), &[u]),
            )
        } else {
            (
                self.derived(&format!("{n}closure"), 2),
                self.sets(&format!("{n}member"), 2, limit),
                self.derived(&format!("{n}step"), 3),
                self.derived(&format!("{n}start"), 2),
                self.derived(&format!("{n}state"), 1),
            )
        };
        let at = |rel: RelId, vs: &[Var]| Atom {
            rel,
            terms: vs.iter().map(|&v| Term::Var(v)).collect(),
        };
        let pos = |rel: RelId, vs: &[Var]| Literal::Pos(at(rel, vs));
        let [k, s, x, y, z, p, a, nn, w, v] =
            ["K", "S", "X", "Y", "Z", "P", "A", "N", "W", "V"].map(|x| self.var(x));
        self.rule(at(closure, &[x, x]), [pos(start, &[w, x])])?;
        self.rule(at(closure, &[z, z]), [pos(edge, &[w, v, z])])?;
        if let Some(e) = eps {
            self.rule(
                at(closure, &[x, z]),
                [pos(closure, &[x, y]), pos(e, &[y, z])],
            )?;
        }
        self.aggregate(
            at(out, &[k, nn]),
            Aggregate::set_number([k], [x], nn, member),
            [pos(start, &[k, s]), pos(closure, &[s, x])],
        )?;
        self.aggregate(
            at(step, &[p, a, nn]),
            Aggregate::set_number([p, a], [y], nn, member),
            [
                pos(member, &[p, x]),
                pos(edge, &[x, a, z]),
                pos(closure, &[z, y]),
            ],
        )?;
        self.rule(at(state, &[nn]), [pos(member, &[nn, x])])?;
        self.rounds([(out, Part::Keep), (step, Part::Keep), (member, Part::Keep)])?;
        Ok(Machine {
            member,
            step,
            start: out,
            state,
        })
    }
}