crates/kleene-plan/src/external.rs
use std::fmt;
use std::sync::Arc;
use crate::rules::Value;
use crate::{NameIndex, Result};
/// A relation answered by Rust code when a rule runs: an index lookup (address to
/// function, can A reach B, which ranges cover X), a decoder, any producer of facts.
/// Declared with [`crate::Plan::external`], given with [`crate::Inputs::external`].
///
/// The engine asks set at a time: a batch of `n` keys, each holding values for the columns
/// that are bound (by the rule's other atoms or by constants); `bound` has bit `i` set
/// when column `i` is. It first asks [`External::can`] whether that pattern is answered. A
/// relation that answers the empty pattern (`can(0)`) can be listed whole: for a pattern
/// it does not answer, the engine lists it once and joins the rows itself.
///
/// Rows for one key should be distinct (a repeat is harmless to rule heads, but an
/// aggregate's group size would count it).
pub trait External: Send + Sync + fmt::Debug {
/// The number of columns (1 to 64).
fn arity(&self) -> usize;
/// Whether rows can be listed when the columns in `bound` are given.
fn can(&self, bound: u64) -> bool;
/// For every key `k` in `0..n`, call `out(k, row)` once for each row of the relation
/// (all its columns, in order) whose bound columns equal the key's values
/// `keys[i][k]` (`keys[i]` is empty for an unbound column `i`). Called only when
/// `can(bound)` holds; keys are handed in rising `k`.
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()>;
}
/// A producer of facts as an [`External`]: a function that lists every row. It answers
/// only the empty pattern; the engine lists it once per run and joins.
pub struct Producer<F> {
arity: usize,
rows: F,
}
impl<F> Producer<F>
where
F: Fn(&mut dyn FnMut(&[Value])) -> Result<()> + Send + Sync,
{
/// `arity` columns, listed by `rows` (which calls its argument once per row).
pub fn new(arity: usize, rows: F) -> Self {
Producer { arity, rows }
}
}
impl<F> fmt::Debug for Producer<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Producer({} columns)", self.arity)
}
}
impl<F> External for Producer<F>
where
F: Fn(&mut dyn FnMut(&[Value])) -> Result<()> + Send + Sync,
{
fn arity(&self) -> usize {
self.arity
}
fn can(&self, bound: u64) -> bool {
bound == 0
}
fn lookup(
&self,
_bound: u64,
_keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
for k in 0..n {
(self.rows)(&mut |r| out(k, r))?;
}
Ok(())
}
}
/// The ids of an id space's blocks (each `(base, count)`: a vertex type's ids
/// `base..base + count`, kleene-gar's `IdSpace`) that lie in some closed intervals of ids,
/// one column: a lookup of nodes by `id(n)` (an equality, a range, an OR of them) that lists
/// the ids from the numbers alone, no label read. Unbound it lists them rising, each once;
/// bound it keeps the keys among them. An id beyond the last block is none.
#[derive(Clone, Debug)]
pub struct IdRanges {
blocks: Vec<(Value, Value)>,
wanted: Vec<(Value, Value)>,
rows: bool,
}
impl IdRanges {
/// The ids of `blocks` (`(base, count)`) within the intervals `wanted` (`(lo, hi)`,
/// both ends in; one with `lo > hi` is empty).
pub fn new(
blocks: impl IntoIterator<Item = (Value, Value)>,
wanted: impl IntoIterator<Item = (Value, Value)>,
) -> Self {
let mut blocks: Vec<(Value, Value)> = blocks.into_iter().filter(|b| b.1 > 0).collect();
blocks.sort_unstable();
let mut w: Vec<(Value, Value)> = wanted.into_iter().filter(|x| x.0 <= x.1).collect();
w.sort_unstable();
let mut wanted: Vec<(Value, Value)> = Vec::with_capacity(w.len());
for (lo, hi) in w {
match wanted.last_mut() {
Some(last) if lo <= last.1.saturating_add(1) => last.1 = last.1.max(hi),
_ => wanted.push((lo, hi)),
}
}
IdRanges {
blocks,
wanted,
rows: false,
}
}
/// Whether `id` is one of them.
pub fn contains(&self, id: Value) -> bool {
self.wanted.iter().any(|w| (w.0..=w.1).contains(&id))
&& self.blocks.iter().any(|b| id >= b.0 && id - b.0 < b.1)
}
/// Them, rising.
pub fn ids(&self) -> impl Iterator<Item = Value> + '_ {
self.wanted.iter().flat_map(move |&(lo, hi)| {
self.blocks.iter().flat_map(move |&(b, c)| {
// (empty where they do not meet)
lo.max(b)..=hi.min(b + (c - 1))
})
})
}
}
impl IdRanges {
/// The same ids handed as rows of their blocks (`id - base`, each row once, rising), for
/// a lookup of a vertex table's rows by `id(n)`; a bound row is one of them when the id
/// of that row in some block is.
pub fn rows(mut self) -> Self {
self.rows = true;
self
}
/// Row `r` as the id of the block it lies in, if one of them.
fn row_id(&self, r: Value) -> Option<Value> {
self.blocks
.iter()
.filter(|b| r < b.1)
.map(|b| b.0 + r)
.find(|&id| self.contains(id))
}
/// An id as handed: itself, or its row.
fn hand(&self, id: Value) -> Value {
if !self.rows {
return id;
}
let b = self
.blocks
.iter()
.find(|b| id >= b.0 && id - b.0 < b.1)
.expect("an id of a block");
id - b.0
}
}
impl External for IdRanges {
fn arity(&self) -> usize {
1
}
fn can(&self, _bound: u64) -> bool {
true
}
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
if bound & 1 == 1 {
for (k, &x) in keys[0].iter().take(n).enumerate() {
let found = if self.rows {
self.row_id(x).is_some()
} else {
self.contains(x)
};
if found {
out(k, &[x]);
}
}
} else {
if self.rows {
// (rows of two blocks may be one row: each once)
let mut handed: Vec<Value> = self.ids().map(|id| self.hand(id)).collect();
handed.sort_unstable();
handed.dedup();
for k in 0..n {
for &x in &handed {
out(k, &[x]);
}
}
} else {
for k in 0..n {
for id in self.ids() {
out(k, &[id]);
}
}
}
}
Ok(())
}
}
/// `(row, id)` of a vertex table: `id = base + row` for each row below `count` (any row
/// when the count is not known: then it answers only with a column bound). A lookup of a
/// node's `id(n)` from its row and back, by arithmetic alone.
#[derive(Clone, Copy, Debug)]
pub struct IdShift {
base: Value,
count: Option<Value>,
}
impl IdShift {
/// Rows `0..count` (`None`: any row) with ids from `base`.
pub fn new(base: Value, count: Option<Value>) -> Self {
IdShift { base, count }
}
}
impl External for IdShift {
fn arity(&self) -> usize {
2
}
fn can(&self, bound: u64) -> bool {
bound != 0 || self.count.is_some()
}
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
let fits = |r: Value| self.count.is_none_or(|c| r < c);
match bound & 3 {
0 => {
for k in 0..n {
for r in 0..self.count.unwrap_or(0) {
out(k, &[r, r + self.base]);
}
}
}
1 => {
for (k, &r) in keys[0].iter().take(n).enumerate() {
if fits(r)
&& let Some(id) = r.checked_add(self.base)
{
out(k, &[r, id]);
}
}
}
2 => {
for (k, &id) in keys[1].iter().take(n).enumerate() {
if let Some(r) = id.checked_sub(self.base)
&& fits(r)
{
out(k, &[r, id]);
}
}
}
_ => {
for (k, (&r, &id)) in keys[0].iter().zip(keys[1]).take(n).enumerate() {
if fits(r) && r.checked_add(self.base) == Some(id) {
out(k, &[r, id]);
}
}
}
}
Ok(())
}
}
/// The ids a name index ([`crate::NameIndex`]) gives for some strings, one column, listed
/// when a rule reads them (each id once, rising): a lookup of nodes by a string property's
/// value, an equality or an OR of them.
#[derive(Debug)]
pub struct NameHits {
index: Arc<dyn NameIndex>,
names: Vec<String>,
}
impl NameHits {
/// The ids `index` gives for `names`.
pub fn new(index: Arc<dyn NameIndex>, names: Vec<String>) -> Self {
NameHits { index, names }
}
}
impl External for NameHits {
fn arity(&self) -> usize {
1
}
fn can(&self, bound: u64) -> bool {
bound == 0
}
fn lookup(
&self,
_bound: u64,
_keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
let mut ids: Vec<u32> = Vec::new();
for name in &self.names {
self.index.nodes(name, &mut |v| ids.push(v))?;
}
ids.sort_unstable();
ids.dedup();
for k in 0..n {
for &v in &ids {
out(k, &[v as Value]);
}
}
Ok(())
}
}
/// An external relation over a type's own rows, handed in an id space: column `i`'s values
/// are the inner relation's plus `bases[i]` (0 for a column that is no node). A bound key
/// below its column's base matches nothing; one past the inner relation's rows finds none
/// there. Built to put an index over one vertex type's rows (rows `0..count`) into a set's
/// one id space (kleene-gar's `IdSpace`).
pub struct Shifted {
inner: Arc<dyn External>,
bases: Vec<Value>,
}
impl Shifted {
/// `inner` with column `i` shifted by `bases[i]` (as many bases as columns).
pub fn new(inner: Arc<dyn External>, bases: Vec<Value>) -> Result<Self> {
if bases.len() != inner.arity() {
return Err(crate::PlanError::Input(format!(
"{} bases for an external of {} columns",
bases.len(),
inner.arity()
)));
}
Ok(Shifted { inner, bases })
}
}
impl fmt::Debug for Shifted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Shifted({:?} by {:?})", self.inner, self.bases)
}
}
impl External for Shifted {
fn arity(&self) -> usize {
self.bases.len()
}
fn can(&self, bound: u64) -> bool {
self.inner.can(bound)
}
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> Result<()> {
let is_bound = |i: usize| bound >> i & 1 == 1;
let kept: Vec<usize> = (0..n)
.filter(|&k| (0..self.bases.len()).all(|i| !is_bound(i) || keys[i][k] >= self.bases[i]))
.collect();
if kept.is_empty() {
return Ok(());
}
let cols: Vec<Vec<Value>> = (0..self.bases.len())
.map(|i| {
if is_bound(i) {
kept.iter().map(|&k| keys[i][k] - self.bases[i]).collect()
} else {
Vec::new()
}
})
.collect();
let refs: Vec<&[Value]> = cols.iter().map(Vec::as_slice).collect();
let mut row = vec![0; self.bases.len()];
self.inner.lookup(bound, &refs, kept.len(), &mut |j, r| {
for (x, (&v, &b)) in row.iter_mut().zip(r.iter().zip(&self.bases)) {
*x = v + b;
}
out(kept[j], &row);
})
}
}