crates/kleene-plan/src/rules.rs
use std::fmt;
use crate::compute::{Compute, Expr, Test, operand_type};
use crate::typed::{Type, f64_code, i64_code};
use crate::{PlanError, Result};
/// A relation's number in its plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RelId(pub(crate) u32);
impl RelId {
/// The number.
pub fn index(self) -> usize {
self.0 as usize
}
}
/// A rule's number in its plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleId(pub(crate) u32);
impl RuleId {
/// The number.
pub fn index(self) -> usize {
self.0 as usize
}
}
/// A variable of a plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Var(pub(crate) u32);
/// A value of a fact: an unsigned 64-bit integer (an address, an id, a small number).
/// Columns keep `u32` storage while every value fits ([`crate::Column`]); a value is never
/// cut to fewer bits. A graph stratum (reach, closure) takes its vertex ids as `u32` and
/// refuses a larger one.
pub type Value = u64;
/// A term of an atom: a variable or a constant.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Term {
/// A variable.
Var(Var),
/// A constant.
Const(Value),
}
impl From<Var> for Term {
fn from(v: Var) -> Self {
Term::Var(v)
}
}
impl From<u32> for Term {
fn from(c: u32) -> Self {
Term::Const(c as Value)
}
}
impl From<u64> for Term {
fn from(c: u64) -> Self {
Term::Const(c)
}
}
impl Term {
/// A signed integer constant (its code; a column or comparison of type
/// [`Type::I64`] reads it as the integer). `i64::MAX` is refused when a rule takes it.
pub fn int(x: i64) -> Term {
Term::Const(i64_code(x))
}
/// A float constant (its code, read as a float by a [`Type::F64`] column or comparison).
pub fn float(x: f64) -> Term {
Term::Const(f64_code(x))
}
/// A boolean constant (0 or 1).
pub fn bool(b: bool) -> Term {
Term::Const(b as Value)
}
/// The term's value under `binding` (a constant is itself); `None` for a variable the
/// binding does not hold.
pub fn value(&self, binding: &[(Var, Value)]) -> Option<Value> {
match self {
Term::Const(c) => Some(*c),
Term::Var(v) => binding.iter().find(|(w, _)| w == v).map(|(_, x)| *x),
}
}
pub(crate) fn var(&self) -> Option<Var> {
match self {
Term::Var(v) => Some(*v),
Term::Const(_) => None,
}
}
}
/// A constant as a client writes it, before it is coded for the place it meets
/// ([`Plan::constant`]): GQL's literals and parameters, the `datalog!` macro's literals and
/// Rust values.
#[derive(Clone, Debug, PartialEq)]
pub enum Constant {
/// An unsigned integer.
Uint(u64),
/// A signed integer.
Int(i64),
/// A float.
Float(f64),
/// A string.
Str(String),
/// A boolean.
Bool(bool),
}
impl Constant {
/// What it is, in words (for a refusal).
pub fn kind(&self) -> &'static str {
match self {
Constant::Uint(_) => "an unsigned integer",
Constant::Int(i) if *i < 0 => "a negative integer",
Constant::Int(_) => "a signed integer",
Constant::Float(_) => "a float",
Constant::Str(_) => "a string",
Constant::Bool(_) => "a boolean",
}
}
/// The type it has where nothing else gives one: an unsigned integer [`Type::U64`], a
/// signed one [`Type::I64`], a float [`Type::F64`], a string [`Type::Str`], a boolean
/// [`Type::Bool`].
pub fn own_type(&self) -> Type {
match self {
Constant::Uint(_) => Type::U64,
Constant::Int(_) => Type::I64,
Constant::Float(_) => Type::F64,
Constant::Str(_) => Type::Str,
Constant::Bool(_) => Type::Bool,
}
}
}
/// A comparison of two values (unsigned).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Cmp {
/// `a == b`
Eq,
/// `a != b`
Ne,
/// `a < b`
Lt,
/// `a <= b`
Le,
/// `a > b`
Gt,
/// `a >= b`
Ge,
}
impl Cmp {
/// Whether `a op b` holds.
#[inline]
pub fn holds(self, a: Value, b: Value) -> bool {
match self {
Cmp::Eq => a == b,
Cmp::Ne => a != b,
Cmp::Lt => a < b,
Cmp::Le => a <= b,
Cmp::Gt => a > b,
Cmp::Ge => a >= b,
}
}
/// The operator as text.
pub fn symbol(self) -> &'static str {
match self {
Cmp::Eq => "==",
Cmp::Ne => "!=",
Cmp::Lt => "<",
Cmp::Le => "<=",
Cmp::Gt => ">",
Cmp::Ge => ">=",
}
}
/// The operator that holds exactly where this one does not.
pub fn negated(self) -> Cmp {
match self {
Cmp::Eq => Cmp::Ne,
Cmp::Ne => Cmp::Eq,
Cmp::Lt => Cmp::Ge,
Cmp::Ge => Cmp::Lt,
Cmp::Le => Cmp::Gt,
Cmp::Gt => Cmp::Le,
}
}
}
/// One test on the edges of a walk ([`Plan::edge_filter`]): an AND of comparisons of edge
/// properties with constants, each property an `(from, to, value)` relation; kept where the
/// AND holds (`keep`, GQL's `all(x IN r WHERE ...)`) or where it is false (`none(...)`).
/// A property an edge lacks makes the AND neither: the edge is not kept either way.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EdgeTest {
/// `(property relation, op, constant)`: `value op constant`.
pub cmps: Vec<(RelId, Cmp, Value)>,
/// Whether the AND must hold (else, be false).
pub keep: bool,
}
/// A condition of a rule body over values its positive atoms bind: a comparison, or a
/// half-open range.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Cond {
/// `left op right`.
Cmp {
/// The left side.
left: Term,
/// The comparison.
op: Cmp,
/// The right side.
right: Term,
},
/// `lo <= x < hi`: `x` in the half-open range `[lo, hi)`.
Within {
/// The value tested.
x: Term,
/// The first value inside.
lo: Term,
/// The first value past the range.
hi: Term,
},
/// `x IS NULL` (`null`) or `x IS NOT NULL`: on a nullable column ([`Type::nullable`]),
/// whether its value is missing; a [`Type::U64`] value is never null.
IsNull {
/// The value tested.
x: Term,
/// True: holds when `x` is null; false: when it is not.
null: bool,
},
/// `x STARTS WITH pat`, `x ENDS WITH pat`, `x CONTAINS pat`: a test of a string
/// variable against a string constant ([`Plan::str`]). A run decides it once per
/// string of its dictionary, not per row: a prefix is one range of ids (the dictionary
/// is sorted), a suffix or a part a set of ids. A null is not true.
Text {
/// The string tested (a [`Type::Str`] variable).
x: Term,
/// The test.
op: TextOp,
/// The pattern (a string constant).
pat: Term,
},
/// `x in (k1, k2, ..)`, or `!(x in (..))` (`not`): whether `x` is one of the members of
/// a list of constants ([`Plan::list`]). A null holds neither form; an empty list holds
/// for no value (its negation for every value that is not null).
OneOf {
/// The value tested.
x: Term,
/// The list.
list: ListId,
/// True: holds when `x` is not a member.
not: bool,
},
}
/// A list of constants of a plan ([`Plan::list`]) that a [`Cond::OneOf`] tests a value
/// against: its number in the plan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ListId(pub(crate) u32);
impl ListId {
/// The number.
pub fn index(self) -> usize {
self.0 as usize
}
}
/// A member of a list as a client gives it ([`Plan::list`]): a constant, coded for the
/// list's type as [`Plan::constant`] codes it, or a raw value (a Rust integer or boolean),
/// its code as it is, as a Rust value in braces is in a `datalog!` atom.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ListMember {
/// A constant (a literal of the rule text or of a query, a Rust string).
Const(Constant),
/// A raw value.
Raw(Value),
}
macro_rules! raw_members {
($($t:ty),*) => {$(
impl From<$t> for ListMember {
fn from(x: $t) -> Self {
ListMember::Raw(Value::from(x))
}
}
)*};
}
raw_members!(u8, u16, u32, u64, bool);
impl From<&str> for ListMember {
fn from(s: &str) -> Self {
ListMember::Const(Constant::Str(s.to_string()))
}
}
impl From<String> for ListMember {
fn from(s: String) -> Self {
ListMember::Const(Constant::Str(s))
}
}
impl From<&String> for ListMember {
fn from(s: &String) -> Self {
ListMember::Const(Constant::Str(s.clone()))
}
}
impl From<Constant> for ListMember {
fn from(c: Constant) -> Self {
ListMember::Const(c)
}
}
/// A list of a plan ([`Plan::list`]): its members coded for its type, as given.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct List {
/// The name it is shown by (a Rust path), if it has one ([`Plan::list_named`]).
pub name: Option<String>,
/// The type of its members: the type of the value it is tested on.
pub ty: Type,
/// The members' codes, in the order given (a string: its number in
/// [`Plan::strings`]).
pub members: Vec<Value>,
/// The codes a run tests, sorted, each once (a string: its id in the run's dictionary,
/// set when the plan is resolved for a run).
pub(crate) run: Vec<Value>,
}
impl List {
/// Whether `v` is a member (of the codes a run tests): a scan of a short list, a binary
/// search of a long one.
#[inline]
pub(crate) fn has(run: &[Value], v: Value) -> bool {
if run.len() <= 16 {
run.contains(&v)
} else {
run.binary_search(&v).is_ok()
}
}
}
/// A test of a string against a pattern ([`Cond::Text`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TextOp {
/// The string starts with the pattern.
StartsWith,
/// The string ends with the pattern.
EndsWith,
/// The pattern occurs in the string.
Contains,
}
impl TextOp {
/// The test as GQL writes it.
pub fn words(self) -> &'static str {
match self {
TextOp::StartsWith => "starts with",
TextOp::EndsWith => "ends with",
TextOp::Contains => "contains",
}
}
/// Whether `s` passes the test with `pat`.
pub fn holds(self, s: &str, pat: &str) -> bool {
match self {
TextOp::StartsWith => s.starts_with(pat),
TextOp::EndsWith => s.ends_with(pat),
TextOp::Contains => s.contains(pat),
}
}
}
impl Cond {
/// The terms, in order.
pub fn terms(&self) -> Vec<Term> {
match *self {
Cond::Cmp { left, right, .. } => vec![left, right],
Cond::Within { x, lo, hi } => vec![x, lo, hi],
Cond::IsNull { x, .. } => vec![x],
Cond::Text { x, pat, .. } => vec![x, pat],
Cond::OneOf { x, .. } => vec![x],
}
}
/// The variables, in order (repeats kept).
pub fn vars(&self) -> impl Iterator<Item = Var> {
self.terms().into_iter().filter_map(|t| t.var())
}
/// Whether the condition holds under `binding`; `false` when a variable is unbound.
pub fn holds(&self, binding: &[(Var, Value)]) -> bool {
match *self {
Cond::Cmp { left, op, right } => match (left.value(binding), right.value(binding)) {
(Some(a), Some(b)) => op.holds(a, b),
_ => false,
},
Cond::Within { x, lo, hi } => {
match (x.value(binding), lo.value(binding), hi.value(binding)) {
(Some(x), Some(lo), Some(hi)) => lo <= x && x < hi,
_ => false,
}
}
// by code: the binding holds codes, and a nullable column's null is NULL
Cond::IsNull { x, null } => x
.value(binding)
.is_some_and(|v| (v == crate::typed::NULL) == null),
// a binding holds string ids, and the strings are the run's: not decided here
Cond::Text { .. } => false,
// the members are the plan's: not decided here
Cond::OneOf { .. } => false,
}
}
}
/// Whether a relation is given (an input, read from a table or a graph), answered by Rust
/// code (an index or producer), or derived by rules.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RelKind {
/// Given: facts come from an input.
Input,
/// Answered when a rule runs by an [`crate::External`] (index lookups, producers).
External,
/// Derived: facts come from rules.
Derived,
}
/// `rel(terms)`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Atom {
/// The relation.
pub rel: RelId,
/// The terms, one per column.
pub terms: Vec<Term>,
}
impl Atom {
/// The variables, in column order (repeats kept).
pub fn vars(&self) -> impl Iterator<Item = Var> + '_ {
self.terms.iter().filter_map(|t| match t {
Term::Var(v) => Some(*v),
Term::Const(_) => None,
})
}
}
/// `!rel(terms)`: the atom must not hold (stratified negation).
impl std::ops::Not for Atom {
type Output = Literal;
fn not(self) -> Literal {
Literal::Neg(self)
}
}
/// A body literal.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Literal {
/// The atom holds.
Pos(Atom),
/// The atom does not hold (stratified negation).
Neg(Atom),
/// A comparison or range over bound values ([`Cond`]).
Cond(Cond),
/// `out = expr`: a computed value ([`Compute`]).
Compute(Compute),
/// A comparison or range with an expression on a side ([`Test`]).
Test(Test),
}
impl From<Atom> for Literal {
fn from(a: Atom) -> Self {
Literal::Pos(a)
}
}
impl From<Cond> for Literal {
fn from(c: Cond) -> Self {
Literal::Cond(c)
}
}
impl Literal {
/// The atom, for an atom literal.
pub fn atom(&self) -> Option<&Atom> {
match self {
Literal::Pos(a) | Literal::Neg(a) => Some(a),
Literal::Cond(_) | Literal::Compute(_) | Literal::Test(_) => None,
}
}
}
/// What an aggregate rule computes for each group of its body's bindings.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Agg {
/// `out` is the number of distinct values of `of` in the group.
Count {
/// The variables counted (distinct tuples).
of: Vec<Var>,
/// The head variable that takes the count; no body atom binds it.
out: Var,
},
/// The group's binding whose `key` tuple is least ("first"): the head takes its values.
/// Bindings with equal keys are told apart by the head's values, least first, then by
/// the rest of the binding, so each group gives one fact, the same at any thread count.
Min {
/// The key, compared column by column.
key: Vec<Var>,
},
/// As [`Agg::Min`] with the greatest key (equal keys: least head values first).
Max {
/// The key, compared column by column.
key: Vec<Var>,
},
/// The group holds when `of` takes exactly one distinct value; the head takes it.
One {
/// The variables that must be single valued.
of: Vec<Var>,
},
/// The position of each binding's key in its group ([`Aggregate::rank`]): `out` is the
/// number of distinct `key` tuples of the group before the binding's own in rising
/// order (from 0; equal keys share it, so it counts distinct keys, not bindings). A
/// binding with a null key column is skipped. The head takes the binding's values and
/// `out`: one fact per binding of its variables.
Rank {
/// The key, compared column by column in each type's own order.
key: Vec<Var>,
/// The head variable that takes the position; no body atom binds it.
out: Var,
},
/// Several reductions of the same group in one pass ([`Aggregate::many`]): counts,
/// sums, means, least and greatest values, each into its head variable. Each skips its
/// nulls (and the bindings where one of its `when` flags is not 1); a group where a
/// reduction finds no value gets 0 for a count and null for the others (its `has` flag
/// 0). A count without a variable takes each binding whole. Every group of the body's
/// bindings gives one fact; no binding gives no fact.
Many {
/// The reductions, each with its head variable.
reduces: Vec<Reduce>,
/// The count columns of counted body atoms: each binding weighs their product in
/// a count and a sum or mean that is not of distinct values (empty: 1).
times: Vec<Var>,
},
/// The number of each group's set in a table of sets ([`Aggregate::set_number`]): the
/// group's distinct `of` tuples are its set, and `out` is that set's number in `table`
/// ([`Plan::sets`]). Equal sets get the same number, also across rules and head
/// relations. A group with no binding gives no fact (there is no empty set); a binding
/// with a null `of` column is skipped, as [`Agg::Rank`] skips a null key (a null in a
/// grouping column is a value of its own). One fact per group: its grouping values
/// and `out`.
SetNumber {
/// The element's variables: as many as the table's element columns, of their types.
of: Vec<Var>,
/// The head variable that takes the set's number (a u64 column); no body atom
/// binds it.
out: Var,
/// The table of sets numbered into.
table: RelId,
},
}
/// What one reduction of [`Agg::Many`] computes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReduceOp {
/// The number of bindings (weighed) with a value, or of distinct values: a u64.
Count,
/// The sum, of the values' type (u64, i64, f64).
Sum,
/// The mean, an f64.
Avg,
/// The least value.
Min,
/// The greatest value.
Max,
}
/// One reduction of [`Agg::Many`]: `out` = `op` over `of`'s values in the group.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reduce {
/// The reduction.
pub op: ReduceOp,
/// The variables reduced: one, or for a count none (each binding whole) or several (a
/// tuple, null where one is).
pub of: Vec<Var>,
/// Of distinct values (unweighed).
pub distinct: bool,
/// Flag variables: a binding counts only where each is 1.
pub when: Vec<Var>,
/// The head variable that takes the result; no body atom binds it.
pub out: Var,
/// A head variable that takes 1 where the group has a value, 0 where none.
pub has: Option<Var>,
}
impl Reduce {
fn of(op: ReduceOp, of: impl IntoIterator<Item = Var>, out: Var) -> Self {
Reduce {
op,
of: of.into_iter().collect(),
distinct: false,
when: Vec::new(),
out,
has: None,
}
}
/// `out` = the number of bindings (each whole).
pub fn count(out: Var) -> Self {
Reduce::of(ReduceOp::Count, [], out)
}
/// `out` = the number of bindings where `of` is not null.
pub fn count_of(of: impl IntoIterator<Item = Var>, out: Var) -> Self {
Reduce::of(ReduceOp::Count, of, out)
}
/// `out` = the sum of `of`.
pub fn sum(of: Var, out: Var) -> Self {
Reduce::of(ReduceOp::Sum, [of], out)
}
/// `out` = the mean of `of`.
pub fn avg(of: Var, out: Var) -> Self {
Reduce::of(ReduceOp::Avg, [of], out)
}
/// `out` = the least value of `of`.
pub fn min(of: Var, out: Var) -> Self {
Reduce::of(ReduceOp::Min, [of], out)
}
/// `out` = the greatest value of `of`.
pub fn max(of: Var, out: Var) -> Self {
Reduce::of(ReduceOp::Max, [of], out)
}
/// Of distinct values.
pub fn distinct(mut self) -> Self {
self.distinct = true;
self
}
/// Only the bindings where each of `flags` is 1.
pub fn when(mut self, flags: impl IntoIterator<Item = Var>) -> Self {
self.when.extend(flags);
self
}
/// `has` takes 1 where the group has a value, else 0.
pub fn has(mut self, has: Var) -> Self {
self.has = Some(has);
self
}
/// The head variables it gives.
pub fn gives(&self) -> impl Iterator<Item = Var> + '_ {
std::iter::once(self.out).chain(self.has)
}
}
/// An aggregate: the body's bindings grouped by `group`, each group reduced by `agg`. Like
/// negation it reads its body relations whole, so they must be complete in lower strata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Aggregate {
/// The grouping variables (each in the head); empty: one group of every binding.
pub group: Vec<Var>,
/// The reduction.
pub agg: Agg,
}
impl Aggregate {
/// `out` = the number of distinct `of` tuples per group.
pub fn count(
group: impl IntoIterator<Item = Var>,
of: impl IntoIterator<Item = Var>,
out: Var,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::Count {
of: of.into_iter().collect(),
out,
},
}
}
/// The binding with the least `key` tuple per group (the first in key order).
pub fn min_by(
group: impl IntoIterator<Item = Var>,
key: impl IntoIterator<Item = Var>,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::Min {
key: key.into_iter().collect(),
},
}
}
/// The binding with the greatest `key` tuple per group.
pub fn max_by(
group: impl IntoIterator<Item = Var>,
key: impl IntoIterator<Item = Var>,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::Max {
key: key.into_iter().collect(),
},
}
}
/// Several reductions of each group in one pass ([`Agg::Many`]).
///
/// ```
/// use kleene_plan::{Aggregate, Plan, Reduce, Type};
/// let mut p = Plan::new();
/// let sale = p.input_typed("sale", &[Type::Str, Type::I64]);
/// let sums = p.derived_typed("sums", &[Type::Str, Type::U64, Type::I64, Type::F64, Type::I64]);
/// let [who, x, n, s, m, hi] = ["Who", "X", "N", "S", "M", "Hi"].map(|v| p.var(v));
/// let agg = Aggregate::many(
/// [who],
/// [Reduce::count(n), Reduce::sum(x, s), Reduce::avg(x, m), Reduce::max(x, hi)],
/// );
/// let head = kleene_plan::Atom {
/// rel: sums,
/// terms: [who, n, s, m, hi].map(kleene_plan::Term::Var).to_vec(),
/// };
/// let body = kleene_plan::Atom { rel: sale, terms: vec![who.into(), x.into()] };
/// p.aggregate(head, agg, [body]).unwrap();
/// ```
pub fn many(
group: impl IntoIterator<Item = Var>,
reduces: impl IntoIterator<Item = Reduce>,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::Many {
reduces: reduces.into_iter().collect(),
times: Vec::new(),
},
}
}
/// Each binding weighed by the product of the count variables `times` (of counted body
/// atoms) in [`Agg::Many`]'s counts, sums and means of values that are not distinct.
pub fn times(mut self, times: impl IntoIterator<Item = Var>) -> Self {
if let Agg::Many { times: t, .. } = &mut self.agg {
t.extend(times);
}
self
}
/// `out` = the position of each binding's `key` tuple among its group's distinct key
/// tuples in rising order, from 0 ([`Agg::Rank`]).
///
/// ```
/// use kleene_plan::{Aggregate, Atom, Plan, Term};
/// let mut p = Plan::new();
/// let item = p.input("item", 2);
/// let pos = p.derived("pos", 3);
/// let (g, k, n) = (p.var("G"), p.var("K"), p.var("N"));
/// let at = |rel, vs: &[kleene_plan::Var]| Atom { rel, terms: vs.iter().map(|&v| Term::Var(v)).collect() };
/// let r = p.aggregate(at(pos, &[g, k, n]), Aggregate::rank([g], [k], n), [at(item, &[g, k])]).unwrap();
/// assert_eq!(p.show_rule(r), "pos(G, K, N) :- N = rank (K) by (G): item(G, K).");
/// ```
pub fn rank(
group: impl IntoIterator<Item = Var>,
key: impl IntoIterator<Item = Var>,
out: Var,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::Rank {
key: key.into_iter().collect(),
out,
},
}
}
/// `out` = the number of each group's set of distinct `of` tuples in the table of sets
/// `table` ([`Plan::sets`], [`Agg::SetNumber`]). The table gives each distinct set one
/// number, from 0: the sets new when the numbering is computed in rising order of their
/// sorted members, numbered on from the count so far, so the same facts give the same
/// numbers on every run. Without recursion through the table it runs as it stands;
/// with it, as a group of [`Plan::rounds`] that lists the table.
///
/// ```
/// use kleene_plan::{Aggregate, Atom, Plan, Term};
/// let mut p = Plan::new();
/// let member = p.input("member", 2);
/// let state = p.sets("state", 2, None);
/// let id = p.derived("id", 2);
/// let (k, x, n) = (p.var("K"), p.var("X"), p.var("N"));
/// let at = |rel, vs: &[kleene_plan::Var]| Atom { rel, terms: vs.iter().map(|&v| Term::Var(v)).collect() };
/// let agg = Aggregate::set_number([k], [x], n, state);
/// let r = p.aggregate(at(id, &[k, n]), agg, [at(member, &[k, x])]).unwrap();
/// assert_eq!(p.show_rule(r), "id(K, N) :- N = set (X) by (K) in state: member(K, X).");
/// ```
pub fn set_number(
group: impl IntoIterator<Item = Var>,
of: impl IntoIterator<Item = Var>,
out: Var,
table: RelId,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::SetNumber {
of: of.into_iter().collect(),
out,
table,
},
}
}
/// The groups where `of` takes exactly one distinct value.
pub fn exactly_one(
group: impl IntoIterator<Item = Var>,
of: impl IntoIterator<Item = Var>,
) -> Self {
Aggregate {
group: group.into_iter().collect(),
agg: Agg::One {
of: of.into_iter().collect(),
},
}
}
}
/// `head :- body`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rule {
/// The head.
pub head: Atom,
/// The positive body atoms.
pub body: Vec<Atom>,
/// The negated body atoms: each must not hold (its relation is complete in a lower
/// stratum; its variables are bound by the positive atoms).
pub negated: Vec<Atom>,
/// The conditions: each must hold over the values the positive atoms bind.
pub conds: Vec<Cond>,
/// The computed values, in an order in which each one's operands are bound (by the
/// positive atoms or a compute before it): each binds its variable, or tests it where
/// it is bound already.
pub computes: Vec<Compute>,
/// For an aggregate rule, how the body's bindings are grouped and reduced.
pub agg: Option<Aggregate>,
/// For a fold rule ([`Plan::fold`]: sum, average), how the body's bindings are grouped
/// and folded.
pub fold: Option<Fold>,
}
/// How a client takes a counted relation's rows ([`crate::Output::rows_as`]): the bag (each row
/// its count's times) or the distinct rows (each once).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Rows {
/// Each row as often as it holds (Cypher's and ISO GQL's default).
#[default]
Bag,
/// Each distinct row once.
Distinct,
}
/// How a fold rule folds a group's values ([`Fold`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FoldOp {
/// The sum (of the same type as the values: u64, i64, f64; an integer sum that leaves
/// its type is refused when the run reaches it).
Sum,
/// The mean, an f64.
Avg,
/// The number of the group's distinct bindings, each weighed by the product of the
/// fold's `times` (1 when there are none): a u64. Made by [`Plan::count_rule`].
Count,
}
/// A fold: the body's bindings grouped by `group`, and `of`'s values of each group's
/// distinct bindings folded by `op` into `out`. Nulls are skipped (a group of only nulls
/// gives no fact). Stratified like an [`Aggregate`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fold {
/// The grouping variables (each in the head); empty: one group of every binding.
pub group: Vec<Var>,
/// The fold.
pub op: FoldOp,
/// The variable folded (a u64, i64 or f64 one).
pub of: Var,
/// The head variable that takes the result; no body atom binds it.
pub out: Var,
/// For [`FoldOp::Count`]: the count columns of the counted body atoms, multiplied
/// per binding (empty for a sum or a mean).
pub times: Vec<Var>,
}
impl Fold {
/// `out` = the sum of `of` over each group's distinct bindings.
pub fn sum(group: impl IntoIterator<Item = Var>, of: Var, out: Var) -> Self {
Fold {
group: group.into_iter().collect(),
op: FoldOp::Sum,
of,
out,
times: Vec::new(),
}
}
/// The fold with each binding weighed by the product of `times` (u64 variables a body
/// atom binds: the counts of counted atoms, say): a sum of `of` times the weight, a mean
/// over the weights' sum. With no `times`, each binding once.
pub fn times(mut self, times: impl IntoIterator<Item = Var>) -> Self {
self.times = times.into_iter().collect();
self
}
/// `out` = the mean of `of` over each group's distinct bindings (an f64 column).
pub fn avg(group: impl IntoIterator<Item = Var>, of: Var, out: Var) -> Self {
Fold {
group: group.into_iter().collect(),
op: FoldOp::Avg,
of,
out,
times: Vec::new(),
}
}
}
impl Rule {
/// Whether the rule groups its body's bindings (an aggregate or a fold): it reads its
/// body relations whole, so they must be complete in lower strata.
pub fn groups(&self) -> bool {
self.agg.is_some() || self.fold.is_some()
}
/// The variables the positive atoms bind, in order of first appearance, then those the
/// computes bind.
pub fn vars(&self) -> Vec<Var> {
let mut out = Vec::new();
for v in self
.body
.iter()
.flat_map(Atom::vars)
.chain(self.computes.iter().map(|c| c.out))
{
if !out.contains(&v) {
out.push(v);
}
}
out
}
/// The compute made for an expression of a [`Test`] whose variable is `v`, if any.
pub fn test_compute(&self, v: Var) -> Option<&Compute> {
self.computes.iter().find(|c| c.of_test && c.out == v)
}
/// Whether every condition holds under `binding`.
pub fn conds_hold(&self, binding: &[(Var, Value)]) -> bool {
self.conds.iter().all(|c| c.holds(binding))
}
}
/// `atom` with its variables replaced by their values in `binding` (variable, value).
pub fn instantiate(atom: &Atom, binding: &[(Var, Value)]) -> Vec<Value> {
atom.terms
.iter()
.map(|t| t.value(binding).expect("a bound variable"))
.collect()
}
/// What a plan knows of a relation.
#[derive(Clone, Debug)]
pub struct RelInfo {
/// The name.
pub name: String,
/// The number of columns.
pub arity: usize,
/// Input or derived.
pub kind: RelKind,
}
/// A plan: relations (by number, with their width and kind), variables, rules. Clients
/// lower their queries onto it (the Datalog rule builder, GQL); nothing here knows their
/// text or types. A rule is a join of its positive atoms, filtered by its conditions and
/// negated atoms, projected to its head (or grouped and reduced, for an aggregate rule);
/// rules over their own relations recurse to a fixed point.
///
/// ```
/// use kleene_plan::{Atom, Plan, Term};
/// let mut p = Plan::new();
/// let entry = p.input("entry", 1);
/// let calls = p.input("calls", 2);
/// let reach = p.derived("reach", 1);
/// let (f, g) = (p.var("F"), p.var("G"));
/// let at = |rel, vs: &[kleene_plan::Var]| Atom { rel, terms: vs.iter().map(|&v| Term::Var(v)).collect() };
/// p.rule(at(reach, &[f]), [at(entry, &[f])]).unwrap();
/// let step = p.rule(at(reach, &[g]), [at(reach, &[f]), at(calls, &[f, g])]).unwrap();
/// assert_eq!(p.show_rule(step), "reach(G) :- reach(F), calls(F, G).");
/// ```
#[derive(Clone, Debug, Default)]
pub struct Plan {
rels: Vec<RelInfo>,
vars: Vec<String>,
rules: Vec<Rule>,
rounds: Vec<Vec<(RelId, Part)>>,
walks: Vec<Walk>,
calls: Vec<Call>,
/// The column types of the relations declared with types (the rest are all `U64`).
types: std::collections::HashMap<RelId, Vec<Type>>,
/// The string constants ([`Plan::str`]), each once.
strings: Vec<String>,
/// The lists of [`Cond::OneOf`] ([`Plan::list`]), by [`ListId`].
pub(crate) lists: Vec<List>,
/// Per rule, the types of its variables (empty while the plan has no typed relation).
var_types: Vec<Vec<(Var, Type)>>,
/// The counted relations ([`Plan::derived_counted`], [`Plan::input_counted`]).
counted: Vec<RelId>,
/// The derived relations whose facts no one reads but the plan's rules
/// ([`Plan::internal`]).
internal: Vec<RelId>,
/// For a plan resolved for a run: the sets of string ids of its text tests (a bit per
/// id), each named by its place in the resolved [`Cond::Text`].
pub(crate) text_sets: Vec<Vec<u64>>,
/// The inputs that are empty where the catalog lacks their name
/// ([`Plan::input_or_empty`]).
pub(crate) optional: Vec<RelId>,
/// The relations of the catalog's schema ([`Plan::schema`]).
pub(crate) schema: Option<crate::Schema>,
/// The tables of sets ([`Plan::sets`]) and their limits.
sets: Vec<(RelId, u64)>,
}
/// The default limit of a table of sets ([`Plan::sets`]): one million sets.
pub const DEFAULT_SET_LIMIT: u64 = 1000000;
pub use kleene_graph::{Hops, Shortest};
/// The most shortest paths one [`Plan::shortest`] relation may hold (ALL SHORTEST can
/// grow exponentially with the graph's size).
pub const SHORTEST_PATHS_LIMIT: usize = 1 << 24;
/// A relation given by walks of bounded length ([`Plan::walk`]): the ends of the walks
/// along `edge` from the vertices of `from` whose number of edges lies in `hops`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Walk {
/// The relation: one column (the ends), or two (the start, a vertex of `from`; the end).
pub rel: RelId,
/// The starts (one column).
pub from: RelId,
/// The edges (two columns).
pub edge: RelId,
/// Along or against the edges.
pub way: crate::Way,
/// How many edges.
pub hops: Hops,
/// `Some`: the relation holds shortest paths as vertex lists ([`Plan::shortest`]).
pub shortest: Option<Shortest>,
/// The relation holds the number of walks per row ([`Plan::walk_counted`]).
pub counted: bool,
}
/// A graph algorithm whose answer is a relation ([`Plan::procedure`]), run by a
/// kleene-graph kernel on the edges of a two-column relation (vertices `0..n`, `n` one past
/// the highest vertex of an edge, or the graph's size). Scores are floats as order-keeping
/// codes ([`crate::Type::F64`]'s: `Type::F64.decode(code, None)`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Procedure {
/// (vertex, score): PageRank (damping 0.85, GAP's tolerance; [`kleene_graph::pagerank`]).
PageRank,
/// (vertex, component): weakly connected components, a component named by its least
/// vertex ([`kleene_graph::GraphBackend::components_of`]).
WeakComponents,
/// (vertex, component): strongly connected components, named by their least vertex
/// ([`kleene_graph::GraphBackend::scc_of`]).
StrongComponents,
/// (vertex, distance) for each vertex reached from `source`: shortest paths, every
/// edge of weight 1, or the weights of `weights` ((from, to, weight) rows, the least
/// of repeats) ([`kleene_graph::GraphBackend::sssp_of`]).
Sssp {
/// The source vertex.
source: Value,
/// The edge weights; `None`: 1 each.
weights: Option<RelId>,
},
/// (vertex, score): betweenness centrality with every vertex a source (Brandes;
/// [`kleene_graph::betweenness`]).
Betweenness,
/// (count): the triangles of the graph with its edges taken both ways and its
/// self-loops left out, each once ([`kleene_graph::triangles`]).
Triangles,
/// (vertex, score): harmonic centrality, the sum of 1 / d over the vertices a vertex
/// reaches along out-edges, d the fewest edges: exact ([`kleene_graph::harmonic`]) or
/// estimated ([`kleene_graph::harmonic_estimate`]), as `mode` says.
Harmonic {
/// Exact, estimated, or chosen by the vertex count.
mode: HarmonicMode,
},
/// (source, target, support): the k-truss of the graph with its edges taken both ways
/// and its self-loops left out, each kept edge once (source below target) with the
/// triangles of the truss it sits in ([`kleene_graph::ktruss`]).
KTruss {
/// `k`: every kept edge sits in at least `k - 2` triangles of the truss.
k: u32,
},
/// (source, target, truss): the truss number of every edge of the graph with its edges
/// taken both ways and its self-loops left out, each edge once (source below target):
/// the largest k whose k-truss holds it, 2 for an edge in no triangle
/// ([`kleene_graph::truss_numbers`]).
TrussNumbers,
/// (vertex): a maximal independent set of the graph with its edges taken both ways and
/// its self-loops left out, fixed by `seed` ([`kleene_graph::mis`]).
Mis {
/// The seed of the vertices' priorities.
seed: u64,
},
/// (from, to, weight) for each edge of a minimum spanning forest, the edges taken both
/// ways ([`kleene_graph::spanning_forest`], Borůvka's rounds): every edge of weight 1,
/// or the weights of `weights` ((from, to, weight) rows, the least of repeats; a
/// [`crate::Type::F64`] weight column gives float weights, a [`crate::Type::I64`] one
/// signed weights, negative ones too, and the relation's third
/// column must be of the weights' type). The total is the sum of the weights.
SpanningForest {
/// The edge weights; `None`: 1 each.
weights: Option<RelId>,
},
/// (flow): the value of a maximum flow from `source` to `target`, each edge an arc of
/// capacity 1, or of the capacities of `capacities` ((from, to, capacity) rows, repeats
/// summed; unsigned, or [`crate::Type::F64`] for float capacities and a float flow,
/// the relation's column then of that type) ([`kleene_graph::max_flow`],
/// [`kleene_graph::max_flow_f64`]). A whole value past `u64` is refused.
MaxFlow {
/// The source vertex.
source: Value,
/// The target vertex.
target: Value,
/// The arc capacities; `None`: 1 each.
capacities: Option<RelId>,
},
}
impl Procedure {
/// The number of columns of its relation.
pub fn arity(&self) -> usize {
match self {
Procedure::Triangles | Procedure::Mis { .. } | Procedure::MaxFlow { .. } => 1,
Procedure::KTruss { .. } | Procedure::TrussNumbers => 3,
Procedure::SpanningForest { .. } => 3,
_ => 2,
}
}
/// The columns of its relation that are vertices (the rest are values: a score, a
/// distance, a component's name is a vertex too).
pub fn vertex_columns(&self) -> &'static [usize] {
match self {
Procedure::Triangles | Procedure::MaxFlow { .. } => &[],
Procedure::WeakComponents
| Procedure::StrongComponents
| Procedure::KTruss { .. }
| Procedure::TrussNumbers
| Procedure::SpanningForest { .. } => &[0, 1],
_ => &[0],
}
}
/// Its name.
pub fn name(&self) -> &'static str {
match self {
Procedure::PageRank => "pagerank",
Procedure::WeakComponents => "weak components",
Procedure::StrongComponents => "strong components",
Procedure::Sssp { .. } => "sssp",
Procedure::Betweenness => "betweenness",
Procedure::Triangles => "triangle count",
Procedure::Harmonic { .. } => "harmonic centrality",
Procedure::KTruss { .. } => "k-truss",
Procedure::TrussNumbers => "truss numbers",
Procedure::Mis { .. } => "maximal independent set",
Procedure::SpanningForest { .. } => "spanning forest",
Procedure::MaxFlow { .. } => "maximum flow",
}
}
/// The relation of its edge weights, if it takes one.
pub fn weights(&self) -> Option<RelId> {
match *self {
Procedure::Sssp { weights, .. } | Procedure::SpanningForest { weights } => weights,
Procedure::MaxFlow { capacities, .. } => capacities,
_ => None,
}
}
/// Whether column `c` holds float codes.
pub fn is_float(&self, c: usize) -> bool {
c == 1
&& matches!(
self,
Procedure::PageRank | Procedure::Betweenness | Procedure::Harmonic { .. }
)
}
}
/// An argument of a procedure call after its edge relation, as a client read it: a word
/// (`exact`) or a whole number (`4`). [`Procedure::from_args`] gives it its meaning.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProcArg<'a> {
/// A word.
Word(&'a str),
/// A whole number.
Number(u64),
/// The (from, to, value) relation of an edge property: what a client maps a word to at
/// an argument [`Procedure::property_arg`] names (weights, capacities). Its value type
/// is checked by [`Plan::procedure`].
Values(RelId),
}
/// The kinds [`Procedure::from_args`] makes and the arguments each takes after the edge
/// relation.
const KINDS: [(&str, &str); 11] = [
("pagerank", ""),
("wcc", ""),
("scc", ""),
("betweenness", ""),
("triangles", ""),
("harmonic", "[, auto | exact | estimate [, log2Registers]]"),
("ktruss", ", k"),
("mis", " [, seed]"),
("trussnumbers", ""),
("msf", " [, weightKey]"),
("maxflow", ", source, target [, capacityKey]"),
];
/// [`Procedure::Mis`]'s seed when a call gives none.
pub const MIS_DEFAULT_SEED: u64 = 0;
impl Procedure {
/// The arguments procedure `kind` takes after its edge relation, as a usage text
/// (`", k"`), for the kinds [`Procedure::from_args`] makes; `None` for the others.
pub fn usage(kind: &str) -> Option<&'static str> {
KINDS.iter().find(|k| k.0 == kind).map(|k| k.1)
}
/// Whether argument `i` (after the edge relation) of procedure `kind` names an edge
/// property: a client gives it as [`ProcArg::Values`], the property's relation.
pub fn property_arg(kind: &str, i: usize) -> bool {
matches!((kind, i), ("msf", 0) | ("maxflow", 2))
}
/// The procedure `kind` from the arguments of a call after its edge relation, with
/// every default and every check of them:
///
/// | kind | arguments | default |
/// |---|---|---|
/// | `pagerank`, `wcc`, `scc`, `betweenness`, `triangles`, `trussnumbers` | none | |
/// | `harmonic` | `[auto \| exact \| estimate [, log2Registers]]` (`hyperball` for `estimate`) | `auto`: exact up to [`HARMONIC_EXACT_MAX`] vertices, HyperBall with 2^7 registers above; `estimate` 2^7 registers; 4 to 16 |
/// | `ktruss` | `k` (a whole number to `u32::MAX`) | none: k is given |
/// | `mis` | `[seed]` | [`MIS_DEFAULT_SEED`] |
/// | `msf` | `[weightKey]` ([`ProcArg::Values`]) | every edge of weight 1 |
/// | `maxflow` | `source, target [, capacityKey]` ([`ProcArg::Values`]) | every edge of capacity 1 |
///
/// `Ok(None)` for a kind not made here (`sssp`, whose weights are a relation the client
/// finds); a [`PlanError::Program`] naming the usage for arguments that do not fit.
pub fn from_args(kind: &str, args: &[ProcArg<'_>]) -> Result<Option<Procedure>> {
let Some(usage) = Procedure::usage(kind) else {
return Ok(None);
};
let refuse = |why: String| -> Result<Option<Procedure>> {
Err(PlanError::Program(format!("{kind}(edges{usage}): {why}")))
};
let most = match kind {
"harmonic" => 2,
"ktruss" | "mis" | "msf" => 1,
"maxflow" => 3,
_ => 0,
};
if args.len() > most {
return refuse("too many arguments".into());
}
Ok(Some(match kind {
"pagerank" => Procedure::PageRank,
"wcc" => Procedure::WeakComponents,
"scc" => Procedure::StrongComponents,
"betweenness" => Procedure::Betweenness,
"triangles" => Procedure::Triangles,
"trussnumbers" => Procedure::TrussNumbers,
"harmonic" => {
let registers = match args.get(1) {
None => None,
Some(&ProcArg::Number(b)) if (4..=16).contains(&b) => Some(b as u8),
Some(&ProcArg::Number(b)) => {
return refuse(format!("2^4 to 2^16 registers, not 2^{b}"));
}
Some(_) => return refuse("log2Registers is a number".into()),
};
match args.first() {
None => Procedure::Harmonic {
mode: HarmonicMode::Auto,
},
Some(ProcArg::Word(m)) => match m.to_ascii_lowercase().as_str() {
"auto" if registers.is_none() => Procedure::Harmonic {
mode: HarmonicMode::Auto,
},
"exact" if registers.is_none() => Procedure::Harmonic {
mode: HarmonicMode::Exact,
},
"estimate" | "hyperball" => Procedure::Harmonic {
mode: HarmonicMode::Estimate {
log2_registers: registers.unwrap_or(
kleene_graph::HyperBallOptions::default().log2_registers,
),
},
},
_ => {
return refuse(format!(
"the mode is auto, exact or estimate (registers only for \
estimate), not `{m}`"
));
}
},
Some(_) => return refuse("the mode is auto, exact or estimate".into()),
}
}
"ktruss" => match args.first() {
Some(&ProcArg::Number(k)) => match u32::try_from(k) {
Ok(k) => Procedure::KTruss { k },
Err(_) => return refuse(format!("k {k} is past u32")),
},
Some(_) => return refuse("k is a number".into()),
None => return refuse("k is missing".into()),
},
"mis" => match args.first() {
None => Procedure::Mis {
seed: MIS_DEFAULT_SEED,
},
Some(&ProcArg::Number(seed)) => Procedure::Mis { seed },
Some(_) => return refuse("the seed is a number".into()),
},
"msf" => match args.first() {
None => Procedure::SpanningForest { weights: None },
Some(&ProcArg::Values(w)) => Procedure::SpanningForest { weights: Some(w) },
Some(_) => return refuse("the weight is an edge property's key".into()),
},
"maxflow" => {
let (Some(&ProcArg::Number(source)), Some(&ProcArg::Number(target))) =
(args.first(), args.get(1))
else {
return refuse("a source and a target vertex".into());
};
let capacities = match args.get(2) {
None => None,
Some(&ProcArg::Values(c)) => Some(c),
Some(_) => return refuse("the capacity is an edge property's key".into()),
};
Procedure::MaxFlow {
source,
target,
capacities,
}
}
_ => unreachable!("every kind of KINDS is made above"),
}))
}
}
/// How [`Procedure::Harmonic`] gets its scores.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HarmonicMode {
/// Exact on graphs of at most [`HARMONIC_EXACT_MAX`] vertices, estimated with the
/// default registers above.
#[default]
Auto,
/// A search from every vertex ([`kleene_graph::harmonic`]).
Exact,
/// HyperBall ([`kleene_graph::harmonic_estimate`]) with `2^log2_registers` registers a
/// counter (4 to 16; [`kleene_graph::HyperBallOptions`]'s default is 7).
Estimate {
/// `b`: `2^b` registers a counter.
log2_registers: u8,
},
}
/// [`HarmonicMode::Auto`] is exact up to this many vertices (a search from every vertex
/// takes seconds there) and estimated above.
pub const HARMONIC_EXACT_MAX: usize = 1 << 16;
/// A relation given by a graph algorithm ([`Plan::procedure`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Call {
/// The relation.
pub rel: RelId,
/// The edges (two columns).
pub edge: RelId,
/// The algorithm.
pub procedure: Procedure,
}
/// How a relation of a stratum of rounds ([`Plan::rounds`]) goes from round to round.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Part {
/// Its facts are kept: each round adds to them (it only grows).
Keep,
/// It is made afresh every round from that round's facts.
Fresh,
}
impl Plan {
/// An empty plan.
pub fn new() -> Self {
Plan::default()
}
fn relation(&mut self, name: &str, arity: usize, kind: RelKind) -> RelId {
assert!(
arity > 0 || kind != RelKind::External,
"an external relation has at least one column"
);
let id = RelId(self.rels.len() as u32);
self.rels.push(RelInfo {
name: name.into(),
arity,
kind,
});
id
}
fn typed(&mut self, name: &str, types: &[Type], kind: RelKind) -> RelId {
let id = self.relation(name, types.len(), kind);
self.types.insert(id, types.to_vec());
id
}
/// A relation given by an input whose columns have `types` (one per column). Its inputs
/// are read by type: Arrow strings (`Utf8`, `LargeUtf8`, `Utf8View`, dictionaries of
/// them), signed and unsigned integers into [`Type::I64`], `Float64`/`Float32`,
/// `Boolean`, nulls in every type but [`Type::U64`]. Empty `types`: a flag, as
/// [`Plan::input`] of no column.
pub fn input_typed(&mut self, name: &str, types: &[Type]) -> RelId {
self.typed(name, types, RelKind::Input)
}
/// A relation derived by rules whose columns have `types`. Empty `types`: a flag, as
/// [`Plan::derived`] of no column.
pub fn derived_typed(&mut self, name: &str, types: &[Type]) -> RelId {
self.typed(name, types, RelKind::Derived)
}
/// A relation answered by an [`crate::External`] whose columns have `types`; the
/// external hands and takes codes ([`Type::encode`]). A [`Type::Str`] column is refused
/// when a run starts (its codes are the run's). Panics when `types` is empty or longer
/// than 64.
pub fn external_typed(&mut self, name: &str, types: &[Type]) -> RelId {
assert!(
types.len() <= 64,
"an external relation has at most 64 columns"
);
self.typed(name, types, RelKind::External)
}
/// A relation derived with a count per row: columns of `types`, then a u64 count. A
/// row stands for that many matches (a bag kept as one row per distinct tuple). It is
/// given by [`Plan::count_rule`] rules or by [`Plan::walk_counted`]; an ordinary rule
/// reads it as any relation (its count a column), so reading it without its count is
/// the distinct rows. [`crate::Output::expand`] repeats each row its count's times.
pub fn derived_counted(&mut self, name: &str, types: &[Type]) -> RelId {
let mut t = types.to_vec();
t.push(Type::U64);
let r = self.typed(name, &t, RelKind::Derived);
self.counted.push(r);
r
}
/// An input relation with a count per row: columns of `types`, then a u64 count (as
/// [`Plan::derived_counted`]; edges with parallel edges, say). Two rows of one tuple
/// add up where a counting rule reads them, as a union of bags does.
pub fn input_counted(&mut self, name: &str, types: &[Type]) -> RelId {
let mut t = types.to_vec();
t.push(Type::U64);
let r = self.typed(name, &t, RelKind::Input);
self.counted.push(r);
r
}
/// A table of sets of `arity` columns (`arity >= 2`), all u64: column 0 is a set's
/// number (from 0), the others are one element. It gives each distinct set that rules
/// number into it ([`Aggregate::set_number`]) one number, and holds each numbered set
/// once, a row `(n, element..)` per element. Rules read it as any relation; no rule
/// derives it. `limit` is the most sets it may number (`None`: [`DEFAULT_SET_LIMIT`]);
/// a run that would number one more stops with [`crate::PlanError::SetLimit`]. Panics
/// when `arity < 2`.
pub fn sets(&mut self, name: &str, arity: usize, limit: Option<u64>) -> RelId {
assert!(arity >= 2, "a table of sets has a number and an element");
let id = self.relation(name, arity, RelKind::Derived);
self.sets.push((id, limit.unwrap_or(DEFAULT_SET_LIMIT)));
id
}
/// [`Plan::sets`] with column types, one per column: `types[0]` (the number) is
/// [`Type::U64`], the rest are the element's. Panics when `types` has fewer than two
/// columns or the first is not u64.
pub fn sets_typed(&mut self, name: &str, types: &[Type], limit: Option<u64>) -> RelId {
assert!(
types.len() >= 2,
"a table of sets has a number and an element"
);
assert!(
types[0] == Type::U64,
"the number of a table of sets is a u64"
);
let id = self.typed(name, types, RelKind::Derived);
self.sets.push((id, limit.unwrap_or(DEFAULT_SET_LIMIT)));
id
}
/// The limit of table of sets `rel` ([`Plan::sets`]); `None` when `rel` is not one.
pub fn set_limit(&self, rel: RelId) -> Option<u64> {
self.sets.iter().find(|s| s.0 == rel).map(|s| s.1)
}
/// Whether `rel` carries a count per row (its last column).
pub fn is_counted(&self, rel: RelId) -> bool {
self.counted.contains(&rel)
}
/// Add a counting rule to a counted relation ([`Plan::derived_counted`]): the head's
/// last term is the count, a variable no body atom binds; the rest of the head is the
/// row. A row's count is the number of the body's distinct bindings that give it,
/// each binding weighed by the product of the counts of its counted body atoms (their
/// last terms): a join multiplies counts, a projection sums them, and several counting
/// rules of one relation add up (a union of bags). A body of uncounted atoms counts
/// each distinct binding once, so the matches of a pattern are counted by binding all
/// its parts. Stratified like an aggregate (no counting through recursion). Refused,
/// besides what [`Plan::fold`] refuses: a head relation not counted, a count term that
/// is not a fresh variable, a counted body atom whose count is not a variable of its
/// own.
///
/// ```
/// use kleene_plan::{Atom, Plan, Term, Type};
/// let mut p = Plan::new();
/// let edge = p.input("edge", 2);
/// let two = p.derived_counted("two", &[Type::U64, Type::U64]);
/// let (a, b, c, n) = (p.var("A"), p.var("B"), p.var("C"), p.var("N"));
/// let at = |rel, vs: &[kleene_plan::Var]| Atom { rel, terms: vs.iter().map(|&v| Term::Var(v)).collect() };
/// // the walks of two edges, counted per pair of ends (one per middle vertex)
/// let r = p.count_rule(at(two, &[a, c, n]), [at(edge, &[a, b]), at(edge, &[b, c])]).unwrap();
/// assert_eq!(p.show_rule(r), "two(A, C, N) :- N = count () by (A, C): edge(A, B), edge(B, C).");
/// ```
pub fn count_rule<L: Into<Literal>>(
&mut self,
head: Atom,
body: impl IntoIterator<Item = L>,
) -> Result<RuleId> {
let refuse = |m: String| Err(PlanError::Program(m));
let name = self
.rels
.get(head.rel.index())
.map_or(String::new(), |r| r.name.clone());
if !self.is_counted(head.rel) || self.rels[head.rel.index()].kind != RelKind::Derived {
return refuse(format!(
"a counting rule gives a derived counted relation, not `{name}`"
));
}
let body: Vec<Literal> = self.lower(body);
let Some(&Term::Var(out)) = head.terms.last() else {
return refuse(format!(
"the count of `{name}` (its last head term) is a variable"
));
};
let mut times: Vec<Var> = Vec::new();
for lit in &body {
if let Literal::Pos(a) = lit
&& self.is_counted(a.rel)
{
match a.terms.last() {
Some(&Term::Var(v))
if !times.contains(&v)
&& body
.iter()
.filter_map(Literal::atom)
.flat_map(|b| b.vars())
.filter(|&w| w == v)
.count()
== 1 =>
{
times.push(v)
}
_ => {
return refuse(format!(
"the count of a `{}` atom in a counting rule of `{name}` is a variable of its own",
self.rels[a.rel.index()].name
));
}
}
}
}
let group: Vec<Var> = head.terms[..head.terms.len() - 1]
.iter()
.filter_map(|t| match *t {
Term::Var(v) => Some(v),
Term::Const(_) => None,
})
.collect();
let fold = Fold {
group,
op: FoldOp::Count,
of: out,
out,
times,
};
let rule = self.checked(head, body, None, Some(fold))?;
self.push(rule)
}
/// The column types of `rel` (all [`Type::U64`] for a relation declared without).
pub fn types(&self, rel: RelId) -> Vec<Type> {
match self.types.get(&rel) {
Some(t) => t.clone(),
None => vec![Type::U64; self.rels[rel.index()].arity],
}
}
/// The type of column `i` of `rel`.
pub fn col_type(&self, rel: RelId, i: usize) -> Type {
self.types.get(&rel).map_or(Type::U64, |t| t[i])
}
/// Whether `rel` has a column of a type other than [`Type::U64`].
pub fn is_typed(&self, rel: RelId) -> bool {
self.types
.get(&rel)
.is_some_and(|t| t.iter().any(|&x| x != Type::U64))
}
/// Whether any relation has a column of a type other than [`Type::U64`].
pub fn has_types(&self) -> bool {
self.types
.values()
.any(|t| t.iter().any(|&x| x != Type::U64))
}
/// `c` coded as a value of type `ty`, the type of the place it meets (a column, or the
/// variable it is compared with): an unsigned integer for a u64, i64 or f64 place, a
/// signed one for an i64 or f64 place (a u64 one when it is not negative), a float for
/// an f64 place, a string for a str place ([`Plan::str`]), a boolean for a bool place.
/// Refused: any other pair, an integer outside the place's range, `i64::MAX` in an i64
/// place (the null's code). GQL codes its literals with it; so does `datalog!` its
/// literals (not its Rust values, which stay raw).
///
/// ```
/// use kleene_plan::{Constant, Plan, Term, Type};
/// let mut p = Plan::new();
/// assert_eq!(p.constant(&Constant::Int(-1), Type::I64).unwrap(), Term::int(-1));
/// assert_eq!(p.constant(&Constant::Uint(2), Type::F64).unwrap(), Term::float(2.0));
/// assert_eq!(p.constant(&Constant::Uint(7), Type::U64).unwrap(), Term::Const(7));
/// assert!(p.constant(&Constant::Int(-1), Type::U64).is_err());
/// assert!(p.constant(&Constant::Float(1.5), Type::I64).is_err());
/// ```
pub fn constant(&mut self, c: &Constant, ty: Type) -> Result<Term> {
let an = if matches!(ty, Type::I64 | Type::F64) {
"an"
} else {
"a"
};
let refuse = |what: String| Err(PlanError::Program(what));
let range =
|x: &dyn fmt::Display| refuse(format!("{x} is out of the range of {an} {ty} value"));
Ok(match (c, ty) {
(Constant::Uint(u), Type::U64) => Term::Const(*u),
(Constant::Int(i), Type::U64) if *i >= 0 => Term::Const(*i as Value),
(Constant::Uint(u), Type::I64) => match i64::try_from(*u) {
Ok(i) if i < i64::MAX => Term::int(i),
_ => return range(u),
},
(Constant::Int(i), Type::I64) if *i < i64::MAX => Term::int(*i),
(Constant::Int(i), Type::I64) => return range(i),
(Constant::Uint(u), Type::F64) => Term::float(*u as f64),
(Constant::Int(i), Type::F64) => Term::float(*i as f64),
(Constant::Float(f), Type::F64) => Term::float(*f),
(Constant::Bool(b), Type::Bool) => Term::bool(*b),
(Constant::Str(s), Type::Str) => self.str(s),
(c, ty) => return refuse(format!("{} compared with {an} {ty} value", c.kind())),
})
}
/// A string constant, for a [`Type::Str`] column or a comparison with a string
/// variable: the term holds the string's number in this plan (its place in
/// [`Plan::strings`]); a run reads it as the string.
pub fn str(&mut self, s: &str) -> Term {
let i = match self.strings.iter().position(|x| x == s) {
Some(i) => i,
None => {
self.strings.push(s.to_string());
self.strings.len() - 1
}
};
Term::Const(i as Value)
}
/// The string constants, by their number.
pub fn strings(&self) -> &[String] {
&self.strings
}
/// A list of constants for [`Cond::OneOf`] (`x in (k1, k2, ..)`), its members coded for
/// `ty`, the type of the value it is tested on: a constant as [`Plan::constant`] codes
/// it (a string through [`Plan::str`]), a raw value as it is. An empty list is a list
/// (no value is in it). Refused by the member's place (from 1): a constant that does
/// not fit `ty` (`list member 2: a string compared with a u64 value`), a raw value for
/// a str list (`list member 1: a Rust integer for a str value`).
///
/// ```
/// use kleene_plan::{ListMember, Plan, Type};
/// let mut p = Plan::new();
/// let l = p.list(Type::U64, [ListMember::from(1u64), ListMember::from(5u32)]).unwrap();
/// assert_eq!(p.list_of(l).members, [1, 5]);
/// assert!(p.list(Type::U64, [ListMember::from("x")]).is_err());
/// ```
pub fn list(
&mut self,
ty: Type,
members: impl IntoIterator<Item = ListMember>,
) -> Result<ListId> {
self.add_list(None, ty, members)
}
/// A list as [`Plan::list`] makes it, shown by `name` (the Rust path it was given by,
/// `names::CALLEES`) in a rule's text and a proof.
pub fn list_named(
&mut self,
name: &str,
ty: Type,
members: impl IntoIterator<Item = ListMember>,
) -> Result<ListId> {
self.add_list(Some(name.to_string()), ty, members)
}
fn add_list(
&mut self,
name: Option<String>,
ty: Type,
members: impl IntoIterator<Item = ListMember>,
) -> Result<ListId> {
let mut codes = Vec::new();
for (i, m) in members.into_iter().enumerate() {
let at = |m: String| PlanError::Program(format!("list member {}: {m}", i + 1));
codes.push(match m {
ListMember::Raw(_) if ty == Type::Str => {
return Err(at(format!("a Rust integer for a {ty} value")));
}
ListMember::Raw(v) => v,
ListMember::Const(c) => match self.constant(&c, ty) {
Ok(Term::Const(k)) => k,
Ok(Term::Var(_)) => unreachable!("a constant"),
Err(PlanError::Program(m)) => return Err(at(m)),
Err(e) => return Err(e),
},
});
}
let mut run = codes.clone();
run.sort_unstable();
run.dedup();
self.lists.push(List {
name,
ty,
members: codes,
run,
});
Ok(ListId(self.lists.len() as u32 - 1))
}
/// List `id` ([`Plan::list`]).
pub fn list_of(&self, id: ListId) -> &List {
&self.lists[id.index()]
}
/// The members of list `id` as text: `(1, 2, 3)`, each by the list's type; a named one
/// `names::CALLEES = ("memcpy", ..)`, its first 8 values and how many there are past.
pub fn show_list(&self, id: ListId) -> String {
let l = self.list_of(id);
let vals: Vec<String> = l
.members
.iter()
.take(if l.name.is_some() { 8 } else { usize::MAX })
.map(|&k| self.show_const(k, l.ty))
.collect();
let mut x = format!("({}", vals.join(", "));
if l.members.len() > vals.len() {
x.push_str(&format!(", .. {} values", l.members.len()));
}
x.push(')');
match &l.name {
Some(n) => format!("{n} = {x}"),
None => x,
}
}
/// A list as a rule's text writes it: its members, or `{name}` for a named one.
fn show_list_ref(&self, id: ListId) -> String {
let l = self.list_of(id);
match &l.name {
Some(n) => format!("{{{n}}}"),
None => {
let vals: Vec<String> = l
.members
.iter()
.map(|&k| self.show_const(k, l.ty))
.collect();
format!("({})", vals.join(", "))
}
}
}
/// `x in list` as a rule's text: `K in (1, 2)`, `!(K in (1, 2))`.
fn show_one_of(&self, x: String, list: ListId, not: bool) -> String {
let t = format!("{x} in {}", self.show_list_ref(list));
if not { format!("!({t})") } else { t }
}
/// The type of variable `v` in rule `r` ([`Type::U64`] for one no typed column binds).
pub fn var_type(&self, r: RuleId, v: Var) -> Type {
self.var_types
.get(r.index())
.and_then(|t| t.iter().find(|x| x.0 == v))
.map_or(Type::U64, |x| x.1)
}
/// The types of rule `r`'s variables (empty when the plan has no typed relation).
pub fn var_types(&self, r: RuleId) -> &[(Var, Type)] {
self.var_types.get(r.index()).map_or(&[], Vec::as_slice)
}
/// Mark derived relation `rel` internal: its client reads none of its facts, only the
/// plan's rules do. A run may then compute it only as far as those rules need: an
/// aggregate that reads it alone may read the rule that derives it instead (the next row
/// by a key, [`crate::Engine::next_rows`]), and its facts in the output may be missing.
pub fn internal(&mut self, rel: RelId) {
if !self.internal.contains(&rel) {
self.internal.push(rel);
}
}
/// Whether `rel` is internal ([`Plan::internal`]).
pub fn is_internal(&self, rel: RelId) -> bool {
self.internal.contains(&rel)
}
/// Rule `r` replaced by `rule`, its variables typed anew when the plan has types.
pub(crate) fn set_rule(&mut self, r: RuleId, rule: Rule) -> Result<()> {
let text = rule.conds.iter().any(|c| matches!(c, Cond::Text { .. }));
let types = if self.types.is_empty() && !text {
Vec::new()
} else {
self.type_rule(&rule)?
};
self.rules[r.index()] = rule;
if let Some(t) = self.var_types.get_mut(r.index()) {
*t = types;
} else {
while self.var_types.len() < r.index() {
self.var_types.push(Vec::new());
}
self.var_types.push(types);
}
Ok(())
}
/// Rule `r` taken out (the rules after it numbered one less).
pub(crate) fn remove_rule(&mut self, r: RuleId) {
self.rules.remove(r.index());
if r.index() < self.var_types.len() {
self.var_types.remove(r.index());
}
}
/// The rules with their variable types, for the run of a typed plan.
pub(crate) fn rules_mut(&mut self) -> &mut Vec<Rule> {
&mut self.rules
}
/// Give variable `v` of rule `r` type `ty` (a variable a run adds to a rule).
pub(crate) fn set_var_type(&mut self, r: RuleId, v: Var, ty: Type) {
if self.var_types.len() <= r.index() {
self.var_types.resize(r.index() + 1, Vec::new());
}
self.var_types[r.index()].push((v, ty));
}
/// A relation of `arity` columns given by an input. Of no column it is a flag: it holds
/// (its one empty row) or does not ([`crate::Inputs::flag`]).
pub fn input(&mut self, name: &str, arity: usize) -> RelId {
self.relation(name, arity, RelKind::Input)
}
/// A relation of `arity` columns 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. Panics when `arity` is 0 or above 64.
pub fn external(&mut self, name: &str, arity: usize) -> RelId {
assert!(arity <= 64, "an external relation has at most 64 columns");
self.relation(name, arity, RelKind::External)
}
/// A relation of `arity` columns derived by rules. Of no column it is a flag, which a
/// rule `flag() :- body.` makes hold when its body has a binding; its one fact (the
/// empty row) is read by an atom of no term, positive or negated
/// ([`crate::Output::holds`]).
///
/// ```
/// use kleene_plan::{Atom, Plan, Term};
/// let mut p = Plan::new();
/// let t = p.input("t", 1);
/// let has = p.derived("has", 0);
/// let x = p.var("X");
/// let r = p.rule(Atom { rel: has, terms: vec![] }, [Atom { rel: t, terms: vec![Term::Var(x)] }]).unwrap();
/// assert_eq!(p.show_rule(r), "has() :- t(X).");
/// ```
pub fn derived(&mut self, name: &str, arity: usize) -> RelId {
self.relation(name, arity, RelKind::Derived)
}
/// A variable (each call is a new variable; the name is for printing).
pub fn var(&mut self, name: &str) -> Var {
self.vars.push(name.into());
Var(self.vars.len() as u32 - 1)
}
/// A derived relation `name` of the edges of `edges` (two columns) that pass every one
/// of `tests`: the edges a walk may take when a predicate holds for each edge of it
/// (GQL's `all` / `none` over a path's edges), so the walk is a plain walk over it. A
/// test kept is one rule of its comparisons; one negated is a rule per comparison
/// negated (the AND false where one is false); several tests are their product.
pub fn edge_filter(&mut self, name: &str, edges: RelId, tests: &[EdgeTest]) -> Result<RelId> {
let (a, b) = (
self.var(&format!("{name} from")),
self.var(&format!("{name} to")),
);
let ends = |rel: RelId, v: Var| {
Literal::Pos(Atom {
rel,
terms: vec![Term::Var(a), Term::Var(b), Term::Var(v)],
})
};
let test = |v: Var, op: Cmp, c: Value| {
Literal::Cond(Cond::Cmp {
left: Term::Var(v),
op,
right: Term::Const(c),
})
};
let mut bodies: Vec<Vec<Literal>> = vec![vec![Literal::Pos(Atom {
rel: edges,
terms: vec![Term::Var(a), Term::Var(b)],
})]];
for (t, et) in tests.iter().enumerate() {
let vars: Vec<Var> = (0..et.cmps.len())
.map(|i| self.var(&format!("{name} value {t}.{i}")))
.collect();
let alts: Vec<Vec<Literal>> = if et.keep {
vec![
et.cmps
.iter()
.zip(&vars)
.flat_map(|(&(r, op, c), &v)| [ends(r, v), test(v, op, c)])
.collect(),
]
} else {
et.cmps
.iter()
.zip(&vars)
.map(|(&(r, op, c), &v)| vec![ends(r, v), test(v, op.negated(), c)])
.collect()
};
bodies = bodies
.iter()
.flat_map(|b| alts.iter().map(move |x| [b.clone(), x.clone()].concat()))
.collect();
}
let f = self.derived(name, 2);
for body in bodies {
self.rule(
Atom {
rel: f,
terms: vec![Term::Var(a), Term::Var(b)],
},
body,
)?;
}
Ok(f)
}
/// Add `head :- body`. Refused: an atom of a relation this plan does not hold or with
/// the wrong number of terms, 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> {
let body = self.lower(body);
let rule = self.checked(head, body, None, None)?;
self.push(rule)
}
/// The body with each [`Test`] made a [`Cond`]: a side that is an expression becomes a
/// variable of its own (named by the expression's text) and a [`Compute`] of it.
fn lower<L: Into<Literal>>(&mut self, body: impl IntoIterator<Item = L>) -> Vec<Literal> {
let mut out = Vec::new();
for l in body.into_iter().map(Into::into) {
let Literal::Test(t) = l else {
out.push(l);
continue;
};
let cond = match t {
Test::Cmp { left, op, right } => Cond::Cmp {
left: self.side(left, &mut out),
op,
right: self.side(right, &mut out),
},
Test::Within { x, lo, hi } => Cond::Within {
x: self.side(x, &mut out),
lo: self.side(lo, &mut out),
hi: self.side(hi, &mut out),
},
Test::OneOf { x, list, not } => Cond::OneOf {
x: self.side(x, &mut out),
list,
not,
},
};
out.push(Literal::Cond(cond));
}
out
}
/// A side of a [`Test`] as a term: itself, or the variable of a compute of it.
fn side(&mut self, e: Expr, out: &mut Vec<Literal>) -> Term {
if let Some(t) = e.term() {
return t;
}
let name = e.show(&|t| self.show_term(t));
let v = self.var(&name);
out.push(Literal::Compute(Compute {
out: v,
expr: e,
of_test: true,
ty: None,
}));
Term::Var(v)
}
/// Refuse an ordinary rule, aggregate or fold into a counted relation.
fn uncounted_head(&self, head: &Atom, fold: Option<&Fold>) -> Result<()> {
if self.is_counted(head.rel) && fold.is_none_or(|f| f.op != FoldOp::Count) {
return Err(PlanError::Program(format!(
"`{}` is counted: its rules are counting rules (Plan::count_rule)",
self.rels[head.rel.index()].name
)));
}
Ok(())
}
/// 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; one per
/// binding for an [`Aggregate::rank`]). Refused, besides what [`Plan::rule`] refuses: a
/// grouping variable missing from the head, a counted, key or single-valued variable no
/// positive atom binds, a count's or rank's result variable that a body atom binds or
/// that groups, 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_plan::{Aggregate, Atom, Plan, Term};
/// let mut p = Plan::new();
/// let calls = p.input("calls", 2);
/// let fan = p.derived("fan", 2);
/// let (f, g, n) = (p.var("F"), p.var("G"), p.var("N"));
/// let at = |rel, vs: [kleene_plan::Var; 2]| Atom { rel, terms: vs.map(Term::Var).to_vec() };
/// // fan(F, N) :- N = count (G) by (F): calls(F, G).
/// p.aggregate(at(fan, [f, n]), Aggregate::count([f], [g], n), [at(calls, [f, g])]).unwrap();
/// ```
pub fn aggregate<L: Into<Literal>>(
&mut self,
head: Atom,
agg: Aggregate,
body: impl IntoIterator<Item = L>,
) -> Result<RuleId> {
let body = self.lower(body);
let rule = self.checked(head, body, Some(agg), None)?;
self.push(rule)
}
/// Add a fold rule: `body`'s bindings grouped by `fold.group`, `fold.of`'s values of each
/// group's distinct bindings summed or averaged into `fold.out`. Refused, besides what
/// [`Plan::rule`] refuses: a grouping variable missing from the head, a folded variable
/// no positive atom binds or not of type u64, i64 or f64, a result variable a body atom
/// binds or that groups, a head variable neither grouped nor the result, a result column
/// of another type than the sum's (the values' type) or the mean's (f64). Stratified
/// like an aggregate.
///
/// ```
/// use kleene_plan::{Atom, Fold, Plan, Term, Type};
/// let mut p = Plan::new();
/// let sale = p.input_typed("sale", &[Type::Str, Type::F64]);
/// let total = p.derived_typed("total", &[Type::Str, Type::F64]);
/// let (who, amount, sum) = (p.var("Who"), p.var("Amount"), p.var("Sum"));
/// let at = |rel, vs: [kleene_plan::Var; 2]| Atom { rel, terms: vs.map(Term::Var).to_vec() };
/// let r = p.fold(at(total, [who, sum]), Fold::sum([who], amount, sum), [at(sale, [who, amount])]).unwrap();
/// assert_eq!(p.show_rule(r), "total(Who, Sum) :- Sum = sum (Amount) by (Who): sale(Who, Amount).");
/// ```
pub fn fold<L: Into<Literal>>(
&mut self,
head: Atom,
fold: Fold,
body: impl IntoIterator<Item = L>,
) -> Result<RuleId> {
if fold.op == FoldOp::Count {
return Err(PlanError::Program(
"a count of matches is a counting rule (Plan::count_rule)".into(),
));
}
let body = self.lower(body);
let rule = self.checked(head, body, None, Some(fold))?;
self.push(rule)
}
/// Add a checked rule: its variables typed when the plan has typed relations.
fn push(&mut self, rule: Rule) -> Result<RuleId> {
let text = rule.conds.iter().any(|c| match *c {
Cond::Text { .. } => true,
Cond::OneOf { list, .. } => self.list_of(list).ty != Type::U64,
_ => false,
});
let typed = rule.computes.iter().any(|c| c.ty.is_some());
let types = if self.types.is_empty() && !text && !typed {
Vec::new()
} else {
self.type_rule(&rule)?
};
self.rules.push(rule);
while self.var_types.len() + 1 < self.rules.len() {
self.var_types.push(Vec::new());
}
self.var_types.push(types);
Ok(RuleId(self.rules.len() as u32 - 1))
}
/// The types of `rule`'s variables, from the columns its atoms bind them to; refused:
/// a variable bound to columns of two types, a head column of another type than its
/// variable, a comparison of two types, a constant that does not fit its column or
/// comparison (a string constant this plan does not hold, `i64::MAX`).
pub(crate) fn type_rule(&self, rule: &Rule) -> Result<Vec<(Var, Type)>> {
let head = &self.rels[rule.head.rel.index()].name;
let err = |m: String| PlanError::Program(format!("in a rule of `{head}`: {m}"));
let refuse = |m: String| Err(err(m));
let mut out: Vec<(Var, Type)> = Vec::new();
let type_atom = |a: &Atom, out: &mut Vec<(Var, Type)>| -> Result<()> {
for (j, t) in a.terms.iter().enumerate() {
let ty = self.col_type(a.rel, j);
match *t {
Term::Var(v) => match out.iter().find(|x| x.0 == v) {
Some(&(_, was)) if was != ty => {
return Err(err(format!(
"variable {} is a {was} and a {ty} (column {j} of `{}`)",
self.var_name(v),
self.rels[a.rel.index()].name
)));
}
Some(_) => {}
None => out.push((v, ty)),
},
Term::Const(c) => self.fits(c, ty).map_err(err)?,
}
}
Ok(())
};
for a in &rule.body {
type_atom(a, &mut out)?;
}
// the computed values: of the type of the column their variable is bound to (a
// positive atom's, else the head's), else of their operands'
for c in &rule.computes {
let shown = || {
format!(
"`{} = {}`",
self.var_name(c.out),
c.expr.show(&|t| self.show_term(t))
)
};
// each term in its place: a string place (a string argument of a call) holds a
// str variable or a string constant, a number place a number
let mut ops: Vec<Type> = Vec::new();
let mut bad: Option<String> = None;
c.expr.each_term_placed(&mut |t, text| {
if bad.is_some() {
return;
}
match t {
Term::Var(v) => {
let ty = out.iter().find(|x| x.0 == v).map_or(Type::U64, |x| x.1);
if text && ty != Type::Str {
bad = Some(format!(
"the computed value {} reads {}, a {ty}, where a string goes",
shown(),
self.var_name(v)
));
} else if !text && !matches!(ty, Type::U64 | Type::I64 | Type::F64) {
bad = Some(format!(
"the computed value {} reads {}, a {ty} (u64, i64 or f64)",
shown(),
self.var_name(v)
));
} else if !text {
ops.push(ty);
}
}
Term::Const(k) if text => bad = self.fits(k, Type::Str).err(),
Term::Const(_) => {}
}
});
if let Some(m) = bad.or_else(|| call_places(&c.expr, c.expr.is_string()).err()) {
return refuse(if m.starts_with("the computed value") {
m
} else {
format!("the computed value {}: {m}", shown())
});
}
let float = ops.contains(&Type::F64);
if float && c.expr.has_bits() {
return refuse(format!(
"the computed value {} takes a bit operator over a float",
shown()
));
}
let string = c.expr.is_string();
let head = rule
.head
.terms
.iter()
.position(|&t| t == Term::Var(c.out))
.map(|j| self.col_type(rule.head.rel, j));
let ty = match out.iter().find(|x| x.0 == c.out) {
Some(&(_, ty)) => ty,
None if string => head.or(c.ty).unwrap_or(Type::Str),
None => head.or(c.ty).unwrap_or_else(|| operand_type(&ops)),
};
if string && ty != Type::Str {
return refuse(format!(
"the computed value {} is a string; its variable is a {ty}",
shown()
));
}
if c.expr.calls() && (float || ty == Type::F64) {
return refuse(format!(
"the computed value {} calls a string function in a float expression",
shown()
));
}
if !string && !matches!(ty, Type::U64 | Type::I64 | Type::F64) {
return refuse(format!(
"the computed value {} goes in a {ty} (u64, i64 or f64)",
shown()
));
}
if float && ty != Type::F64 {
return refuse(format!(
"the computed value {} is a float; its variable is a {ty}",
shown()
));
}
if ty == Type::F64 {
// (its constants are float codes)
let mut bad = None;
c.expr.each_term(&mut |t| {
if let Term::Const(k) = t
&& bad.is_none()
{
bad = self.fits(k, Type::F64).err();
}
});
if let Some(m) = bad {
return refuse(m);
}
}
if !out.iter().any(|x| x.0 == c.out) {
out.push((c.out, ty));
}
}
for a in &rule.negated {
type_atom(a, &mut out)?;
}
// the variables the aggregate makes
if let Some(Aggregate {
agg: Agg::Count { out: o, .. } | Agg::Rank { out: o, .. },
..
}) = &rule.agg
{
let ty = rule
.head
.terms
.iter()
.position(|&t| t == Term::Var(*o))
.map_or(Type::U64, |j| self.col_type(rule.head.rel, j));
if ty != Type::U64 && ty != Type::I64 {
let what = match rule.agg.as_ref().map(|a| &a.agg) {
Some(Agg::Rank { .. }) => "position",
_ => "count",
};
return refuse(format!(
"the {what} {} goes in a {ty} column (u64 or i64)",
self.var_name(*o)
));
}
out.push((*o, ty));
}
if let Some(Aggregate {
agg: Agg::SetNumber { of, out: o, table },
..
}) = &rule.agg
{
let name = &self.rels[table.index()].name;
for (j, &v) in of.iter().enumerate() {
let want = self.col_type(*table, j + 1);
let got = out.iter().find(|x| x.0 == v).map_or(Type::U64, |x| x.1);
if got != want {
return refuse(format!(
"the element {} is a {got}; column {} of the table of sets `{name}` is a {want}",
self.var_name(v),
j + 1
));
}
}
let ty = rule
.head
.terms
.iter()
.position(|&t| t == Term::Var(*o))
.map_or(Type::U64, |j| self.col_type(rule.head.rel, j));
if ty != Type::U64 {
return refuse(format!(
"the set number {} goes in a {ty} column (u64)",
self.var_name(*o)
));
}
out.push((*o, ty));
}
if let Some(Aggregate {
agg: Agg::Many { reduces, .. },
..
}) = &rule.agg
{
let head_ty = |v: Var, want: Type| {
rule.head
.terms
.iter()
.position(|&t| t == Term::Var(v))
.map_or(want, |j| self.col_type(rule.head.rel, j))
};
let mut made: Vec<(Var, Type)> = Vec::new();
for red in reduces {
let of = red
.of
.first()
.and_then(|&v| out.iter().find(|x| x.0 == v))
.map_or(Type::U64, |x| x.1);
let want = match red.op {
ReduceOp::Count => Type::U64,
ReduceOp::Avg => Type::F64,
ReduceOp::Sum | ReduceOp::Min | ReduceOp::Max => of,
};
let got = head_ty(red.out, want);
let fits = got == want || (red.op == ReduceOp::Count && got == Type::I64);
if !fits {
return refuse(format!(
"the reduction {} is a {want}; its head column is a {got}",
self.var_name(red.out)
));
}
if matches!(red.op, ReduceOp::Sum | ReduceOp::Avg)
&& !matches!(of, Type::U64 | Type::I64 | Type::F64)
{
return refuse(format!(
"the reduction {} sums a {of} (u64, i64 or f64)",
self.var_name(red.out)
));
}
made.push((red.out, got));
if let Some(h) = red.has {
made.push((h, Type::U64));
}
}
out.extend(made);
}
if let Some(f) = &rule.fold {
let ty = rule
.head
.terms
.iter()
.position(|&t| t == Term::Var(f.out))
.map_or(Type::U64, |j| self.col_type(rule.head.rel, j));
out.push((f.out, ty));
}
let ty_of = |v: Var| out.iter().find(|x| x.0 == v).map(|x| x.1);
for (j, t) in rule.head.terms.iter().enumerate() {
let ty = self.col_type(rule.head.rel, j);
match *t {
Term::Var(v) => {
if let Some(was) = ty_of(v)
&& was != ty
{
return refuse(format!(
"variable {} is a {was}; head column {j} is a {ty}",
self.var_name(v)
));
}
}
Term::Const(c) => self.fits(c, ty).map_err(err)?,
}
}
for c in &rule.conds {
if let Cond::Text { x, op, pat } = *c {
let xt = x.var().and_then(ty_of);
if xt != Some(Type::Str) {
return refuse(format!(
"`{}` tests a string variable, not {}",
op.words(),
self.show_cond(c)
));
}
match pat {
Term::Const(k) => self.fits(k, Type::Str).map_err(err)?,
Term::Var(_) => {
return refuse(format!(
"the pattern of `{}` is a string constant: {}",
op.words(),
self.show_cond(c)
));
}
}
continue;
}
if let Cond::OneOf { x, list, .. } = *c {
let xt = x.var().and_then(ty_of).unwrap_or(Type::U64);
let lt = self.list_of(list).ty;
if xt != lt {
let x = match x {
Term::Var(v) => rule.test_compute(v).map_or_else(
|| self.var_name(v).to_string(),
|c| c.expr.show(&|t| self.show_term(t)),
),
Term::Const(k) => k.to_string(),
};
return refuse(format!(
"`{x} in (..)`: a list of {lt} values tested on {x}, a {xt} value"
));
}
continue;
}
let terms = c.terms();
let vt: Vec<Type> = terms
.iter()
.filter_map(|t| t.var().and_then(ty_of))
.collect();
let Some(&ty) = vt.first() else { continue };
if let Some(&other) = vt.iter().find(|&&x| x != ty) {
return refuse(format!(
"a comparison of a {ty} and a {other}: {}",
self.show_cond(c)
));
}
for t in &terms {
if let Term::Const(k) = *t {
self.fits(k, ty).map_err(err)?;
}
}
}
Ok(out)
}
/// Whether constant `c` fits a column or comparison of type `ty`.
fn fits(&self, c: Value, ty: Type) -> std::result::Result<(), String> {
match ty {
Type::Str if c as usize >= self.strings.len() => Err(format!(
"constant {c} in a str place is not a string of this plan (Plan::str)"
)),
Type::Bool if c > 1 => Err(format!("constant {c} in a bool place")),
Type::I64 | Type::F64 if c == crate::typed::NULL => {
Err(format!("constant {c} in a {ty} place is the null's code"))
}
_ => Ok(()),
}
}
fn checked<L: Into<Literal>>(
&self,
head: Atom,
body: impl IntoIterator<Item = L>,
agg: Option<Aggregate>,
fold: Option<Fold>,
) -> Result<Rule> {
let body: Vec<Literal> = body.into_iter().map(Into::into).collect();
let refuse = |m: String| Err(PlanError::Program(m));
if head.rel.index() < self.rels.len() {
self.uncounted_head(&head, fold.as_ref())?;
}
// A typed client makes these two checks at compile time.
for a in std::iter::once(&head).chain(body.iter().filter_map(Literal::atom)) {
let Some(r) = self.rels.get(a.rel.index()) else {
return refuse(format!("relation {} is not in this plan", a.rel.index()));
};
if a.terms.len() != r.arity {
return refuse(format!(
"`{}` has {} columns; an atom of it gives {}",
r.name,
r.arity,
a.terms.len()
));
}
}
let info = &self.rels[head.rel.index()];
if self.walk_of(head.rel).is_some() || self.call_of(head.rel).is_some() {
return refuse(format!("`{}` is given by a walk, not rules", info.name));
}
if info.kind != RelKind::Derived {
return refuse(format!(
"`{}` is given, not derived; a rule cannot derive it",
info.name
));
}
if self.set_limit(head.rel).is_some() {
return refuse(format!(
"`{}` is a table of sets: no rule derives it; rules number into it (set number)",
info.name
));
}
if let Some(Aggregate {
agg: Agg::SetNumber { of, table, .. },
..
}) = &agg
{
let Some(t) = self.rels.get(table.index()) else {
return refuse(format!("relation {} is not in this plan", table.index()));
};
if self.set_limit(*table).is_none() {
return refuse(format!(
"`{}` numbers into `{}`, which is not a table of sets (Plan::sets)",
info.name, t.name
));
}
if of.len() + 1 != t.arity {
return refuse(format!(
"`{}` numbers sets of {} column{} into `{}`, whose elements have {}",
info.name,
of.len(),
if of.len() == 1 { "" } else { "s" },
t.name,
t.arity - 1
));
}
}
if info.arity == 0 && (agg.is_some() || fold.is_some()) {
return refuse(format!(
"`{}` has no column: an aggregate or fold has nothing to give it",
info.name
));
}
if body.is_empty() {
return refuse(format!(
"a rule for `{}` needs a body (facts come from inputs)",
info.name
));
}
let mut atoms = Vec::with_capacity(body.len());
let mut negated = Vec::new();
let mut conds = Vec::new();
let mut given = Vec::new();
for l in body {
match l {
Literal::Pos(a) => atoms.push(a),
Literal::Neg(a) => negated.push(a),
Literal::Cond(c) => conds.push(c),
Literal::Compute(c) => given.push(c),
Literal::Test(_) => {
return refuse("a test of expressions is lowered before it is checked".into());
}
}
}
if atoms.is_empty() {
return refuse(format!(
"a rule for `{}` needs a positive body atom",
info.name
));
}
let name = |v: Var| self.vars[v.0 as usize].as_str();
// The computes in an order in which each one's operands are bound: by the positive
// atoms, or by a compute before it.
let mut known: Vec<Var> = atoms.iter().flat_map(Atom::vars).collect();
let mut computes: Vec<Compute> = Vec::with_capacity(given.len());
while let Some(i) = given
.iter()
.position(|c| c.expr.vars().iter().all(|v| known.contains(v)))
{
let c = given.remove(i);
if !known.contains(&c.out) {
known.push(c.out);
}
computes.push(c);
}
if let Some(c) = given.first() {
let v = c
.expr
.vars()
.into_iter()
.find(|v| !known.contains(v))
.expect("an operand not bound");
return refuse(format!(
"variable {} of the computed value `{} = {}` of `{}` is bound by no positive atom or computed value",
name(v),
name(c.out),
c.expr.show(&|t| self.show_term(t)),
info.name
));
}
let bound = |v: Var| known.contains(&v);
// The head variables the rule gives: the body's, or what the aggregate keeps.
let gives = |v: Var| match &agg {
None if fold.is_some() => fold
.as_ref()
.is_some_and(|f| f.group.contains(&v) || f.out == v),
None => bound(v),
Some(a) => {
a.group.contains(&v)
|| match &a.agg {
Agg::Count { out, .. } => *out == v,
Agg::Min { .. } | Agg::Max { .. } => bound(v),
Agg::Rank { out, .. } => *out == v || bound(v),
Agg::SetNumber { out, .. } => *out == v,
Agg::One { of } => of.contains(&v),
Agg::Many { reduces, .. } => {
reduces.iter().any(|r| r.gives().any(|w| w == v))
}
}
}
};
for v in head.vars() {
if !gives(v) {
return refuse(match (&agg, &fold) {
(None, Some(_)) => format!(
"head variable {} of `{}` is neither grouped nor the fold's result",
name(v),
info.name
),
(None, None) => format!(
"head variable {} of `{}` is bound by no body atom",
name(v),
info.name
),
(Some(_), _) => format!(
"head variable {} of `{}` is neither grouped nor given by the aggregate",
name(v),
info.name
),
});
}
}
for a in &negated {
for v in a.vars() {
if !bound(v) {
return refuse(format!(
"variable {} of the negated `{}` is bound by no positive atom",
name(v),
self.rels[a.rel.index()].name
));
}
}
}
for c in &conds {
if let Cond::OneOf { list, .. } = c
&& list.index() >= self.lists.len()
{
return refuse(format!("list {} is not in this plan", list.index()));
}
for v in c.vars() {
if !bound(v) {
return refuse(format!(
"variable {} of a condition of `{}` is bound by no positive atom",
name(v),
info.name
));
}
}
}
if let Some(Aggregate {
group,
agg: Agg::Many { reduces, times },
}) = &agg
{
if reduces.is_empty() {
return refuse(format!("the aggregate of `{}` has no reduction", info.name));
}
let mut made: Vec<Var> = Vec::new();
for red in reduces {
let one = red.op != ReduceOp::Count;
if one && red.of.len() != 1 {
return refuse(format!(
"the reduction {} of `{}` reduces one variable",
name(red.out),
info.name
));
}
for v in red.gives() {
if bound(v) || group.contains(&v) || made.contains(&v) {
return refuse(format!(
"the reduction's variable {} of `{}` is bound by a body atom, a group or another reduction",
name(v),
info.name
));
}
made.push(v);
}
for &v in red.of.iter().chain(&red.when) {
if !bound(v) {
return refuse(format!(
"aggregate variable {} of `{}` is bound by no positive atom",
name(v),
info.name
));
}
}
}
for &v in group.iter().chain(times) {
if !bound(v) {
return refuse(format!(
"aggregate variable {} of `{}` is bound by no positive atom",
name(v),
info.name
));
}
}
for &v in group {
if !head.vars().any(|w| w == v) {
return refuse(format!(
"grouping variable {} of `{}` is not in the head",
name(v),
info.name
));
}
}
} else if let Some(a) = &agg {
let (what, vars) = match &a.agg {
Agg::Count { of, out } => {
if bound(*out) {
return refuse(format!(
"the count {} of `{}` is bound by a body atom",
name(*out),
info.name
));
}
if a.group.contains(out) {
return refuse(format!(
"the count {} of `{}` is also a grouping variable",
name(*out),
info.name
));
}
("counted", of)
}
Agg::Min { key } | Agg::Max { key } => ("key", key),
Agg::Rank { key, out } => {
if bound(*out) || a.group.contains(out) {
return refuse(format!(
"the position {} of `{}` is bound by a body atom or groups",
name(*out),
info.name
));
}
("key", key)
}
Agg::SetNumber { of, out, .. } => {
if bound(*out) || a.group.contains(out) {
return refuse(format!(
"the set number {} of `{}` is bound by a body atom or groups",
name(*out),
info.name
));
}
("element", of)
}
Agg::One { of } => ("single-valued", of),
Agg::Many { .. } => unreachable!("checked above"),
};
if vars.is_empty() {
return refuse(format!(
"the aggregate of `{}` has no {what} variable",
info.name
));
}
for &v in a.group.iter().chain(vars) {
if !bound(v) {
return refuse(format!(
"aggregate variable {} of `{}` is bound by no positive atom",
name(v),
info.name
));
}
}
for &v in &a.group {
if !head.vars().any(|w| w == v) {
return refuse(format!(
"grouping variable {} of `{}` is not in the head",
name(v),
info.name
));
}
}
}
if let Some(f) = &fold {
if bound(f.out) {
return refuse(format!(
"the fold's result {} of `{}` is bound by a body atom",
name(f.out),
info.name
));
}
if f.group.contains(&f.out) {
return refuse(format!(
"the fold's result {} of `{}` is also a grouping variable",
name(f.out),
info.name
));
}
let of = (f.op != FoldOp::Count).then_some(&f.of);
for &v in f.group.iter().chain(of).chain(&f.times) {
if !bound(v) {
return refuse(format!(
"fold variable {} of `{}` is bound by no positive atom",
name(v),
info.name
));
}
}
for &v in &f.group {
if !head.vars().any(|w| w == v) {
return refuse(format!(
"grouping variable {} of `{}` is not in the head",
name(v),
info.name
));
}
}
}
let rule = Rule {
head,
body: atoms,
negated,
conds,
computes,
agg,
fold,
};
if let Some(f) = &rule.fold {
// the folded values' type and the result column's
let types = self.type_rule(&rule)?;
let of = types
.iter()
.find(|x| x.0 == f.of)
.map_or(Type::U64, |x| x.1);
if let Some(&w) = f
.times
.iter()
.find(|&&w| types.iter().any(|x| x.0 == w && x.1 != Type::U64))
{
return refuse(format!(
"the fold of `{}` weighs by {}, not a u64",
info.name,
name(w)
));
}
if !matches!(of, Type::U64 | Type::I64 | Type::F64) {
return refuse(format!(
"the fold of `{}` folds {}, a {of} (u64, i64 or f64)",
info.name,
name(f.of)
));
}
let want = match f.op {
FoldOp::Sum => of,
FoldOp::Avg => Type::F64,
FoldOp::Count => Type::U64,
};
let got = rule
.head
.terms
.iter()
.position(|&t| t == Term::Var(f.out))
.map_or(want, |j| self.col_type(rule.head.rel, j));
if got != want {
return refuse(format!(
"the fold's result {} of `{}` is a {want}; its head column is a {got}",
name(f.out),
info.name
));
}
}
Ok(rule)
}
/// Run `parts` (derived relations, in this order) as one stratum of inflationary
/// rounds: count and negation inside recursion. A round computes the parts in order,
/// each from this round's facts of the parts before it (and of itself, recursing to a
/// fixed point within the round) and the round before's facts of the parts after it;
/// a [`Part::Keep`] adds what it finds to what it held, a [`Part::Fresh`] holds only
/// what it finds. Everything a round finds is added at once, so the answer is the same
/// at any thread count; the rounds stop when one changes no part. A part may negate or
/// aggregate over the other parts (as of the round it reads them), not over itself.
/// A table of sets ([`Plan::sets`]) may be a part, kept: it grows at the moment a part
/// that numbers into it is computed (parts after it read it as it then is), and keeps
/// every set it numbered. A kept numbered head adds each key's number of the round to
/// what it held, a fresh one holds each key's number as of the round; a kept head whose
/// rule reads only kept parts and negates none computes again only the groups whose
/// key has a binding with a row gained since it last ran.
/// Refused: an empty list, a relation not derived, listed twice or already in a group,
/// a table of sets as a fresh part.
/// [`crate::plan`] refuses a group whose recursion takes in relations outside it.
pub fn rounds(&mut self, parts: impl IntoIterator<Item = (RelId, Part)>) -> Result<()> {
let parts: Vec<(RelId, Part)> = parts.into_iter().collect();
if parts.is_empty() {
return Err(PlanError::Program("rounds of no relations".into()));
}
for (i, &(r, _)) in parts.iter().enumerate() {
let info = self.rels.get(r.index()).ok_or_else(|| {
PlanError::Program(format!("relation {} is not in this plan", r.index()))
})?;
if info.kind != RelKind::Derived {
return Err(PlanError::Program(format!(
"`{}` is not derived, so it cannot be a part of rounds",
info.name
)));
}
if parts[..i].iter().any(|&(q, _)| q == r) || self.round_of(r).is_some() {
return Err(PlanError::Program(format!(
"`{}` is a part of rounds twice",
info.name
)));
}
if parts[i].1 == Part::Fresh && self.set_limit(r).is_some() {
return Err(PlanError::Program(format!(
"`{}` is a table of sets: it keeps every set it numbered, so its part is keep, not fresh",
info.name
)));
}
}
self.rounds.push(parts);
Ok(())
}
/// Give `rel` (derived, one or two columns, with no rules) by walks of bounded length:
/// one column holds every vertex at the end of a walk from a vertex of `from` (one
/// column) along `edge` (two columns; [`crate::Way::Backward`]: against its edges)
/// whose number of edges lies in `hops`; two columns hold the (start, end) pairs of
/// those walks. Walks may repeat vertices and edges (GQL's WALK mode), and each end
/// (or pair) is a fact once. It runs as frontier steps on kleene-graph
/// ([`crate::Stratum::Walk`], [`kleene_graph::walk_ends`], [`kleene_graph::walk_pairs`]),
/// never as joins. Refused: `rel` not derived, of another width, already given rules
/// or a walk, or in a group of rounds; `from` not of one column; `edge` not of two or
/// an external relation; a relation with typed columns.
pub fn walk(
&mut self,
rel: RelId,
from: RelId,
edge: RelId,
way: crate::Way,
hops: Hops,
) -> Result<()> {
self.walk_checked(rel, from, edge, way, hops, None, 1..=2, false)
}
/// Give `rel` (derived counted, [`Plan::derived_counted`] with one or two u64 columns,
/// with no rules) by the number of walks of bounded length: (end, count) summed over
/// the starts in `from`, or (start, end, count), the walks as [`Plan::walk`] takes
/// them, each counted (vertices and edges may repeat). `edge` is two columns (each
/// edge once) or a counted relation of three (source, destination, number of parallel
/// edges), whose counts multiply. One plus-times step per edge of the length on
/// kleene-graph ([`kleene_graph::walk_counts`]), never an enumeration of walks.
/// Refused as [`Plan::walk`] is, and for `hops` with no `max` (a count is finite only
/// for a bounded length).
pub fn walk_counted(
&mut self,
rel: RelId,
from: RelId,
edge: RelId,
way: crate::Way,
hops: Hops,
) -> Result<()> {
let name = |p: &Self, r: RelId| {
p.rels
.get(r.index())
.map_or(String::new(), |x| x.name.clone())
};
if !self.is_counted(rel) {
return Err(PlanError::Program(format!(
"a counted walk gives a counted relation, not `{}`",
name(self, rel)
)));
}
if hops.max.is_none() {
return Err(PlanError::Program(format!(
"walks of no bounded length are not counted (`{}`): give a most length",
name(self, rel)
)));
}
self.walk_checked(rel, from, edge, way, hops, None, 2..=3, true)
}
#[allow(clippy::too_many_arguments)]
fn walk_checked(
&mut self,
rel: RelId,
from: RelId,
edge: RelId,
way: crate::Way,
hops: Hops,
shortest: Option<Shortest>,
widths: std::ops::RangeInclusive<usize>,
counted: bool,
) -> Result<()> {
for r in [rel, from, edge] {
if r.index() >= self.rels.len() {
return Err(PlanError::Program(format!(
"relation {} is not in this plan",
r.index()
)));
}
}
let (info, f, e) = (
&self.rels[rel.index()],
&self.rels[from.index()],
&self.rels[edge.index()],
);
let refuse = |m: String| Err(PlanError::Program(m));
if info.kind != RelKind::Derived || !widths.contains(&info.arity) {
return refuse(format!(
"a walk gives a derived relation of {} columns, not `{}`",
if shortest.is_some() {
"five"
} else if counted {
"one or two and a count"
} else {
"one or two"
},
info.name
));
}
if self.rules.iter().any(|r| r.head.rel == rel)
|| self.walk_of(rel).is_some()
|| self.call_of(rel).is_some()
|| self.round_of(rel).is_some()
{
return refuse(format!(
"`{}` already has rules, a walk or rounds",
info.name
));
}
if f.arity != 1 {
return refuse(format!("a walk starts from one column, not `{}`", f.name));
}
if let Some(&t) = [rel, from, edge].iter().find(|&&r| self.is_typed(r)) {
return refuse(format!(
"a walk holds u64 vertex ids; `{}` has typed columns",
self.rels[t.index()].name
));
}
let counted_edge = counted && e.arity == 3 && self.is_counted(edge);
if (e.arity != 2 && !counted_edge) || e.kind == RelKind::External {
return refuse(format!(
"a walk goes along a two-column relation that is not external, not `{}`",
e.name
));
}
self.walks.push(Walk {
rel,
from,
edge,
way,
hops,
shortest,
counted,
});
Ok(())
}
/// Give `rel` (derived, five columns, with no rules) by the shortest paths from each
/// vertex of `from` (one column) along `edge` (two columns; [`crate::Way::Backward`]:
/// against its edges) to every vertex reached with a number of edges in `hops`
/// (`hops.min` 0 or 1): a row (start, end, path, position, vertex) per vertex of each
/// path, `path` numbering the paths of one (start, end) pair from 0 (one path with
/// [`Shortest::Any`], every shortest one with [`Shortest::All`], at most
/// [`SHORTEST_PATHS_LIMIT`] in all), `position` from 0 at the start to the length at
/// the end. It runs as one breadth-first search per start on kleene-graph
/// ([`kleene_graph::shortest_paths`]). Refused as [`Plan::walk`] is, and for `hops.min`
/// over 1.
pub fn shortest(
&mut self,
rel: RelId,
from: RelId,
edge: RelId,
way: crate::Way,
hops: Hops,
which: Shortest,
) -> Result<()> {
if rel.index() < self.rels.len() && self.rels[rel.index()].arity != 5 {
return Err(PlanError::Program(format!(
"shortest paths give a derived relation of five columns (start, end, path, \
position, vertex), not `{}`",
self.rels[rel.index()].name
)));
}
if hops.min > 1 {
return Err(PlanError::Program(format!(
"shortest paths take 0 or 1 edges at least, not {}",
hops.min
)));
}
self.walk_checked(rel, from, edge, way, hops, Some(which), 5..=5, false)
}
/// The walks ([`Plan::walk`]).
pub fn walks(&self) -> &[Walk] {
&self.walks
}
/// The column types of the relation `procedure` gives ([`Plan::procedure`] checks them):
/// float scores [`Type::F64`] ([`Procedure::is_float`]), a spanning forest's weights of
/// its weights' type, the rest [`Type::U64`].
pub fn procedure_types(&self, procedure: &Procedure) -> Vec<Type> {
(0..procedure.arity())
.map(|c| match *procedure {
_ if procedure.is_float(c) => Type::F64,
Procedure::SpanningForest { weights: Some(w) } if c == 2 => self.col_type(w, 2),
Procedure::MaxFlow {
capacities: Some(w),
..
} => self.col_type(w, 2),
_ => Type::U64,
})
.collect()
}
/// Give `rel` (derived, of [`Procedure::arity`] columns, with no rules) by the graph
/// algorithm `procedure` over the edges of `edge` (two columns, not external). It runs
/// as its own stratum on kleene-graph ([`crate::Stratum::Procedure`]); PageRank,
/// betweenness, triangles, harmonic centrality, the k-truss, the independent set and the
/// spanning forest need the CPU backend. Refused: `rel` not derived, of
/// another width, already given rules, a walk, rounds or a procedure; `edge` not of two
/// columns or external; weights not of three columns or external.
pub fn procedure(&mut self, rel: RelId, edge: RelId, procedure: Procedure) -> Result<()> {
let weights = procedure.weights();
for r in [Some(rel), Some(edge), weights].into_iter().flatten() {
if r.index() >= self.rels.len() {
return Err(PlanError::Program(format!(
"relation {} is not in this plan",
r.index()
)));
}
}
let (info, e) = (&self.rels[rel.index()], &self.rels[edge.index()]);
let refuse = |m: String| Err(PlanError::Program(m));
if let Procedure::Harmonic {
mode: HarmonicMode::Estimate { log2_registers: b },
} = procedure
&& !(4..=16).contains(&b)
{
return refuse(format!(
"harmonic centrality takes 2^4 to 2^16 registers a counter, not 2^{b}"
));
}
if info.kind != RelKind::Derived || info.arity != procedure.arity() {
return refuse(format!(
"{} gives a derived relation of {} column(s), not `{}`",
procedure.name(),
procedure.arity(),
info.name
));
}
if self.rules.iter().any(|r| r.head.rel == rel)
|| self.walk_of(rel).is_some()
|| self.call_of(rel).is_some()
|| self.round_of(rel).is_some()
{
return refuse(format!(
"`{}` already has rules, a walk, rounds or a procedure",
info.name
));
}
if e.arity != 2 || e.kind == RelKind::External {
return refuse(format!(
"{} runs on a two-column relation that is not external, not `{}`",
procedure.name(),
e.name
));
}
if let Some(w) = weights {
let w = &self.rels[w.index()];
if w.arity != 3 || w.kind == RelKind::External {
return refuse(format!(
"weights are (from, to, weight) rows not external, not `{}`",
w.name
));
}
}
if let Procedure::SpanningForest { weights } = procedure {
let ty = weights.map_or(Type::U64, |w| self.col_type(w, 2));
if !matches!(ty, Type::U64 | Type::I64 | Type::F64) {
return refuse(format!(
"a spanning forest's weights are unsigned, signed or float, not {ty:?}"
));
}
if self.col_type(rel, 2) != ty || self.col_type(rel, 0) != Type::U64 {
return refuse(format!(
"`{}`'s columns are (from, to, weight) with weights of {ty:?}",
self.rels[rel.index()].name
));
}
}
if let Procedure::MaxFlow {
source,
target,
capacities,
} = procedure
{
if source == target {
return refuse(format!(
"a maximum flow from vertex {source} to itself: the source is the target"
));
}
let ty = capacities.map_or(Type::U64, |c| self.col_type(c, 2));
if !matches!(ty, Type::U64 | Type::F64) {
return refuse(format!(
"a maximum flow's capacities are unsigned or float, not {ty:?}"
));
}
if self.col_type(rel, 0) != ty {
return refuse(format!(
"`{}`'s column is the flow, of the capacities' type {ty:?}",
self.rels[rel.index()].name
));
}
}
self.calls.push(Call {
rel,
edge,
procedure,
});
Ok(())
}
/// The procedures ([`Plan::procedure`]).
pub fn calls(&self) -> &[Call] {
&self.calls
}
/// The procedure that gives `r`, if one does.
pub fn call_of(&self, r: RelId) -> Option<&Call> {
self.calls.iter().find(|c| c.rel == r)
}
/// The walk that gives `r`, if one does.
pub fn walk_of(&self, r: RelId) -> Option<&Walk> {
self.walks.iter().find(|w| w.rel == r)
}
/// The groups of [`Plan::rounds`], each in its order.
pub fn round_groups(&self) -> &[Vec<(RelId, Part)>] {
&self.rounds
}
/// The group of rounds `r` is a part of, and its place in it.
pub fn round_of(&self, r: RelId) -> Option<(usize, usize)> {
self.rounds
.iter()
.enumerate()
.find_map(|(g, parts)| parts.iter().position(|&(q, _)| q == r).map(|i| (g, i)))
}
/// The relations.
pub fn relations(&self) -> &[RelInfo] {
&self.rels
}
/// One relation.
pub fn relation_info(&self, r: RelId) -> &RelInfo {
&self.rels[r.index()]
}
/// The rules.
pub fn rules(&self) -> &[Rule] {
&self.rules
}
/// The rule numbered `r`, to change in place (the index choice adds atoms).
pub(crate) fn rule_mut(&mut self, r: RuleId) -> &mut Rule {
&mut self.rules[r.index()]
}
/// One rule.
pub fn rule_at(&self, r: RuleId) -> &Rule {
&self.rules[r.index()]
}
/// A variable's name.
pub fn var_name(&self, v: Var) -> &str {
&self.vars[v.0 as usize]
}
/// A rule as text, `head(X) :- body(X, Y).`
pub fn show_rule(&self, r: RuleId) -> String {
struct A<'a>(&'a Plan, &'a Atom);
impl fmt::Display for A<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}(", self.0.rels[self.1.rel.index()].name)?;
for (i, t) in self.1.terms.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
match t {
Term::Var(v) => write!(f, "{}", self.0.var_name(*v))?,
Term::Const(c) => write!(
f,
"{}",
self.0.show_const(*c, self.0.col_type(self.1.rel, i))
)?,
}
}
write!(f, ")")
}
}
let rule = self.rule_at(r);
let body: Vec<String> = rule
.body
.iter()
.map(|a| A(self, a).to_string())
.chain(
rule.computes
.iter()
.filter(|c| !c.of_test)
.map(|c| self.show_compute(r, c)),
)
.chain(rule.negated.iter().map(|a| format!("!{}", A(self, a))))
.chain(rule.conds.iter().map(|c| self.show_cond_of(r, c)))
.collect();
let agg = match (&rule.agg, &rule.fold) {
(
Some(Aggregate {
group,
agg: Agg::SetNumber { of, out, table },
}),
_,
) => format!(
"{} = set ({}) by ({}) in {}: ",
self.var_name(*out),
self.show_vars(of),
self.show_vars(group),
self.rels[table.index()].name
),
(Some(a), _) => format!(
"{} by ({}): ",
self.show_agg(&a.agg),
self.show_vars(&a.group)
),
(None, Some(f)) => format!(
"{} = {} ({}) by ({}): ",
self.var_name(f.out),
match f.op {
FoldOp::Sum => "sum",
FoldOp::Avg => "avg",
FoldOp::Count => "count",
},
if f.op == FoldOp::Count {
f.times
.iter()
.map(|&v| self.var_name(v))
.collect::<Vec<_>>()
.join(" * ")
} else {
self.var_name(f.of).to_string()
},
self.show_vars(&f.group)
),
(None, None) => String::new(),
};
format!("{} :- {agg}{}.", A(self, &rule.head), body.join(", "))
}
fn show_vars(&self, vs: &[Var]) -> String {
let names: Vec<&str> = vs.iter().map(|&v| self.var_name(v)).collect();
names.join(", ")
}
/// An aggregate's reduction as text, `N = count (G)`, `min (A, B)`, `exactly one (X)`.
pub fn show_agg(&self, a: &Agg) -> String {
match a {
Agg::Count { of, out } => {
format!("{} = count ({})", self.var_name(*out), self.show_vars(of))
}
Agg::Min { key } => format!("min ({})", self.show_vars(key)),
Agg::Max { key } => format!("max ({})", self.show_vars(key)),
Agg::One { of } => format!("exactly one ({})", self.show_vars(of)),
Agg::Rank { key, out } => {
format!("{} = rank ({})", self.var_name(*out), self.show_vars(key))
}
Agg::SetNumber { of, out, table } => format!(
"{} = set ({}) in {}",
self.var_name(*out),
self.show_vars(of),
self.rels[table.index()].name
),
Agg::Many { reduces, times } => {
let parts: Vec<String> = reduces
.iter()
.map(|r| {
let op = match r.op {
ReduceOp::Count => "count",
ReduceOp::Sum => "sum",
ReduceOp::Avg => "avg",
ReduceOp::Min => "min",
ReduceOp::Max => "max",
};
let mut x = format!(
"{} = {op} ({}{})",
self.var_name(r.out),
if r.distinct { "distinct " } else { "" },
self.show_vars(&r.of)
);
if !r.when.is_empty() {
x.push_str(&format!(" when {}", self.show_vars(&r.when)));
}
if let Some(h) = r.has {
x.push_str(&format!(" has {}", self.var_name(h)));
}
x
})
.collect();
let mut x = parts.join(", ");
if !times.is_empty() {
x.push_str(&format!(" times {}", self.show_vars(times)));
}
x
}
}
}
/// A term as text: a variable's name or the constant.
pub fn show_term(&self, t: Term) -> String {
match t {
Term::Var(v) => self.var_name(v).to_string(),
Term::Const(c) => c.to_string(),
}
}
/// A constant of type `ty` as text: the number, the signed number, the float, `true` /
/// `false`, or the quoted string.
pub fn show_const(&self, c: Value, ty: Type) -> String {
match ty {
Type::Str => match self.strings.get(c as usize) {
Some(s) => format!("{s:?}"),
None => format!("#{c}"),
},
_ => ty.decode(c, None).to_string(),
}
}
/// A computed value of rule `r` as text, `O = LO + I`.
pub fn show_compute(&self, r: RuleId, c: &Compute) -> String {
format!("{} = {}", self.var_name(c.out), self.show_expr(r, c))
}
/// The expression of a computed value of rule `r` as text: its constants as numbers,
/// or as floats in a float one.
pub fn show_expr(&self, r: RuleId, c: &Compute) -> String {
let float = self.var_type(r, c.out) == Type::F64;
c.expr.show_with(
&|t| match t {
Term::Var(v) => self.var_name(v).to_string(),
Term::Const(k) if float => self.show_const(k, Type::F64),
Term::Const(k) => k.to_string(),
},
&|t| match t {
Term::Var(v) => self.var_name(v).to_string(),
Term::Const(k) => self.show_const(k, Type::Str),
},
)
}
/// Whether a rule makes strings: a computed value calls `concat` or `substr`
/// ([`crate::Func::makes_string`]).
pub fn makes_strings(&self) -> bool {
self.rules
.iter()
.any(|r| r.computes.iter().any(|c| c.expr.makes_string()))
}
/// A condition of rule `r` as text, its constants printed by the type of the variables
/// they are compared with, an expression of a [`Test`] in its place.
pub fn show_cond_of(&self, r: RuleId, c: &Cond) -> String {
let ty = c
.terms()
.iter()
.find_map(|t| t.var())
.map_or(Type::U64, |v| self.var_type(r, v));
let rule = self.rule_at(r);
let term = |t: Term| match t {
Term::Var(v) => match rule.test_compute(v) {
Some(c) => self.show_expr(r, c),
None => self.var_name(v).to_string(),
},
Term::Const(k) => self.show_const(k, ty),
};
match *c {
Cond::Cmp { left, op, right } => {
format!("{} {} {}", term(left), op.symbol(), term(right))
}
Cond::Within { x, lo, hi } => format!("{} in [{}, {})", term(x), term(lo), term(hi)),
Cond::IsNull { x, null } => {
format!("{} is {}null", term(x), if null { "" } else { "not " })
}
Cond::Text { x, op, pat } => format!("{} {} {}", term(x), op.words(), term(pat)),
Cond::OneOf { x, list, not } => self.show_one_of(term(x), list, not),
}
}
/// A condition as text, `X != Y` or `A in [Lo, Hi)`.
pub fn show_cond(&self, c: &Cond) -> String {
match *c {
Cond::Cmp { left, op, right } => format!(
"{} {} {}",
self.show_term(left),
op.symbol(),
self.show_term(right)
),
Cond::Within { x, lo, hi } => format!(
"{} in [{}, {})",
self.show_term(x),
self.show_term(lo),
self.show_term(hi)
),
Cond::IsNull { x, null } => format!(
"{} is {}null",
self.show_term(x),
if null { "" } else { "not " }
),
Cond::Text { x, op, pat } => format!(
"{} {} {}",
self.show_term(x),
op.words(),
self.show_term(pat)
),
Cond::OneOf { x, list, not } => self.show_one_of(self.show_term(x), list, not),
}
}
}
/// Whether every call of `e` stands in a place of its kind (a string function where a
/// string goes, `len` and the operators where a number goes) with its number of
/// arguments; `text`: `e` stands where a string goes.
fn call_places(e: &crate::compute::Expr, text: bool) -> std::result::Result<(), String> {
use crate::compute::Expr;
match e {
Expr::Term(_) => Ok(()),
Expr::Op(_, a, b) if !text => {
call_places(a, false)?;
call_places(b, false)
}
Expr::Unary(_, a) if !text => call_places(a, false),
Expr::Op(..) | Expr::Unary(..) => Err(format!(
"`{}` is a number where a string goes",
e.show(&|_| "_".into())
)),
Expr::Call(f, args) => {
if f.makes_string() != text {
return Err(format!(
"{}(..) gives a {} where a {} goes",
f.name(),
if text { "number" } else { "string" },
if text { "string" } else { "number" }
));
}
let (lo, hi) = f.arity();
if args.len() < lo || args.len() > hi {
return Err(format!(
"{}(..) takes {}, not {}",
f.name(),
match (lo, hi) {
(1, 1) => "1 argument".to_string(),
(l, h) if l == h => format!("{l} arguments"),
(l, usize::MAX) => format!("{l} or more arguments"),
(l, h) => format!("{l} to {h} arguments"),
},
args.len()
));
}
for (i, a) in args.iter().enumerate() {
call_places(a, f.string_arg(i))?;
}
Ok(())
}
}
}