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

nordisk/kleene

crates/kleene-datalog/src/program.rs

use std::marker::PhantomData;
use std::ops::Deref;

use kleene_plan::{
    Aggregate, Atom, Catalog, Cmp, Compute, Cond, Constant, Expr, Fold, ListId, ListMember,
    Literal, Part, Plan, Procedure, RelId, RuleId, Stratum, Term, Test, TextOp, Type, Var,
};

use crate::Result;

/// A relation of `N` columns: its arity is part of its type, so an atom with the wrong
/// number of terms does not compile.
#[derive(Debug)]
pub struct Rel<const N: usize> {
    id: RelId,
    _n: PhantomData<[(); N]>,
}

impl<const N: usize> Clone for Rel<N> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<const N: usize> Copy for Rel<N> {}

impl<const N: usize> Rel<N> {
    fn new(id: RelId) -> Self {
        Rel {
            id,
            _n: PhantomData,
        }
    }

    /// The relation's number.
    pub fn id(&self) -> RelId {
        self.id
    }

    /// An atom of this relation: `rel(t1, ..., tN)`.
    pub fn at<T: Into<Term> + Copy>(&self, terms: [T; N]) -> Atom {
        Atom {
            rel: self.id,
            terms: terms.iter().map(|&t| t.into()).collect(),
        }
    }

    /// An atom with mixed terms.
    pub fn atom(&self, terms: [Term; N]) -> Atom {
        Atom {
            rel: self.id,
            terms: terms.to_vec(),
        }
    }
}

/// A Datalog program built in Rust: relations with typed arity, variables, rules. It is
/// lowered onto a [`kleene_plan::Plan`] as it is built (each relation and rule added to the
/// plan); reading it reads the plan (`Deref`).
///
/// ```
/// use kleene_datalog::Program;
/// let mut p = Program::new();
/// let entry = p.input::<1>("entry");
/// let calls = p.input::<2>("calls");
/// let reach = p.derived::<1>("reach");
/// let (f, g) = (p.var("F"), p.var("G"));
/// p.rule(reach.at([f]), [entry.at([f])]).unwrap();
/// p.rule(reach.at([g]), [reach.at([f]), calls.at([f, g])]).unwrap();
/// assert_eq!(p.rules().len(), 2);
/// ```
#[derive(Clone, Debug, Default)]
pub struct Program {
    plan: Plan,
}

impl Deref for Program {
    type Target = Plan;
    fn deref(&self) -> &Plan {
        &self.plan
    }
}

impl Program {
    /// An empty program.
    pub fn new() -> Self {
        Program::default()
    }

    /// A relation given by an input. Of no column (`N` = 0) it is a flag, given as a bool
    /// ([`crate::Inputs::flag`]).
    pub fn input<const N: usize>(&mut self, name: &str) -> Rel<N> {
        Rel::new(self.plan.input(name, N))
    }

    /// An input relation named `name` as `catalog` has it ([`Catalog::relation`]: a node
    /// label `L`, an edge label `E`, a property `L.k` or `E.k`), of the catalog's column
    /// types; [`crate::Inputs::bind`] gives it its source. Refused: a name the catalog does
    /// not have (or refuses), a width other than `N`.
    ///
    /// ```
    /// use kleene_datalog::{Catalog, Program, Source, Type};
    /// let mut c = Catalog::new();
    /// let ids: arrow_array::ArrayRef = std::sync::Arc::new(arrow_array::UInt64Array::from(vec![0, 1]));
    /// let ages: arrow_array::ArrayRef = std::sync::Arc::new(arrow_array::Int64Array::from(vec![30, 40]));
    /// c.typed_property("person", "age", Source::Columns(vec![ids, ages]), Type::I64);
    /// let mut p = Program::new();
    /// let age = p.input_from::<2>(&c, "person.age").unwrap();
    /// assert_eq!(p.types(age.id()), [Type::U64, Type::I64]);
    /// assert!(p.input_from::<3>(&c, "person.age").is_err());
    /// ```
    pub fn input_from<const N: usize>(&mut self, catalog: &Catalog, name: &str) -> Result<Rel<N>> {
        const { assert!(N > 0, "a relation has at least one column") };
        let (_, types) = catalog.relation(name)?;
        if types.len() != N {
            return Err(crate::DatalogError::Input(format!(
                "`{name}` has {} columns in the catalog, not {N}",
                types.len()
            )));
        }
        Ok(Rel::new(self.plan.input_from(catalog, name)?))
    }

    /// An input named `name` of `types`, EMPTY where the set's `catalog` lacks the name
    /// ([`kleene_plan::Plan::input_or_empty`]): [`crate::Inputs::bind`] binds it empty
    /// then, else from the catalog (whose types must be `types`). A property the catalog
    /// refuses stays refused, by name, with why.
    ///
    /// ```
    /// use kleene_datalog::{Catalog, Program, Type};
    /// let c = Catalog::new();
    /// let mut p = Program::new();
    /// let inst = p.input_or_empty(&c, "inst", [Type::U64]).unwrap();
    /// assert!(p.is_optional(inst.id()));
    /// ```
    pub fn input_or_empty<const N: usize>(
        &mut self,
        catalog: &Catalog,
        name: &str,
        types: [Type; N],
    ) -> Result<Rel<N>> {
        const { assert!(N > 0, "a relation has at least one column") };
        Ok(Rel::new(self.plan.input_or_empty(catalog, name, &types)?))
    }

    /// The set's schema as relations of strings a rule reads ([`Schema`]), filled by
    /// [`crate::Inputs::bind`] from the catalog it is given: which node labels, edge labels
    /// and columns the set has, and which columns it refuses. Refused: a catalog with a
    /// relation named `schema.label`, `schema.edge`, `schema.column` or `schema.refused`.
    ///
    /// ```
    /// use kleene_datalog::{Program, datalog};
    /// let mut p = Program::new();
    /// let s = p.schema(&kleene_datalog::Catalog::new()).unwrap();
    /// let site = p.input::<1>("site");
    /// let inst = p.str("inst");
    /// datalog!(&mut p => derived no_inst/1. no_inst(S) :- site(S), !s.label(inst).).unwrap();
    /// ```
    pub fn schema(&mut self, catalog: &Catalog) -> Result<Schema> {
        let s = self.plan.schema(catalog)?;
        Ok(Schema {
            label: Rel::new(s.label),
            edge: Rel::new(s.edge),
            column: Rel::new(s.column),
            refused: Rel::new(s.refused),
        })
    }

    /// A relation answered by an [`crate::External`] when a rule runs (an index lookup or
    /// a producer of facts), given with [`crate::Inputs::external`]. In a rule body it is
    /// a positive or negated atom like any other; the engine asks it with the columns the
    /// rule's other atoms bind.
    pub fn external<const N: usize>(&mut self, name: &str) -> Rel<N> {
        const { assert!(N > 0, "an external relation has at least one column") };
        const { assert!(N <= 64, "an external relation has at most 64 columns") };
        Rel::new(self.plan.external(name, N))
    }

    /// A relation derived by rules. Of no column (`N` = 0) it is a flag: a rule
    /// `flag() :- body.` makes it hold, an atom `flag.atom([])` reads it (negated too), and
    /// [`crate::Output::holds`] tells whether it holds.
    ///
    /// ```
    /// use kleene_datalog::Program;
    /// let mut p = Program::new();
    /// let t = p.input::<1>("t");
    /// let has = p.derived::<0>("has");
    /// let x = p.var("X");
    /// let r = p.rule(has.atom([]), [t.at([x])]).unwrap();
    /// assert_eq!(p.show_rule(r), "has() :- t(X).");
    /// ```
    pub fn derived<const N: usize>(&mut self, name: &str) -> Rel<N> {
        Rel::new(self.plan.derived(name, N))
    }

    /// A table of sets of `N` columns, all u64 ([`kleene_plan::Plan::sets`]): column 0 is a
    /// set's number (from 0), the other `N - 1` are one element. It gives each distinct set
    /// that rules number into it ([`Aggregate::set_number`] in [`Program::aggregate`]) one
    /// number, and holds each set once, a row `(n, element..)` per element; rules read it
    /// as any relation, and no rule derives it. `limit` is the most sets it may number
    /// (`None`: [`kleene_plan::DEFAULT_SET_LIMIT`]); a run that would number more stops with
    /// [`crate::DatalogError::SetLimit`]. In `datalog!`: `sets state/2 limit 1000.`
    ///
    /// ```
    /// use kleene_datalog::{Aggregate, Program};
    /// let mut p = Program::new();
    /// let member = p.input::<2>("member");
    /// let state = p.sets::<2>("state", Some(1000));
    /// let id = p.derived::<2>("id");
    /// let (k, x, n) = (p.var("K"), p.var("X"), p.var("N"));
    /// // id(K, N) :- N = set (X) by (K) in state: member(K, X).
    /// let agg = Aggregate::set_number([k], [x], n, state.id());
    /// let r = p.aggregate(id.at([k, n]), agg, [member.at([k, x])]).unwrap();
    /// assert_eq!(p.show_rule(r), "id(K, N) :- N = set (X) by (K) in state: member(K, X).");
    /// assert_eq!(p.set_limit(state.id()), Some(1000));
    /// ```
    pub fn sets<const N: usize>(&mut self, name: &str, limit: Option<u64>) -> Rel<N> {
        const { assert!(N > 1, "a table of sets has a number and an element") };
        Rel::new(self.plan.sets(name, N, limit))
    }

    /// [`Program::sets`] with a type per column ([`kleene_plan::Plan::sets_typed`]):
    /// `types[0]`, the number, is [`Type::U64`]; the rest are the element's. Panics when the
    /// first is not u64.
    ///
    /// ```
    /// use kleene_datalog::{Program, Type};
    /// let mut p = Program::new();
    /// let names = p.sets_typed("names", [Type::U64, Type::Str], None);
    /// assert_eq!(p.types(names.id()), [Type::U64, Type::Str]);
    /// ```
    pub fn sets_typed<const N: usize>(
        &mut self,
        name: &str,
        types: [Type; N],
        limit: Option<u64>,
    ) -> Rel<N> {
        const { assert!(N > 1, "a table of sets has a number and an element") };
        Rel::new(self.plan.sets_typed(name, &types, limit))
    }

    /// The state machine of a graph with labels, the subset construction, as relations and
    /// rules added to this program ([`kleene_plan::Plan::state_machine`]): from the edges
    /// `edge(from, label, to)`, the edges without a label `eps(from, to)` (or none) and the
    /// starts `start(key, node)`, the relations `{name}.member(state, node)` (a table of sets
    /// of at most `limit` sets), `{name}.step(state, label, next)`, `{name}.start(key,
    /// state)` and `{name}.state(state)`. A state is a set of nodes closed under `eps`; the
    /// numbers are those of the rules written out in the text (`sets`, `N = set(..) in ..`,
    /// one `rounds` line). Refused by name: a node column of another type; nothing is added
    /// then.
    ///
    /// ```
    /// use kleene_datalog::Program;
    /// let mut p = Program::new();
    /// let edge = p.input::<3>("edge");
    /// let eps = p.input::<2>("eps");
    /// let start = p.input::<2>("start");
    /// let m = p.state_machine("nfa", &edge, Some(&eps), &start, None).unwrap();
    /// assert_eq!(p.relation_info(m.step.id()).name, "nfa.step");
    /// assert_eq!(p.set_limit(m.member.id()), Some(kleene_datalog::DEFAULT_SET_LIMIT));
    /// ```
    pub fn state_machine(
        &mut self,
        name: &str,
        edge: &Rel<3>,
        eps: Option<&Rel<2>>,
        start: &Rel<2>,
        limit: Option<u64>,
    ) -> Result<Machine> {
        let graph = kleene_plan::MachineGraph {
            edge: edge.id(),
            eps: eps.map(Rel::id),
            start: start.id(),
        };
        let m = self.plan.state_machine(name, graph, limit)?;
        Ok(Machine {
            member: Rel::new(m.member),
            step: Rel::new(m.step),
            start: Rel::new(m.start),
            state: Rel::new(m.state),
        })
    }

    /// A relation given by an input whose columns have `types`
    /// ([`kleene_plan::Plan::input_typed`]): strings, signed integers, floats, booleans,
    /// each with nulls, or [`Type::U64`] as [`Program::input`] has them.
    pub fn input_typed<const N: usize>(&mut self, name: &str, types: [Type; N]) -> Rel<N> {
        Rel::new(self.plan.input_typed(name, &types))
    }

    /// A relation derived by rules whose columns have `types`.
    pub fn derived_typed<const N: usize>(&mut self, name: &str, types: [Type; N]) -> Rel<N> {
        Rel::new(self.plan.derived_typed(name, &types))
    }

    /// A relation answered by an [`crate::External`] whose columns have `types`; it hands
    /// and takes codes ([`Type::encode`]), and a [`Type::Str`] column is refused when a run
    /// starts.
    pub fn external_typed<const N: usize>(&mut self, name: &str, types: [Type; N]) -> Rel<N> {
        const { assert!(N > 0, "an external relation has at least one column") };
        const { assert!(N <= 64, "an external relation has at most 64 columns") };
        Rel::new(self.plan.external_typed(name, &types))
    }

    /// A string constant, for a [`Type::Str`] column or a comparison with a string
    /// variable ([`kleene_plan::Plan::str`]). Signed, float and boolean constants are
    /// [`Term::int`], [`Term::float`], [`Term::bool`].
    ///
    /// ```
    /// use kleene_datalog::{Program, Term, Type, lt};
    /// let mut p = Program::new();
    /// let person = p.input_typed("person", [Type::Str, Type::I64]);
    /// let young = p.derived_typed("young", [Type::Str]);
    /// let (n, a) = (p.var("N"), p.var("A"));
    /// let ann = p.str("ann");
    /// p.rule(young.at([n]), [person.atom([n.into(), a.into()]).into(), lt(a, Term::int(30))]).unwrap();
    /// p.rule(young.at([ann]), [person.atom([ann, a.into()])]).unwrap();
    /// ```
    pub fn str(&mut self, s: &str) -> Term {
        self.plan.str(s)
    }

    /// `c` coded for a place of type `ty` ([`kleene_plan::Plan::constant`], as GQL codes
    /// its literals): `Constant::Int(-1)` for an i64 column is [`Term::int`]`(-1)`, an
    /// unsigned integer for an f64 one its float, a string [`Program::str`]. Refused: a pair
    /// that does not fit (a negative number for a u64 place, a float for an integer one, a
    /// string for a number). The `datalog!` macro codes its literals so (`-1`, `1.5`,
    /// `"ann"`, `18`), by the column or variable they meet; the builder does not, nor does
    /// the macro a Rust value (`{x}`, a local, a path): in `rel.at([5u64])` or `lt(x, 5u64)`
    /// the number is the raw code, which is the number only for a u64 or bool place.
    ///
    /// ```
    /// use kleene_datalog::{Constant, Program, Term, Type};
    /// let mut p = Program::new();
    /// assert_eq!(p.constant(&Constant::Int(-1), Type::I64).unwrap(), Term::int(-1));
    /// assert_eq!(p.constant(&Constant::Uint(30), Type::I64).unwrap(), Term::int(30));
    /// assert!(p.constant(&Constant::Float(1.5), Type::U64).is_err());
    /// ```
    pub fn constant(&mut self, c: &Constant, ty: Type) -> Result<Term> {
        self.plan.constant(c, ty)
    }

    /// A list of constants for [`one_of`] and [`not_one_of`] (`K in (1, 2, 3)`), its members
    /// coded for `ty`, the type of the value it is tested on
    /// ([`kleene_plan::Plan::list`]): a [`ListMember::Const`] (a literal, a Rust string) as
    /// [`Program::constant`] codes it, a Rust integer or boolean raw. Refused by the
    /// member's place: one that does not fit `ty`.
    ///
    /// ```
    /// use kleene_datalog::{ListMember, Literal, Program, Type, one_of};
    /// let mut p = Program::new();
    /// let item = p.input_typed("item", [Type::U64, Type::U64]);
    /// let small = p.derived_typed("small", [Type::U64]);
    /// let (i, k) = (p.var("I"), p.var("K"));
    /// let l = p.list(Type::U64, [1u64, 2, 3].map(ListMember::from)).unwrap();
    /// let r = p.rule(small.at([i]), [Literal::from(item.at([i, k])), one_of(k, l)]).unwrap();
    /// assert_eq!(p.show_rule(r), "small(I) :- item(I, K), K in (1, 2, 3).");
    /// ```
    pub fn list(
        &mut self,
        ty: Type,
        members: impl IntoIterator<Item = ListMember>,
    ) -> Result<ListId> {
        self.plan.list(ty, members)
    }

    /// A list as [`Program::list`] makes it, shown by `name` (the Rust path it was given
    /// by) in a rule's text (`N in {names::CALLEES}`) and a proof.
    pub fn list_named(
        &mut self,
        name: &str,
        ty: Type,
        members: impl IntoIterator<Item = ListMember>,
    ) -> Result<ListId> {
        self.plan.list_named(name, ty, members)
    }

    /// A variable (each call is a new variable; the name is for printing).
    pub fn var(&mut self, name: &str) -> Var {
        self.plan.var(name)
    }

    /// The edges of `edges` that pass every one of `tests` (comparisons of edge properties
    /// with constants, an AND held or false), as a derived relation `name` a walk or rule
    /// then reads ([`kleene_plan::Plan::edge_filter`]).
    pub fn edge_filter(
        &mut self,
        name: &str,
        edges: &Rel<2>,
        tests: &[kleene_plan::EdgeTest],
    ) -> Result<Rel<2>> {
        Ok(Rel::new(self.plan.edge_filter(name, edges.id(), tests)?))
    }

    /// Add `head :- body`. Refused: a head on an input relation, a body with no positive
    /// atom, a head variable, a negated atom's variable or a condition's variable no
    /// positive atom binds.
    pub fn rule<L: Into<Literal>>(
        &mut self,
        head: Atom,
        body: impl IntoIterator<Item = L>,
    ) -> Result<RuleId> {
        self.plan.rule(head, body)
    }

    /// Add an aggregate rule: `body`'s bindings grouped by `agg.group`, each group reduced
    /// to one head fact (or none, for an [`Aggregate::exactly_one`] that fails). Refused,
    /// besides what [`Program::rule`] refuses: a grouping variable missing from the head, a
    /// counted, key or single-valued variable no positive atom binds, a count's result
    /// variable that a body atom binds, a head variable the reduction does not give, an
    /// empty key or counted tuple. Stratified like negation: [`crate::plan`] refuses an
    /// aggregate over its own recursion.
    ///
    /// ```
    /// use kleene_datalog::{Aggregate, Program};
    /// let mut p = Program::new();
    /// let calls = p.input::<2>("calls");
    /// let fan = p.derived::<2>("fan");
    /// let (f, g, n) = (p.var("F"), p.var("G"), p.var("N"));
    /// // fan(F, N) :- N = count (G) by (F): calls(F, G).
    /// p.aggregate(fan.at([f, n]), Aggregate::count([f], [g], n), [calls.at([f, g])]).unwrap();
    /// ```
    pub fn aggregate<L: Into<Literal>>(
        &mut self,
        head: Atom,
        agg: Aggregate,
        body: impl IntoIterator<Item = L>,
    ) -> Result<RuleId> {
        self.plan.aggregate(head, agg, body)
    }

    /// Add a fold rule ([`kleene_plan::Plan::fold`]): `body`'s bindings grouped by
    /// `fold.group`, the folded variable's values of each group's distinct bindings summed
    /// ([`Fold::sum`]: of its type, u64, i64 or f64) or averaged ([`Fold::avg`]: an f64
    /// column); nulls skipped. Stratified like an aggregate.
    ///
    /// ```
    /// use kleene_datalog::{Fold, Program, Type};
    /// let mut p = Program::new();
    /// let sale = p.input_typed("sale", [Type::Str, Type::I64]);
    /// let mean = p.derived_typed("mean", [Type::Str, Type::F64]);
    /// let (who, n, m) = (p.var("Who"), p.var("N"), p.var("M"));
    /// p.fold(mean.at([who, m]), Fold::avg([who], n, m), [sale.at([who, n])]).unwrap();
    /// ```
    pub fn fold<L: Into<Literal>>(
        &mut self,
        head: Atom,
        fold: Fold,
        body: impl IntoIterator<Item = L>,
    ) -> Result<RuleId> {
        self.plan.fold(head, fold, body)
    }

    /// A relation derived with a count per row, its last of `N` columns
    /// ([`kleene_plan::Plan::derived_counted`]): a bag of rows, one fact per distinct row
    /// with how many times it holds. Given by [`Program::count_rule`].
    pub fn derived_counted<const N: usize>(&mut self, name: &str) -> Rel<N> {
        const { assert!(N > 1, "a counted relation has a column and its count") };
        Rel::new(self.plan.derived_counted(name, &[Type::U64; N][..N - 1]))
    }

    /// An input relation with a count per row, its last of `N` columns
    /// ([`kleene_plan::Plan::input_counted`]).
    pub fn input_counted<const N: usize>(&mut self, name: &str) -> Rel<N> {
        const { assert!(N > 1, "a counted relation has a column and its count") };
        Rel::new(self.plan.input_counted(name, &[Type::U64; N][..N - 1]))
    }

    /// Add a counting rule, `head(X.., N) :- body` with `N` the number of derivations
    /// ([`kleene_plan::Plan::count_rule`]): the number of the body's distinct bindings
    /// that give each head row, a counted body atom's count multiplying, several counting
    /// rules of one relation adding up.
    ///
    /// ```
    /// use kleene_datalog::Program;
    /// let mut p = Program::new();
    /// let e = p.input::<2>("e");
    /// let two = p.derived_counted::<3>("two");
    /// let (a, b, c, n) = (p.var("A"), p.var("B"), p.var("C"), p.var("N"));
    /// // two(A, C, N) :- N = count () by (A, C): e(A, B), e(B, C).
    /// p.count_rule(two.at([a, c, n]), [e.at([a, b]), e.at([b, c])]).unwrap();
    /// ```
    pub fn count_rule<L: Into<Literal>>(
        &mut self,
        head: Atom,
        body: impl IntoIterator<Item = L>,
    ) -> Result<RuleId> {
        self.plan.count_rule(head, body)
    }

    /// Run `parts` (derived relations, in this order) as one stratum of inflationary
    /// rounds, so their rules may count and negate inside the recursion
    /// ([`kleene_plan::Plan::rounds`]): each round computes the parts in order, each from
    /// this round's facts of the parts before it and the round before's of the rest; a
    /// [`Part::Keep`] grows, a [`Part::Fresh`] is made afresh; the rounds stop when one
    /// changes nothing. The why of their facts names the round.
    ///
    /// ```
    /// use kleene_datalog::{Part, Program};
    /// let mut p = Program::new();
    /// let e = p.input::<2>("e");
    /// let s = p.input::<1>("s");
    /// let ev = p.derived::<1>("ev");
    /// let od = p.derived::<1>("od");
    /// let (x, y) = (p.var("X"), p.var("Y"));
    /// p.rule(ev.at([x]), [s.at([x])]).unwrap();
    /// // od(Y) :- ev(X), e(X, Y), !ev(Y).   ev(Y) :- od(X), e(X, Y), !od(Y).
    /// p.rule(od.at([y]), [ev.at([x]).into(), e.at([x, y]).into(), !ev.at([y])]).unwrap();
    /// p.rule(ev.at([y]), [od.at([x]).into(), e.at([x, y]).into(), !od.at([y])]).unwrap();
    /// p.rounds([(ev.id(), Part::Keep), (od.id(), Part::Keep)]).unwrap();
    /// assert!(kleene_datalog::plan(&p).is_ok());
    /// ```
    pub fn rounds(&mut self, parts: impl IntoIterator<Item = (RelId, Part)>) -> Result<()> {
        self.plan.rounds(parts)
    }

    /// Relation `rel` given by a graph procedure over the edges `edge` (two columns)
    /// ([`kleene_plan::Plan::procedure`]): PageRank, components, shortest paths, ...; one row
    /// per vertex in the edges' ids (ids far apart are numbered for the run and mapped back).
    ///
    /// ```
    /// use kleene_datalog::{Procedure, Program};
    /// let mut p = Program::new();
    /// let calls = p.input::<2>("calls");
    /// let part = p.derived::<2>("part");
    /// p.procedure(&part, &calls, Procedure::WeakComponents).unwrap();
    /// ```
    pub fn procedure<const N: usize>(
        &mut self,
        rel: &Rel<N>,
        edge: &Rel<2>,
        procedure: Procedure,
    ) -> Result<()> {
        self.plan.procedure(rel.id(), edge.id(), procedure)
    }
}

/// The relations of a state machine ([`Program::state_machine`]).
#[derive(Clone, Copy, Debug)]
pub struct Machine {
    /// The table of sets `member(state, node)`: each state's nodes.
    pub member: Rel<2>,
    /// `step(state, label, next)`: the state a label leads to.
    pub step: Rel<3>,
    /// `start(key, state)`: the state of each start key.
    pub start: Rel<2>,
    /// `state(state)`: each state once.
    pub state: Rel<1>,
}

/// The relations of a set's schema ([`Program::schema`]), each of string columns.
#[derive(Clone, Copy, Debug)]
pub struct Schema {
    /// `label(L)`: every node label of the set (one with no nodes too).
    pub label: Rel<1>,
    /// `edge(E)`: every edge label, by table name (`src_edge_dst`) and by bare edge name
    /// where one edge type alone has it.
    pub edge: Rel<1>,
    /// `column(L, C, TY)`: every column the catalog reads, of a node or an edge label, `TY`
    /// its type's name (`u64`, `i64`, `f64`, `bool`, `str`).
    pub column: Rel<3>,
    /// `refused(L, C, WHY)`: every column the catalog refuses, with why.
    pub refused: Rel<3>,
}

/// The strata of a program, dependencies first ([`kleene_plan::plan`] on its plan): the
/// derived relations' dependency graph (negated atoms included) cut into strongly connected
/// parts, each given a plan. A part whose rules negate one of its own relations, or
/// aggregate over one, cannot be stratified and is refused, unless it is a group of
/// [`Program::rounds`].
pub fn plan(p: &Program) -> Result<Vec<Stratum>> {
    kleene_plan::plan(&p.plan)
}

/// `a op b` as a body literal: a [`Cond`] when both sides are bare terms (a variable or a
/// constant), else a [`Test`] (each side that is an [`Expr`] computed first).
pub fn compare(a: impl Into<Expr>, op: Cmp, b: impl Into<Expr>) -> Literal {
    let (a, b) = (a.into(), b.into());
    match (a.term(), b.term()) {
        (Some(left), Some(right)) => Literal::Cond(Cond::Cmp { left, op, right }),
        _ => Literal::Test(Test::Cmp {
            left: a,
            op,
            right: b,
        }),
    }
}

/// `out = expr` as a body literal ([`Compute`]): binds `out` to the value of `expr`, or
/// tests it where a positive atom (or an earlier compute) binds it.
///
/// ```
/// use kleene_datalog::{Expr, Program, compute};
/// let mut p = Program::new();
/// let st = p.input::<2>("st");
/// let ix = p.input::<2>("ix");
/// let off = p.derived::<2>("off");
/// let (s, lo, i, o) = (p.var("S"), p.var("LO"), p.var("I"), p.var("O"));
/// // off(S, O) :- st(S, LO), ix(S, I), O = LO + I.
/// let r = p
///     .rule(off.at([s, o]), [st.at([s, lo]).into(), ix.at([s, i]).into(), compute(o, Expr::from(lo) + i)])
///     .unwrap();
/// assert_eq!(p.show_rule(r), "off(S, O) :- st(S, LO), ix(S, I), O = LO + I.");
/// ```
pub fn compute(out: Var, expr: impl Into<Expr>) -> Literal {
    Literal::Compute(Compute::new(out, expr))
}

/// `a == b`
pub fn eq(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Eq, b)
}

/// `a != b`
pub fn ne(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Ne, b)
}

/// `a < b`
pub fn lt(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Lt, b)
}

/// `a <= b`
pub fn le(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Le, b)
}

/// `a > b`
pub fn gt(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Gt, b)
}

/// `a >= b`
pub fn ge(a: impl Into<Expr>, b: impl Into<Expr>) -> Literal {
    compare(a, Cmp::Ge, b)
}

/// `x IS NULL`: `x` (of a nullable column) has no value.
pub fn is_null(x: impl Into<Term>) -> Literal {
    Literal::Cond(Cond::IsNull {
        x: x.into(),
        null: true,
    })
}

/// `x IS NOT NULL`.
pub fn is_not_null(x: impl Into<Term>) -> Literal {
    Literal::Cond(Cond::IsNull {
        x: x.into(),
        null: false,
    })
}

/// `lo <= x < hi`: `x` in `[lo, hi)`; a [`Test`] when a place is an [`Expr`].
pub fn within(x: impl Into<Expr>, lo: impl Into<Expr>, hi: impl Into<Expr>) -> Literal {
    let (x, lo, hi) = (x.into(), lo.into(), hi.into());
    match (x.term(), lo.term(), hi.term()) {
        (Some(x), Some(lo), Some(hi)) => Literal::Cond(Cond::Within { x, lo, hi }),
        _ => Literal::Test(Test::Within { x, lo, hi }),
    }
}

/// `x op pat`: a test of the string variable `x` against the string constant `pat`
/// ([`Program::str`]): [`TextOp`]'s starts with, ends with or contains. A null is not true.
pub fn text(x: impl Into<Term>, op: TextOp, pat: impl Into<Term>) -> Literal {
    Literal::Cond(Cond::Text {
        x: x.into(),
        op,
        pat: pat.into(),
    })
}

/// `x starts with pat`
///
/// ```
/// use kleene_datalog::{Program, Type, starts_with};
/// let mut p = Program::new();
/// let func = p.input_typed("func", [Type::U64, Type::Str]);
/// let parser = p.derived_typed("parser", [Type::U64]);
/// let (i, n) = (p.var("I"), p.var("N"));
/// let pre = p.str("parse");
/// p.rule(parser.at([i]), [func.at([i, n]).into(), starts_with(n, pre)]).unwrap();
/// ```
pub fn starts_with(x: impl Into<Term>, pat: impl Into<Term>) -> Literal {
    text(x, TextOp::StartsWith, pat)
}

/// `x ends with pat`
pub fn ends_with(x: impl Into<Term>, pat: impl Into<Term>) -> Literal {
    text(x, TextOp::EndsWith, pat)
}

/// `x contains pat`
pub fn contains(x: impl Into<Term>, pat: impl Into<Term>) -> Literal {
    text(x, TextOp::Contains, pat)
}

/// `x in list`: `x` is one of the members of `list` ([`Program::list`]); a [`Test`] when
/// `x` is an [`Expr`] (computed first). A null is in no list; an empty list holds for no
/// value.
pub fn one_of(x: impl Into<Expr>, list: ListId) -> Literal {
    member_of(x.into(), list, false)
}

/// `!(x in list)`: `x` is not one of the members of `list`. A null is not out of a list
/// either: the literal does not hold for it.
pub fn not_one_of(x: impl Into<Expr>, list: ListId) -> Literal {
    member_of(x.into(), list, true)
}

fn member_of(x: Expr, list: ListId, not: bool) -> Literal {
    match x.term() {
        Some(x) => Literal::Cond(Cond::OneOf { x, list, not }),
        None => Literal::Test(Test::OneOf { x, list, not }),
    }
}