crates/kleene-datalog-macros/src/lib.rs
//! The `datalog!` macro of kleene-datalog: rules written as Datalog text in Rust, turned at
//! build time into the calls of `kleene_datalog::Program`'s builder. Use it as
//! `kleene_datalog::datalog!`; the grammar and the examples are on that re-export.
use std::collections::{HashMap, HashSet};
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Expr, Ident, LitFloat, LitInt, LitStr, Token, parenthesized};
/// Datalog rules turned into `kleene_datalog::Program` builder calls at build time; see
/// `kleene_datalog::datalog!` for the grammar.
#[proc_macro]
pub fn datalog(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = split_floats(input.into());
match syn::parse2::<Source>(input).and_then(|s| expand(&s)) {
Ok(ts) => ts.into(),
Err(e) => e.to_compile_error().into(),
}
}
/// `calls/2.` and `F < 5.` lex the number and the end of the item as one float literal
/// (`2.`): split each such literal back into the integer and a `.`.
fn split_floats(ts: TokenStream) -> TokenStream {
use proc_macro2::{Group, Literal, Punct, Spacing, TokenTree};
let mut out = Vec::new();
for tt in ts {
match tt {
TokenTree::Group(g) => {
let mut ng = Group::new(g.delimiter(), split_floats(g.stream()));
ng.set_span(g.span());
out.push(TokenTree::Group(ng));
}
TokenTree::Literal(l) => {
let text = l.to_string();
match text.strip_suffix('.') {
Some(d) if !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()) => {
let mut n = Literal::u64_unsuffixed(d.parse().unwrap_or(0));
n.set_span(l.span());
let mut dot = Punct::new('.', Spacing::Alone);
dot.set_span(l.span());
out.push(TokenTree::Literal(n));
out.push(TokenTree::Punct(dot));
}
_ => out.push(TokenTree::Literal(l)),
}
}
t => out.push(t),
}
}
out.into_iter().collect()
}
mod kw {
syn::custom_keyword!(input);
syn::custom_keyword!(external);
syn::custom_keyword!(derived);
syn::custom_keyword!(rounds);
syn::custom_keyword!(keep);
syn::custom_keyword!(fresh);
syn::custom_keyword!(by);
syn::custom_keyword!(from);
syn::custom_keyword!(starts);
syn::custom_keyword!(ends);
syn::custom_keyword!(with);
syn::custom_keyword!(contains);
syn::custom_keyword!(or);
syn::custom_keyword!(empty);
syn::custom_keyword!(counted);
syn::custom_keyword!(is);
syn::custom_keyword!(not);
syn::custom_keyword!(null);
syn::custom_keyword!(sets);
syn::custom_keyword!(limit);
}
/// The whole input: the program it adds to (or none: a new one), then its items.
struct Source {
program: Option<Expr>,
items: Vec<Item>,
}
// A parse tree lives for one expansion: its size does not matter.
#[allow(clippy::large_enum_variant)]
enum Item {
Decl(Vec<Decl>),
Rounds(Vec<(RelRef, bool)>),
Rule(Rule),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Input,
External,
Derived,
/// Derived with a count per row, its last column (`Program::derived_counted`).
Counted,
/// A table of sets (`Program::sets`): rules number into it, none derives it.
Sets,
}
struct Decl {
kind: Kind,
/// The handle: the name as written, a dotted name's parts joined by `_`.
name: Ident,
arity: usize,
arity_span: Span,
text: String,
/// The name rules write: `sym.info` for `input sym.info/2 from cat.`, else the handle's.
key: String,
/// `from CAT ["name"]`: an input read by name from a catalog.
from: Option<FromCat>,
/// `limit INT` of a table of sets.
limit: Option<u64>,
}
/// `input NAME/N [(types)] from CAT ["catalog name"].`: an input relation as a catalog
/// has it (`Program::input_from`).
struct FromCat {
/// The catalog: a local, or a Rust expression in braces.
cat: TokenStream,
/// The catalog's name of the relation, an expression of type `&str`: the quoted name,
/// a Rust expression in braces, or the name as written.
name: TokenStream,
/// The column types the text gives, checked against the catalog's.
types: Option<Vec<Ident>>,
/// `or empty`: an empty input where the catalog lacks the name
/// (`Program::input_or_empty`), of the types given (all `u64` when none are).
or_empty: bool,
}
/// A relation as written: a path of fields (`reach`, `t.calls`) or a braced expression.
enum RelRef {
Path(Vec<Ident>),
Expr(syn::ExprBlock),
}
impl RelRef {
fn span(&self) -> Span {
match self {
RelRef::Path(p) => p[0].span(),
RelRef::Expr(e) => e.span(),
}
}
fn tokens(&self) -> TokenStream {
match self {
RelRef::Path(p) => {
let first = &p[0];
let rest = &p[1..];
quote!(#first #(. #rest)*)
}
RelRef::Expr(e) => {
let inner = &e.block;
quote!((#inner))
}
}
}
fn show(&self) -> String {
match self {
RelRef::Path(p) => p
.iter()
.map(|i| i.unraw().to_string())
.collect::<Vec<_>>()
.join("."),
RelRef::Expr(_) => "{..}".into(),
}
}
}
// A parse tree lives for one expansion: its size does not matter.
#[allow(clippy::large_enum_variant)]
enum Term {
/// A Datalog variable, by name.
Var(Ident),
/// `_`: a variable of its own.
Wild(Span),
/// An unsuffixed integer literal.
Lit(LitInt),
/// `-` and an unsuffixed integer literal: a signed integer.
Neg(Span, LitInt),
/// A float literal, after `-` (true) or not.
Float(Span, bool, LitFloat),
/// A string literal.
Str(LitStr),
/// A Rust expression: a constant or a `Var` of the caller.
Rust(Expr),
}
impl Term {
fn span(&self) -> Span {
match self {
Term::Var(i) => i.span(),
Term::Wild(s) => *s,
Term::Lit(l) => l.span(),
Term::Neg(s, _) | Term::Float(s, ..) => *s,
Term::Str(l) => l.span(),
Term::Rust(e) => e.span(),
}
}
}
struct Atom {
rel: RelRef,
args_span: Span,
terms: Vec<Term>,
}
/// A string test: `starts with`, `ends with`, `contains`.
#[derive(Clone, Copy)]
enum TextOp {
StartsWith,
EndsWith,
Contains,
}
#[derive(Clone, Copy)]
enum Op {
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
}
/// An operator of an expression, with Rust's precedence.
#[derive(Clone, Copy)]
enum BinOp {
Add,
Sub,
Mul,
Div,
Rem,
And,
Or,
Xor,
Shl,
Shr,
}
impl BinOp {
fn precedence(self) -> u8 {
match self {
BinOp::Mul | BinOp::Div | BinOp::Rem => 10,
BinOp::Add | BinOp::Sub => 9,
BinOp::Shl | BinOp::Shr => 8,
BinOp::And => 7,
BinOp::Xor => 6,
BinOp::Or => 5,
}
}
fn tokens(self) -> TokenStream {
match self {
BinOp::Add => quote!(Add),
BinOp::Sub => quote!(Sub),
BinOp::Mul => quote!(Mul),
BinOp::Div => quote!(Div),
BinOp::Rem => quote!(Rem),
BinOp::And => quote!(And),
BinOp::Or => quote!(Or),
BinOp::Xor => quote!(Xor),
BinOp::Shl => quote!(Shl),
BinOp::Shr => quote!(Shr),
}
}
}
/// An expression of a literal: a term, or an operator over two.
// A parse tree lives for one expansion: its size does not matter.
#[allow(clippy::large_enum_variant)]
enum Ex {
Term(Term),
Op(BinOp, Box<Ex>, Box<Ex>),
/// `-a` (true) or `!a` (false).
Un(bool, Box<Ex>),
/// A string function: `concat(..)`, `substr(..)`, `len(..)` (its `Func` variant's name).
Call(Ident, Vec<Ex>),
}
/// The string functions of an expression: name, `Func` variant, least and most arguments.
const FUNCS: &[(&str, &str, usize, usize)] = &[
("concat", "Concat", 2, usize::MAX),
("substr", "Substr", 2, 3),
("len", "Len", 1, 1),
];
impl Ex {
/// The term, where the expression is one.
fn term(&self) -> Option<&Term> {
match self {
Ex::Term(t) => Some(t),
_ => None,
}
}
/// Its terms, left to right.
fn terms<'a>(&'a self, out: &mut Vec<&'a Term>) {
match self {
Ex::Term(t) => out.push(t),
Ex::Op(_, a, b) => {
a.terms(out);
b.terms(out);
}
Ex::Un(_, a) => a.terms(out),
Ex::Call(_, args) => {
for a in args {
a.terms(out);
}
}
}
}
/// Its variables' names, left to right.
fn vars(&self) -> Vec<&Ident> {
let mut ts = Vec::new();
self.terms(&mut ts);
ts.into_iter()
.filter_map(|t| match t {
Term::Var(v) => Some(v),
_ => None,
})
.collect()
}
}
// A parse tree lives for one expansion: its size does not matter.
#[allow(clippy::large_enum_variant)]
enum Lit {
Pos(Atom),
Neg(Atom),
Cmp(Ex, Op, Ex),
Within(Ex, Ex, Ex),
Text(Term, TextOp, Term),
/// `VAR = expr`
Compute(Ident, Ex),
/// `X is null` (true) or `X is not null`.
Null(Term, bool),
/// `x in (k1, ..)` or `x in {slice}`; `!(x in ..)` (true).
OneOf(Ex, List, bool),
}
/// The list of a list test.
// A parse tree lives for one expansion: its size does not matter.
#[allow(clippy::large_enum_variant)]
enum List {
/// `(k1, k2, ..)`: literals and Rust values, each a member.
Members(Vec<Term>),
/// `{expr}`: a Rust list (a slice, an array, a `Vec`), the whole list.
Whole(Expr),
}
/// A value reduction of a list: `OUT = op(vars)`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Red {
Count,
Sum,
Avg,
Least,
Greatest,
}
enum AggKind {
/// `N = count(vars)` alone: the number of distinct tuples.
Count(Ident),
/// `N = count()` alone: the bag count of a counted head (`Program::count_rule`).
Bag(Ident),
/// `N = rank(K..)`: the position of the binding's key in its group.
Rank(Ident),
/// `N = set(X..) in NAME`: the number of the group's set in the table of sets `NAME`.
Set(Ident, RelRef),
Min,
Max,
One,
/// Value reductions (`Aggregate::many`): two or more, or one that is not a count.
Many(Vec<(Red, Ident, Vec<Ident>)>),
}
struct Agg {
kind: AggKind,
of: Vec<Ident>,
group: Vec<Ident>,
span: Span,
}
struct Rule {
head: Atom,
agg: Option<Agg>,
body: Vec<Lit>,
}
impl Parse for Source {
fn parse(input: ParseStream) -> syn::Result<Self> {
let program = {
let fork = input.fork();
match fork.parse::<Expr>() {
Ok(e) if fork.peek(Token![=>]) => {
input.parse::<Expr>()?;
input.parse::<Token![=>]>()?;
Some(e)
}
_ => None,
}
};
let mut items = Vec::new();
while !input.is_empty() {
items.push(input.parse()?);
}
Ok(Source { program, items })
}
}
impl Parse for Item {
fn parse(input: ParseStream) -> syn::Result<Self> {
let decl_kind = if input.peek(kw::input) && input.peek2(Ident) {
input.parse::<kw::input>()?;
Some(Kind::Input)
} else if input.peek(kw::external) && input.peek2(Ident) {
input.parse::<kw::external>()?;
Some(Kind::External)
} else if input.peek(kw::derived) && input.peek2(Ident) {
input.parse::<kw::derived>()?;
Some(Kind::Derived)
} else if input.peek(kw::counted) && input.peek2(Ident) {
input.parse::<kw::counted>()?;
Some(Kind::Counted)
} else if input.peek(kw::sets) && input.peek2(Ident) {
input.parse::<kw::sets>()?;
Some(Kind::Sets)
} else {
None
};
if let Some(kind) = decl_kind {
let mut decls = Vec::new();
loop {
let path = parse_decl_name(input)?;
input.parse::<Token![/]>()?;
let n: LitInt = input.parse()?;
let arity: usize = n.base10_parse()?;
if arity == 0 && kind == Kind::External {
return Err(syn::Error::new(
n.span(),
"an external relation has at least one column",
));
}
if kind == Kind::Counted && arity < 2 {
return Err(syn::Error::new(
n.span(),
"a counted relation has a column and its count",
));
}
if kind == Kind::Sets && arity < 2 {
return Err(syn::Error::new(
n.span(),
"a table of sets has a number and an element: `sets NAME/2` or more",
));
}
if kind == Kind::External && arity > 64 {
return Err(syn::Error::new(
n.span(),
"an external relation has at most 64 columns",
));
}
let types = parse_decl_types(input)?;
let shown = if input.peek(Token![as]) {
input.parse::<Token![as]>()?;
Some(input.parse::<LitStr>()?)
} else {
None
};
let from = parse_from(input)?;
let limit = parse_limit(input, kind)?;
let mut d = decl_of(kind, path, (arity, &n), types, shown, from)?;
d.limit = limit;
decls.push(d);
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
} else {
break;
}
}
end(input, "after a declaration")?;
return Ok(Item::Decl(decls));
}
if input.peek(kw::rounds) && !input.peek2(syn::token::Paren) {
input.parse::<kw::rounds>()?;
let mut parts = Vec::new();
loop {
let rel = parse_relref(input)?;
input.parse::<Token![:]>()?;
let keep = if input.peek(kw::keep) {
input.parse::<kw::keep>()?;
true
} else if input.peek(kw::fresh) {
input.parse::<kw::fresh>()?;
false
} else {
return Err(input.error("expected `keep` or `fresh`"));
};
parts.push((rel, keep));
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
} else {
break;
}
}
end(input, "after the parts of rounds")?;
return Ok(Item::Rounds(parts));
}
let head = parse_atom(input)?;
if !(input.peek(Token![:]) && input.peek2(Token![-])) {
return Err(
input.error("expected `:-` and a body (a rule needs one; facts come from inputs)")
);
}
input.parse::<Token![:]>()?;
input.parse::<Token![-]>()?;
let agg = if is_agg(input) {
Some(parse_agg(input)?)
} else {
None
};
let mut body = Vec::new();
loop {
body.push(parse_lit(input)?);
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
} else {
break;
}
}
end(input, "after a rule")?;
Ok(Item::Rule(Rule { head, agg, body }))
}
}
fn end(input: ParseStream, what: &str) -> syn::Result<()> {
if input.peek(Token![.]) {
input.parse::<Token![.]>()?;
Ok(())
} else {
Err(input.error(format!("expected `,` or `.` {what}")))
}
}
/// A declared name: one identifier, or a dotted catalog name (`sym.info`).
fn parse_decl_name(input: ParseStream) -> syn::Result<Vec<Ident>> {
let mut path = vec![input.parse::<Ident>()?];
while input.peek(Token![.]) && !input.peek(Token![..]) && input.peek2(Ident::peek_any) {
input.parse::<Token![.]>()?;
path.push(Ident::parse_any(input)?);
}
Ok(path)
}
/// `limit INT` at the end of a table of sets' declaration, if there: at least 1.
fn parse_limit(input: ParseStream, kind: Kind) -> syn::Result<Option<u64>> {
if !input.peek(kw::limit) {
return Ok(None);
}
let at = input.parse::<kw::limit>()?.span;
if kind != Kind::Sets {
return Err(syn::Error::new(
at,
"only a table of sets has a limit: `sets NAME/N limit INT.`",
));
}
let n: LitInt = input.parse()?;
let limit: u64 = n.base10_parse()?;
if limit == 0 {
return Err(syn::Error::new(
n.span(),
"a table of sets with limit 0 can number no set: the limit is 1 or more",
));
}
Ok(Some(limit))
}
/// `(u64, str, ...)` after a declaration's arity, if there.
fn parse_decl_types(input: ParseStream) -> syn::Result<Option<Vec<Ident>>> {
if !input.peek(syn::token::Paren) {
return Ok(None);
}
let inner;
parenthesized!(inner in input);
let types = Punctuated::<Ident, Token![,]>::parse_terminated(&inner)?;
for t in &types {
if type_tokens(t).is_none() {
return Err(syn::Error::new(
t.span(),
"a column type is one of `u64`, `i64`, `f64`, `bool`, `str`",
));
}
}
Ok(Some(types.into_iter().collect()))
}
/// `kleene_datalog::Type::..` of a type written `u64`, `i64`, `f64`, `bool`, `str`.
fn type_tokens(t: &Ident) -> Option<TokenStream> {
let v = match t.unraw().to_string().as_str() {
"u64" => quote!(U64),
"i64" => quote!(I64),
"f64" => quote!(F64),
"bool" => quote!(Bool),
"str" => quote!(Str),
_ => return None,
};
Some(quote!(::kleene_datalog::Type::#v))
}
/// The catalog's name after `from CAT`, if given: quoted, or a Rust expression in braces
/// that gives a `&str` (a constant, a path, a local); its span and tokens.
type CatName = Option<(Span, TokenStream)>;
/// `from CAT ["catalog name" | {expr}]`, if there: the catalog (a local or `{expr}`) and the
/// name.
fn parse_from(input: ParseStream) -> syn::Result<Option<(Span, TokenStream, CatName, bool)>> {
if !input.peek(kw::from) {
return Ok(None);
}
let span = input.parse::<kw::from>()?.span;
let cat = if input.peek(syn::token::Brace) {
let e: syn::ExprBlock = input.parse()?;
let inner = &e.block;
quote!((#inner))
} else if input.peek(Ident) {
let i: Ident = input.parse()?;
quote!(#i)
} else {
return Err(input.error("expected the catalog: a local, or a Rust expression in braces"));
};
let name = if input.peek(LitStr) {
let q = input.parse::<LitStr>()?;
Some((q.span(), quote!(#q)))
} else if input.peek(syn::token::Brace) {
let e: syn::ExprBlock = input.parse()?;
let inner = &e.block;
Some((e.span(), quote!((#inner))))
} else {
None
};
let or_empty = input.peek(kw::or) && input.peek2(kw::empty);
if or_empty {
input.parse::<kw::or>()?;
input.parse::<kw::empty>()?;
}
Ok(Some((span, cat, name, or_empty)))
}
/// A declaration from its parts, refused where they do not go together.
fn decl_of(
kind: Kind,
path: Vec<Ident>,
(arity, n): (usize, &LitInt),
types: Option<Vec<Ident>>,
shown: Option<LitStr>,
from: Option<(Span, TokenStream, CatName, bool)>,
) -> syn::Result<Decl> {
let written = path
.iter()
.map(|i| i.unraw().to_string())
.collect::<Vec<_>>()
.join(".");
let err = |span: Span, m: &str| Err(syn::Error::new(span, m));
if let Some(t) = &types {
if from.is_none() {
return err(
n.span(),
"column types are given to an input read `from` a catalog",
);
}
if t.len() != arity {
return err(
n.span(),
&format!("{} column types for a relation of {arity}", t.len()),
);
}
}
let from = match from {
None if path.len() > 1 => {
return err(
path[1].span(),
&format!("a dotted name is a catalog's: `input {written}/{arity} from cat.`"),
);
}
None => None,
Some((span, ..)) if kind != Kind::Input => {
return err(span, "only an input is read `from` a catalog");
}
Some(_) if shown.is_some() => {
return err(
shown.as_ref().expect("given").span(),
"an input read `from` a catalog is shown by the catalog's name: no `as`",
);
}
Some((_, _, Some((at, _)), _)) if path.len() > 1 => {
return err(
at,
"with a catalog name given (quoted or in braces), the name before it is one \
identifier",
);
}
Some((_, cat, given, or_empty)) => Some(FromCat {
cat,
name: given.map_or_else(|| quote!(#written), |(_, t)| t),
types,
or_empty,
}),
};
let name = if path.len() == 1 {
path[0].clone()
} else {
let joined = path
.iter()
.map(|i| i.unraw().to_string())
.collect::<Vec<_>>()
.join("_");
Ident::new(&joined, path[0].span())
};
let text = shown.map_or_else(|| written.clone(), |s| s.value());
Ok(Decl {
kind,
name,
arity,
arity_span: n.span(),
text,
key: written,
from,
limit: None,
})
}
/// The statement that declares `d` on program `p`, its handle bound to its name.
fn decl_stmt(d: &Decl, p: &Ident, fail: &TokenStream) -> TokenStream {
let (name, text) = (&d.name, &d.text);
let n = proc_macro2::Literal::usize_unsuffixed(d.arity);
let span = d.arity_span;
let Some(f) = &d.from else {
let method = match d.kind {
Kind::Input => quote!(input),
Kind::External => quote!(external),
Kind::Derived => quote!(derived),
Kind::Counted => quote!(derived_counted),
Kind::Sets => {
let limit = match d.limit {
Some(l) => quote!(::core::option::Option::Some(#l)),
None => quote!(::core::option::Option::None),
};
return quote_spanned! {span=>
let #name: ::kleene_datalog::Rel<#n> = #p.sets::<#n>(#text, #limit);
};
}
};
return quote_spanned! {span=>
let #name: ::kleene_datalog::Rel<#n> = #p.#method::<#n>(#text);
};
};
let (cat, cat_name) = (&f.cat, &f.name);
if f.or_empty {
let types: Vec<TokenStream> = match &f.types {
Some(t) => t.iter().filter_map(type_tokens).collect(),
None => vec![quote!(::kleene_datalog::Type::U64); d.arity],
};
return quote_spanned! {span=>
let __datalog_name: &str = #cat_name;
let #name: ::kleene_datalog::Rel<#n> = match #p.input_or_empty::<#n>(
::kleene_datalog::__private::catalog(&#cat),
__datalog_name,
[#(#types),*],
) {
::core::result::Result::Ok(r) => r,
::core::result::Result::Err(e) => { #fail(e); }
};
};
}
let check = f.types.as_ref().map(|types| {
let ts: Vec<TokenStream> = types.iter().filter_map(type_tokens).collect();
quote! {
let __datalog_want: &[::kleene_datalog::Type] = &[#(#ts),*];
let __datalog_have = #p.types(::kleene_datalog::Rel::id(&#name));
if __datalog_have[..] != *__datalog_want {
#fail(::kleene_datalog::DatalogError::Input(::std::format!(
"`{}` has columns {:?} in the catalog, the text gives {:?}",
__datalog_name, __datalog_have, __datalog_want
)));
}
}
});
quote_spanned! {span=>
let __datalog_name: &str = #cat_name;
let #name: ::kleene_datalog::Rel<#n> =
match #p.input_from::<#n>(::kleene_datalog::__private::catalog(&#cat), __datalog_name) {
::core::result::Result::Ok(r) => r,
::core::result::Result::Err(e) => { #fail(e); }
};
#check
}
}
fn parse_relref(input: ParseStream) -> syn::Result<RelRef> {
if input.peek(syn::token::Brace) {
return Ok(RelRef::Expr(input.parse()?));
}
let mut path = vec![Ident::parse_any(input)?];
while input.peek(Token![.]) && !input.peek(Token![..]) && input.peek2(Ident::peek_any) {
input.parse::<Token![.]>()?;
path.push(Ident::parse_any(input)?);
}
Ok(RelRef::Path(path))
}
fn parse_atom(input: ParseStream) -> syn::Result<Atom> {
let rel = parse_relref(input)?;
if !input.peek(syn::token::Paren) {
return Err(input.error(format!("expected the terms of `{}` in `( )`", rel.show())));
}
let content;
let paren = parenthesized!(content in input);
let exprs = Punctuated::<Expr, Token![,]>::parse_terminated(&content)?;
let terms = exprs.into_iter().map(term_of).collect();
Ok(Atom {
rel,
args_span: paren.span.join(),
terms,
})
}
/// A term of an atom, from the expression written.
fn term_of(e: Expr) -> Term {
match e {
// syn reads `-1` as one literal where it parses a literal
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(l),
..
}) if l.suffix().is_empty() && l.base10_digits().starts_with('-') => {
Term::Neg(l.span(), LitInt::new(&l.base10_digits()[1..], l.span()))
}
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Float(l),
..
}) if l.suffix().is_empty() && l.base10_digits().starts_with('-') => Term::Float(
l.span(),
true,
LitFloat::new(&l.base10_digits()[1..], l.span()),
),
Expr::Infer(i) => Term::Wild(i.underscore_token.span),
Expr::Path(p)
if p.qself.is_none()
&& p.attrs.is_empty()
&& p.path.leading_colon.is_none()
&& p.path.segments.len() == 1
&& p.path.segments[0].arguments.is_none()
&& is_var_name(&p.path.segments[0].ident) =>
{
Term::Var(p.path.segments[0].ident.clone())
}
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(l),
..
}) if l.suffix().is_empty() => Term::Lit(l),
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Float(l),
..
}) if l.suffix().is_empty() => Term::Float(l.span(), false, l),
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(l),
..
}) => Term::Str(l),
Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(m),
expr,
attrs,
}) if attrs.is_empty() => match *expr {
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(l),
..
}) if l.suffix().is_empty() => Term::Neg(m.span, l),
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Float(l),
..
}) if l.suffix().is_empty() => Term::Float(m.span, true, l),
e => Term::Rust(Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(m),
expr: Box::new(e),
attrs,
})),
},
// `{expr}`: the expression itself (braces around one expression would warn)
Expr::Block(b)
if b.label.is_none()
&& b.attrs.is_empty()
&& b.block.stmts.len() == 1
&& matches!(b.block.stmts[0], syn::Stmt::Expr(_, None)) =>
{
match b.block.stmts.into_iter().next() {
Some(syn::Stmt::Expr(
Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(l),
..
}),
None,
)) if l.suffix().is_empty() => Term::Lit(l),
Some(syn::Stmt::Expr(e, None)) => Term::Rust(e),
_ => unreachable!("one expression"),
}
}
e => Term::Rust(e),
}
}
/// A term of a condition: `_`, a name, a literal, a path or a call, or `{ expr }`.
fn parse_cond_term(input: ParseStream) -> syn::Result<Term> {
if input.peek(Token![_]) {
let u: Token![_] = input.parse()?;
return Ok(Term::Wild(u.span));
}
if input.peek(syn::token::Brace) {
return Ok(term_of(Expr::Block(input.parse()?)));
}
// a literal, `-1` and `-0.5` included
if input.peek(syn::Lit) {
return Ok(term_of(Expr::Lit(input.parse()?)));
}
let path = input.call(syn::Path::parse_mod_style)?;
let func = Expr::Path(syn::ExprPath {
attrs: Vec::new(),
qself: None,
path,
});
if input.peek(syn::token::Paren) {
let content;
let paren_token = parenthesized!(content in input);
let args = Punctuated::<Expr, Token![,]>::parse_terminated(&content)?;
return Ok(Term::Rust(Expr::Call(syn::ExprCall {
attrs: Vec::new(),
func: Box::new(func),
paren_token,
args,
})));
}
Ok(term_of(func))
}
/// After `in`: a list, `( .. )` of members or `{expr}` whole, when the group is not followed
/// by `..` or an operator (then it is the first end of a range, `A in (LO + 1)..HI`, and
/// `None` is returned with nothing read).
fn parse_list(input: ParseStream) -> syn::Result<Option<List>> {
let paren = input.peek(syn::token::Paren);
if !paren && !input.peek(syn::token::Brace) {
return Ok(None);
}
let fork = input.fork();
fork.parse::<proc_macro2::TokenTree>()?;
let ends =
fork.is_empty() || fork.peek(Token![,]) || (fork.peek(Token![.]) && !fork.peek(Token![..]));
if !ends {
return Ok(None);
}
if !paren {
let Term::Rust(e) = term_of(Expr::Block(input.parse()?)) else {
return Err(input.error(
"one value, not a list: write `X = {..}`, or `X in ({..})` for a list of one",
));
};
return Ok(Some(List::Whole(e)));
}
let content;
parenthesized!(content in input);
let mut members = Vec::new();
while !content.is_empty() {
let start = content.span();
let m = match parse_expr(&content, 0)? {
Ex::Term(Term::Var(v)) => {
return Err(syn::Error::new(
v.span(),
format!(
"a list member is a constant or a Rust value in braces; `{}` is a variable",
v.unraw()
),
));
}
Ex::Term(Term::Wild(s)) => {
return Err(syn::Error::new(
s,
"a list member is a constant or a Rust value in braces; `_` is a variable",
));
}
Ex::Term(t) => t,
_ => {
return Err(syn::Error::new(
start,
"a list member is a constant or a Rust value in braces, not an expression",
));
}
};
members.push(m);
if content.is_empty() {
break;
}
content.parse::<Token![,]>()?;
}
Ok(Some(List::Members(members)))
}
fn parse_lit(input: ParseStream) -> syn::Result<Lit> {
// `!(x in (..))`: a negated list test (another `!( .. )` starts an expression)
if input.peek(Token![!]) && input.peek2(syn::token::Paren) {
let fork = input.fork();
fork.parse::<Token![!]>()?;
let content;
parenthesized!(content in fork);
if parse_expr(&content, 0).is_ok() && content.peek(Token![in]) {
let bang: Token![!] = input.parse()?;
let content;
parenthesized!(content in input);
let x = parse_expr(&content, 0)?;
content.parse::<Token![in]>()?;
let Some(list) = parse_list(&content)? else {
return Err(syn::Error::new(
bang.span,
"only a list test can be negated: `!(X in (..))`; a negated range is not covered",
));
};
if !content.is_empty() {
return Err(content.error("expected `)` after the list"));
}
return Ok(Lit::OneOf(x, list, true));
}
}
// `!rel(..)` is a negated atom; another `!` starts an expression (`!X & M == 0`)
if input.peek(Token![!]) && !input.peek(Token![!=]) {
let fork = input.fork();
fork.parse::<Token![!]>()?;
let atom = parse_atom(&fork).is_ok()
&& (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![.]));
if atom
|| !(input.peek2(Ident)
|| input.peek2(syn::token::Paren)
|| input.peek2(syn::token::Brace)
|| input.peek2(Token![-])
|| input.peek2(Token![!]))
{
input.parse::<Token![!]>()?;
return Ok(Lit::Neg(parse_atom(input)?));
}
}
let fork = input.fork();
if let Ok(a) = parse_atom(&fork)
&& (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![.]))
{
let _ = a;
return Ok(Lit::Pos(parse_atom(input)?));
}
// `VAR = expr`
if input.peek(Ident)
&& input.peek2(Token![=])
&& !input.peek2(Token![==])
&& !input.peek2(Token![=>])
{
let v: Ident = input.parse()?;
if !is_var_name(&v) {
return Err(syn::Error::new(
v.span(),
"a computed value's variable starts with an uppercase letter or `_`",
));
}
input.parse::<Token![=]>()?;
return Ok(Lit::Compute(v, parse_expr(input, 0)?));
}
let left = parse_expr(input, 0)?;
if input.peek(Token![in]) {
input.parse::<Token![in]>()?;
if let Some(list) = parse_list(input)? {
return Ok(Lit::OneOf(left, list, false));
}
let lo = parse_expr(input, 0)?;
input.parse::<Token![..]>()?;
let hi = parse_expr(input, 0)?;
return Ok(Lit::Within(left, lo, hi));
}
if input.peek(kw::is) && (input.peek2(kw::null) || input.peek2(kw::not)) {
input.parse::<kw::is>()?;
let null = if input.peek(kw::not) {
input.parse::<kw::not>()?;
false
} else {
true
};
input.parse::<kw::null>()?;
let Ex::Term(left) = left else {
return Err(input.error("a null test is on a term, not an expression"));
};
return Ok(Lit::Null(left, null));
}
let text = if input.peek(kw::starts) && input.peek2(kw::with) {
input.parse::<kw::starts>()?;
input.parse::<kw::with>()?;
Some(TextOp::StartsWith)
} else if input.peek(kw::ends) && input.peek2(kw::with) {
input.parse::<kw::ends>()?;
input.parse::<kw::with>()?;
Some(TextOp::EndsWith)
} else if input.peek(kw::contains) {
input.parse::<kw::contains>()?;
Some(TextOp::Contains)
} else {
None
};
if let Some(op) = text {
let pat = parse_cond_term(input)?;
let Ex::Term(left) = left else {
return Err(input.error("a string test is on a term, not an expression"));
};
return Ok(Lit::Text(left, op, pat));
}
let op = if input.peek(Token![==]) {
input.parse::<Token![==]>()?;
Op::Eq
} else if input.peek(Token![!=]) {
input.parse::<Token![!=]>()?;
Op::Ne
} else if input.peek(Token![<=]) {
input.parse::<Token![<=]>()?;
Op::Le
} else if input.peek(Token![>=]) {
input.parse::<Token![>=]>()?;
Op::Ge
} else if input.peek(Token![<]) {
input.parse::<Token![<]>()?;
Op::Lt
} else if input.peek(Token![>]) {
input.parse::<Token![>]>()?;
Op::Gt
} else {
return Err(input.error(
"expected an atom `rel(..)`, a negated atom `!rel(..)`, a computed value \
`X = expr`, a comparison (`==`, `!=`, `<`, `<=`, `>`, `>=`), a range \
`X in Lo..Hi` or a string test (`X starts with \"..\"`, `ends with`, \
`contains`); an expression alone is not a literal",
));
};
let right = parse_expr(input, 0)?;
Ok(Lit::Cmp(left, op, right))
}
/// The operator next in `input`, if one is.
fn peek_op(input: ParseStream) -> Option<BinOp> {
Some(if input.peek(Token![<<]) && !input.peek(Token![<<=]) {
BinOp::Shl
} else if input.peek(Token![>>]) && !input.peek(Token![>>=]) {
BinOp::Shr
} else if input.peek(Token![+]) && !input.peek(Token![+=]) {
BinOp::Add
} else if input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) {
BinOp::Sub
} else if input.peek(Token![*]) && !input.peek(Token![*=]) {
BinOp::Mul
} else if input.peek(Token![/]) && !input.peek(Token![/=]) {
BinOp::Div
} else if input.peek(Token![%]) && !input.peek(Token![%=]) {
BinOp::Rem
} else if input.peek(Token![&]) && !input.peek(Token![&&]) && !input.peek(Token![&=]) {
BinOp::And
} else if input.peek(Token![|]) && !input.peek(Token![||]) && !input.peek(Token![|=]) {
BinOp::Or
} else if input.peek(Token![^]) && !input.peek(Token![^=]) {
BinOp::Xor
} else {
return None;
})
}
fn take_op(input: ParseStream, op: BinOp) -> syn::Result<()> {
match op {
BinOp::Shl => input.parse::<Token![<<]>().map(drop),
BinOp::Shr => input.parse::<Token![>>]>().map(drop),
BinOp::Add => input.parse::<Token![+]>().map(drop),
BinOp::Sub => input.parse::<Token![-]>().map(drop),
BinOp::Mul => input.parse::<Token![*]>().map(drop),
BinOp::Div => input.parse::<Token![/]>().map(drop),
BinOp::Rem => input.parse::<Token![%]>().map(drop),
BinOp::And => input.parse::<Token![&]>().map(drop),
BinOp::Or => input.parse::<Token![|]>().map(drop),
BinOp::Xor => input.parse::<Token![^]>().map(drop),
}
}
/// A term, an expression in `( )`, a string function `f(expr, ..)`, or `-` or `!` before
/// one of those.
fn parse_primary(input: ParseStream) -> syn::Result<Ex> {
// `-1`, `-0.5`: a negative literal, one term
if input.peek(Token![-]) && (input.peek2(syn::LitInt) || input.peek2(syn::LitFloat)) {
let m: Token![-] = input.parse()?;
let l: syn::Lit = input.parse()?;
return Ok(Ex::Term(term_of(Expr::Unary(syn::ExprUnary {
attrs: Vec::new(),
op: syn::UnOp::Neg(m),
expr: Box::new(Expr::Lit(syn::ExprLit {
attrs: Vec::new(),
lit: l,
})),
}))));
}
if input.peek(Ident) && input.peek2(syn::token::Paren) {
let fork = input.fork();
let f: Ident = fork.parse()?;
let name = f.unraw().to_string();
if let Some(&(_, _, lo, hi)) = FUNCS.iter().find(|x| x.0 == name) {
input.parse::<Ident>()?;
let content;
parenthesized!(content in input);
let args: Vec<Ex> =
Punctuated::<Ex, Token![,]>::parse_terminated_with(&content, |c| parse_expr(c, 0))?
.into_iter()
.collect();
if args.len() < lo || args.len() > hi {
let want = match (lo, hi) {
(1, 1) => "1 argument".to_string(),
(l, usize::MAX) => format!("{l} or more arguments"),
(l, h) => format!("{l} to {h} arguments"),
};
return Err(syn::Error::new(
f.span(),
format!("{name}(..) takes {want}, not {}", args.len()),
));
}
return Ok(Ex::Call(f, args));
}
}
if input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) {
input.parse::<Token![-]>()?;
return Ok(Ex::Un(true, Box::new(parse_primary(input)?)));
}
if input.peek(Token![!]) && !input.peek(Token![!=]) {
input.parse::<Token![!]>()?;
return Ok(Ex::Un(false, Box::new(parse_primary(input)?)));
}
if input.peek(syn::token::Paren) {
let content;
parenthesized!(content in input);
let e = parse_expr(&content, 0)?;
if !content.is_empty() {
return Err(content.error("expected an operator or `)`"));
}
return Ok(e);
}
Ok(Ex::Term(parse_cond_term(input)?))
}
/// An expression whose operators bind at least as tight as `min` (Rust's precedence, each
/// left-associative): terms as in a condition, in `( )` where wanted.
fn parse_expr(input: ParseStream, min: u8) -> syn::Result<Ex> {
let mut left = parse_primary(input)?;
while let Some(op) = peek_op(input) {
let p = op.precedence();
if p < min {
break;
}
take_op(input, op)?;
let right = parse_expr(input, p + 1)?;
left = Ex::Op(op, Box::new(left), Box::new(right));
}
Ok(left)
}
/// Whether the body starts with an aggregate: `[N =] count|rank|set|min|max|exactly_one (..)`,
/// or reductions `OUT = count|sum|avg|least|greatest (..)` separated by `,`, followed by
/// `by`, `in` or `:`.
fn is_agg(input: ParseStream) -> bool {
let fork = input.fork();
loop {
if fork.peek(Ident) && fork.peek2(Token![=]) && !fork.peek2(Token![==]) {
let _ = fork.parse::<Ident>();
let _ = fork.parse::<Token![=]>();
}
let Ok(f) = fork.parse::<Ident>() else {
return false;
};
let names = [
"count",
"rank",
"set",
"min",
"max",
"exactly_one",
"sum",
"avg",
"least",
"greatest",
];
if !names.contains(&f.to_string().as_str()) {
return false;
}
if !fork.peek(syn::token::Paren) || fork.parse::<proc_macro2::TokenTree>().is_err() {
return false;
}
if fork.peek(Token![,]) && fork.peek2(Ident) && fork.peek3(Token![=]) {
let _ = fork.parse::<Token![,]>();
continue;
}
return fork.peek(kw::by)
|| fork.peek(Token![in])
|| (fork.peek(Token![:]) && !fork.peek2(Token![-]));
}
}
/// Whether a bare name is a Datalog variable: it starts with an uppercase letter or `_`.
/// Any other bare name is a Rust value in scope.
fn is_var_name(i: &Ident) -> bool {
let s = i.unraw().to_string();
s.starts_with(|c: char| c.is_uppercase() || c == '_')
}
fn vars_in_parens(input: ParseStream) -> syn::Result<Vec<Ident>> {
let content;
parenthesized!(content in input);
let vars: Vec<Ident> = Punctuated::<Ident, Token![,]>::parse_terminated(&content)?
.into_iter()
.collect();
for v in &vars {
if !is_var_name(v) {
return Err(syn::Error::new(
v.span(),
"an aggregate's variable starts with an uppercase letter or `_`",
));
}
}
Ok(vars)
}
fn parse_agg(input: ParseStream) -> syn::Result<Agg> {
let start = input.span();
if !(input.peek(Ident) && input.peek2(Token![=])) {
// `min (..)`, `max (..)`, `exactly_one (..)`: the binding, no result variable
let f: Ident = input.parse()?;
let of = vars_in_parens(input)?;
let kind = match f.to_string().as_str() {
w @ ("count" | "rank") => {
return Err(syn::Error::new(
f.span(),
format!("a {w} names its result: `N = {w}(..)`"),
));
}
"set" => {
return Err(syn::Error::new(
f.span(),
"a set number names its result: `N = set(..) in NAME`",
));
}
"min" => AggKind::Min,
"max" => AggKind::Max,
"exactly_one" => AggKind::One,
_ => {
return Err(syn::Error::new(
f.span(),
"a reduction names its result: `S = sum(X)`",
));
}
};
if of.is_empty() {
return Err(syn::Error::new(f.span(), "an aggregate needs a variable"));
}
return finish_agg(input, kind, of, start);
}
// `OUT = f(..)`, one or several
let mut list: Vec<(Ident, Ident, Vec<Ident>)> = Vec::new();
loop {
let o: Ident = input.parse()?;
input.parse::<Token![=]>()?;
let f: Ident = input.parse()?;
let of = vars_in_parens(input)?;
if !is_var_name(&o) {
return Err(syn::Error::new(
o.span(),
format!("a {f}'s result is a variable: it starts with an uppercase letter or `_`"),
));
}
list.push((o, f, of));
if input.peek(Token![,]) && input.peek2(Ident) && input.peek3(Token![=]) {
input.parse::<Token![,]>()?;
} else {
break;
}
}
let one = list.len() == 1;
let mut reds = Vec::new();
for (o, f, of) in list {
let red = match f.to_string().as_str() {
"count" if one && of.is_empty() => {
return finish_agg(input, AggKind::Bag(o), of, start);
}
"count" if one => return finish_agg(input, AggKind::Count(o), of, start),
"rank" if one => {
if of.is_empty() {
return Err(syn::Error::new(f.span(), "an aggregate needs a variable"));
}
return finish_agg(input, AggKind::Rank(o), of, start);
}
"set" if one => {
if of.is_empty() {
return Err(syn::Error::new(f.span(), "an aggregate needs a variable"));
}
return finish_set(input, o, of, start);
}
"count" => Red::Count,
"sum" => Red::Sum,
"avg" => Red::Avg,
"least" => Red::Least,
"greatest" => Red::Greatest,
"rank" => {
return Err(syn::Error::new(f.span(), "a rank stands alone in its rule"));
}
"set" => {
return Err(syn::Error::new(
f.span(),
"a set number stands alone in its rule",
));
}
"min" | "max" | "exactly_one" => {
return Err(syn::Error::new(
o.span(),
format!(
"`{f}` takes no result variable: it gives the head the values of its \
binding; the least or greatest value is `{} = least(..)` or \
`greatest(..)`",
o.unraw()
),
));
}
_ => {
return Err(syn::Error::new(
f.span(),
"expected a reduction: count, sum, avg, least or greatest",
));
}
};
if red != Red::Count && of.len() != 1 {
return Err(syn::Error::new(
f.span(),
format!("`{f}` reduces one variable"),
));
}
reds.push((red, o, of));
}
let of = reds.iter().flat_map(|r| r.2.iter().cloned()).collect();
finish_agg(input, AggKind::Many(reds), of, start)
}
/// The rest of a set number: `by (..)` if written, then `in NAME` and `:`.
fn finish_set(input: ParseStream, out: Ident, of: Vec<Ident>, span: Span) -> syn::Result<Agg> {
let group = group_by(input)?;
if !input.peek(Token![in]) {
return Err(
input.error("a set number names its table of sets: `N = set(..) by (..) in NAME:`")
);
}
input.parse::<Token![in]>()?;
let table = parse_relref(input)?;
input.parse::<Token![:]>()?;
Ok(Agg {
kind: AggKind::Set(out, table),
of,
group,
span,
})
}
/// `by (..)`, if written: the grouping variables.
fn group_by(input: ParseStream) -> syn::Result<Vec<Ident>> {
if input.peek(kw::by) {
input.parse::<kw::by>()?;
vars_in_parens(input)
} else {
Ok(Vec::new())
}
}
/// The rest of an aggregate: `by (..)` if written, then `:`.
fn finish_agg(input: ParseStream, kind: AggKind, of: Vec<Ident>, span: Span) -> syn::Result<Agg> {
let group = group_by(input)?;
input.parse::<Token![:]>()?;
Ok(Agg {
kind,
of,
group,
span,
})
}
/// The variable names of a rule, checked against what binds them (the builder makes the same
/// checks at run time; these point at the token).
fn check_rule(r: &Rule) -> syn::Result<()> {
let mut bound: HashSet<String> = HashSet::new();
let mut any_pos = false;
for l in &r.body {
if let Lit::Pos(a) = l {
any_pos = true;
for t in &a.terms {
if let Term::Var(v) = t {
bound.insert(v.unraw().to_string());
}
}
}
}
if !any_pos {
return Err(syn::Error::new(
r.head.rel.span(),
"a rule needs a positive body atom",
));
}
// the computed values bind their variables once their operands are bound
let mut computes: Vec<(&Ident, &Ex)> = r
.body
.iter()
.filter_map(|l| match l {
Lit::Compute(v, e) => Some((v, e)),
_ => None,
})
.collect();
while let Some(i) = computes.iter().position(|(_, e)| {
e.vars()
.iter()
.all(|v| bound.contains(&v.unraw().to_string()))
}) {
let (v, _) = computes.remove(i);
bound.insert(v.unraw().to_string());
}
let is_bound = |v: &Ident| bound.contains(&v.unraw().to_string());
let wild = |s: Span, what: &str| {
Err(syn::Error::new(
s,
format!("`_` in {what} is bound by no positive atom"),
))
};
for l in &r.body {
let mut ts: Vec<&Term> = Vec::new();
let (terms, what): (Vec<&Term>, &str) = match l {
Lit::Pos(_) => continue,
Lit::Neg(a) => (a.terms.iter().collect(), "a negated atom"),
Lit::Cmp(a, _, b) => {
a.terms(&mut ts);
b.terms(&mut ts);
(ts, "a condition")
}
Lit::Within(a, b, c) => {
a.terms(&mut ts);
b.terms(&mut ts);
c.terms(&mut ts);
(ts, "a condition")
}
Lit::Text(a, _, b) => {
ts.push(a);
ts.push(b);
(ts, "a condition")
}
Lit::Compute(_, e) => {
e.terms(&mut ts);
(ts, "a computed value")
}
Lit::Null(a, _) => {
ts.push(a);
(ts, "a condition")
}
Lit::OneOf(a, ..) => {
a.terms(&mut ts);
(ts, "a condition")
}
};
for t in terms {
match t {
Term::Wild(s) => return wild(*s, what),
Term::Var(v) if !is_bound(v) => {
return Err(syn::Error::new(
v.span(),
format!(
"variable {} of {what} is bound by no positive atom or computed value",
v.unraw()
),
));
}
_ => {}
}
}
}
let head_vars: Vec<&Ident> = r
.head
.terms
.iter()
.filter_map(|t| match t {
Term::Var(v) => Some(v),
_ => None,
})
.collect();
for t in &r.head.terms {
if let Term::Wild(s) = t {
return wild(*s, "the head");
}
}
let same = |a: &Ident, b: &Ident| a.unraw() == b.unraw();
match &r.agg {
None => {
for v in &head_vars {
if !is_bound(v) {
return Err(syn::Error::new(
v.span(),
format!("head variable {} is bound by no body atom", v.unraw()),
));
}
}
}
Some(a) => {
for v in a.group.iter().chain(&a.of) {
if !is_bound(v) {
return Err(syn::Error::new(
v.span(),
format!(
"aggregate variable {} is bound by no positive atom",
v.unraw()
),
));
}
}
for g in &a.group {
if !head_vars.iter().any(|h| same(h, g)) {
return Err(syn::Error::new(
g.span(),
format!("grouping variable {} is not in the head", g.unraw()),
));
}
}
let outs: Vec<&Ident> = match &a.kind {
AggKind::Count(o) | AggKind::Bag(o) | AggKind::Rank(o) | AggKind::Set(o, _) => {
vec![o]
}
AggKind::Many(reds) => reds.iter().map(|r| &r.1).collect(),
_ => Vec::new(),
};
for o in &outs {
if is_bound(o) {
let what = match a.kind {
AggKind::Rank(_) => "position",
AggKind::Set(..) => "set number",
AggKind::Count(_) | AggKind::Bag(_) => "count",
_ => "result",
};
return Err(syn::Error::new(
o.span(),
format!("the {what} {} is bound by a body atom", o.unraw()),
));
}
}
if let AggKind::Bag(o) = &a.kind {
// the head is the group, then the count
let last = matches!(r.head.terms.last(), Some(Term::Var(v)) if same(v, o));
let rest: Vec<&Ident> = r.head.terms[..r.head.terms.len() - 1]
.iter()
.filter_map(|t| match t {
Term::Var(v) => Some(v),
_ => None,
})
.collect();
let grouped = rest.len() == a.group.len()
&& rest.iter().all(|h| a.group.iter().any(|g| same(g, h)));
if !last || !grouped {
return Err(syn::Error::new(
o.span(),
format!(
"a bag count's head is its `by` variables, then the count {}",
o.unraw()
),
));
}
}
for v in &head_vars {
let gives = a.group.iter().any(|g| same(g, v))
|| outs.iter().any(|o| same(o, v))
|| match &a.kind {
AggKind::Rank(_) => is_bound(v),
AggKind::Min | AggKind::Max => is_bound(v),
AggKind::One => a.of.iter().any(|o| same(o, v)),
_ => false,
};
if !gives {
return Err(syn::Error::new(
v.span(),
format!(
"head variable {} is neither grouped nor given by the aggregate",
v.unraw()
),
));
}
}
}
}
Ok(())
}
/// What the macro knows of a relation it declared.
/// A literal term as a `Constant` expression (an error's tokens for one out of range).
fn literal(t: &Term) -> TokenStream {
let span = t.span();
match t {
Term::Lit(l) => quote_spanned!(span=> ::kleene_datalog::Constant::Uint(#l)),
Term::Neg(_, l) => {
// the value made here: `-1.` lexes the number as a float and comes back as
// a u64 literal, which Rust does not negate
let n = match l.base10_parse::<u64>() {
Ok(n) if n <= 1 << 63 => (n as i128).wrapping_neg() as i64,
_ => {
let e = syn::Error::new(span, "a negative integer below i64::MIN");
return e.to_compile_error();
}
};
// a negative literal token may come back as `-` and a literal: write it so
let n = if n == i64::MIN {
quote!(::core::primitive::i64::MIN)
} else {
let abs = proc_macro2::Literal::i64_suffixed(-n);
quote!((-#abs))
};
quote_spanned!(span=> ::kleene_datalog::Constant::Int(#n))
}
Term::Float(_, false, l) => {
quote_spanned!(span=> ::kleene_datalog::Constant::Float(#l))
}
Term::Float(_, true, l) => {
quote_spanned!(span=> ::kleene_datalog::Constant::Float(-#l))
}
Term::Str(l) => {
quote_spanned!(span=> ::kleene_datalog::Constant::Str(::std::string::String::from(#l)))
}
Term::Var(_) | Term::Wild(_) | Term::Rust(_) => unreachable!("a literal"),
}
}
struct Known {
kind: Kind,
arity: usize,
/// The handle the rules' atoms use (`sym_info` for `sym.info`).
handle: Ident,
}
struct Ctx {
/// The relations declared in this invocation.
known: HashMap<String, Known>,
/// Whether the program is new (every relation must be declared here).
closed: bool,
/// Variables by name, in order of first appearance.
vars: Vec<String>,
/// Each variable's name as first written (its span), for the guard against constants.
firsts: Vec<Ident>,
/// The constants of the rule being made, each a `let` before its call: coding one
/// needs the program, which the call borrows.
pre: Vec<TokenStream>,
/// How many constants were made, for their names.
consts: usize,
/// For each variable of the rule being made, the first positive atom and column that
/// bind it: the type a constant compared with it is coded for.
binds: HashMap<String, (TokenStream, usize)>,
/// The statement that returns an error from the expansion.
fail: TokenStream,
p: Ident,
}
impl Ctx {
fn var_ident(i: usize) -> Ident {
format_ident!("__datalog_v{}", i, span = Span::mixed_site())
}
fn see_var(&mut self, v: &Ident) -> Ident {
let name = v.unraw().to_string();
let i = match self.vars.iter().position(|n| !n.is_empty() && *n == name) {
Some(i) => i,
None => {
self.vars.push(name);
self.firsts.push(v.clone());
self.vars.len() - 1
}
};
Ctx::var_ident(i)
}
/// What this invocation declared of `rel`, written as declared (`reach`, `sym.info`).
fn known_of(&self, rel: &RelRef) -> Option<&Known> {
match rel {
RelRef::Path(_) => self.known.get(&rel.show()),
RelRef::Expr(_) => None,
}
}
/// `rel` as Rust: the handle of a relation declared here, else as written.
fn rel_tokens(&self, rel: &RelRef) -> TokenStream {
match self.known_of(rel) {
Some(k) => {
let h = &k.handle;
quote!(#h)
}
None => rel.tokens(),
}
}
fn check_rel(&self, rel: &RelRef, arity: usize, args: Span, head: bool) -> syn::Result<()> {
match self.known_of(rel) {
Some(k) => {
if k.arity != arity {
return Err(syn::Error::new(
args,
format!(
"`{}` has {} column{}; this atom gives {arity}",
rel.show(),
k.arity,
if k.arity == 1 { "" } else { "s" }
),
));
}
if head && k.kind == Kind::Sets {
return Err(syn::Error::new(
rel.span(),
format!(
"`{0}` is a table of sets: no rule derives it; rules number into it \
(`N = set(..) in {0}`)",
rel.show()
),
));
}
if head && !matches!(k.kind, Kind::Derived | Kind::Counted) {
return Err(syn::Error::new(
rel.span(),
format!(
"`{}` is given, not derived; a rule cannot derive it",
rel.show()
),
));
}
Ok(())
}
None if self.closed => Err(syn::Error::new(
rel.span(),
format!(
"unknown relation `{}`: declare it with `input`, `external`, `derived` or `sets` \
(or add rules to a program in hand: `datalog!(p => ..)`)",
rel.show()
),
)),
None => Ok(()),
}
}
/// `in NAME` of a set number whose element has `width` columns: NAME a table of sets of
/// `width + 1` columns, where this invocation declares it.
fn check_table(&self, table: &RelRef, width: usize) -> syn::Result<()> {
match self.known_of(table) {
Some(k) if k.kind != Kind::Sets => Err(syn::Error::new(
table.span(),
format!(
"`{0}` is not a table of sets: declare it with `sets {0}/{1}.`",
table.show(),
width + 1
),
)),
Some(k) if k.arity != width + 1 => Err(syn::Error::new(
table.span(),
format!(
"`{}` holds sets of elements of {} column{}; this set's have {width}",
table.show(),
k.arity - 1,
if k.arity == 2 { "" } else { "s" }
),
)),
Some(_) => Ok(()),
None if self.closed => Err(syn::Error::new(
table.span(),
format!(
"unknown table of sets `{0}`: declare it with `sets {0}/{1}.`",
table.show(),
width + 1
),
)),
None => Ok(()),
}
}
fn term(&mut self, t: &Term) -> TokenStream {
let span = t.span();
match t {
Term::Var(v) => {
let id = self.see_var(v);
quote_spanned!(span=> ::kleene_datalog::Term::Var(#id))
}
Term::Wild(_) => {
// an empty name: a variable of its own, printed `_`
self.vars.push(String::new());
let id = Ctx::var_ident(self.vars.len() - 1);
quote_spanned!(span=> ::kleene_datalog::Term::Var(#id))
}
_ => self.place(t, quote!(::core::option::Option::None)),
}
}
/// A term at a place whose type `ty` (an `Option<Type>` expression) is known when the
/// program is built: a literal is coded for it ([`Program::constant`]) in a `let`
/// before the rule's call; a variable and a Rust value are themselves.
fn place(&mut self, t: &Term, ty: TokenStream) -> TokenStream {
let span = t.span();
let val = match t {
Term::Var(_) | Term::Wild(_) => return self.term(t),
// a Rust value is its raw value, as the builder takes it
Term::Rust(e) => return quote_spanned!(span=> ::kleene_datalog::__private::term(#e)),
_ => literal(t),
};
let id = format_ident!("__datalog_c{}", self.consts, span = Span::mixed_site());
self.consts += 1;
let (p, fail) = (&self.p, &self.fail);
self.pre.push(quote_spanned! {span=>
let #id = {
let ty: ::core::option::Option<::kleene_datalog::Type> = #ty;
let x = #val;
match ::kleene_datalog::__private::konst(&mut *#p, ty, x) {
::core::result::Result::Ok(t) => t,
::core::result::Result::Err(e) => #fail(e),
}
};
});
quote!(#id)
}
/// The type of a column of `rel`, as an `Option<Type>` expression.
fn col_type(&self, rel: &TokenStream, j: usize) -> TokenStream {
let p = &self.p;
quote!(::core::option::Option::Some(#p.col_type(::kleene_datalog::Rel::id(&#rel), #j)))
}
/// The type a constant beside `others` (the other terms of its condition) is coded
/// for: the column binding the first variable among them that a positive atom binds.
fn cond_type(&self, others: &[&Term]) -> TokenStream {
for t in others {
if let Term::Var(v) = t
&& let Some((rel, j)) = self.binds.get(&v.unraw().to_string())
{
return self.col_type(rel, *j);
}
}
quote!(::core::option::Option::None)
}
/// A term of a condition: a constant typed by the variables beside it.
fn cond_term(&mut self, t: &Term, others: &[&Term]) -> TokenStream {
let ty = self.cond_type(others);
self.place(t, ty)
}
fn atom(&mut self, a: &Atom, head: bool) -> syn::Result<TokenStream> {
self.check_rel(&a.rel, a.terms.len(), a.args_span, head)?;
let rel = self.rel_tokens(&a.rel);
let terms: Vec<TokenStream> = a
.terms
.iter()
.enumerate()
.map(|(j, t)| {
let ty = self.col_type(&rel, j);
self.place(t, ty)
})
.collect();
let span = a.args_span;
let arr = quote_spanned!(span=> [#(#terms),*]);
Ok(quote_spanned!(span=> ::kleene_datalog::Rel::atom(&#rel, #arr)))
}
fn lit(&mut self, l: &Lit) -> syn::Result<TokenStream> {
Ok(match l {
Lit::Pos(a) => {
let a = self.atom(a, false)?;
quote!(::kleene_datalog::Literal::Pos(#a))
}
Lit::Neg(a) => {
let a = self.atom(a, false)?;
quote!(::kleene_datalog::Literal::Neg(#a))
}
Lit::Cmp(a, op, b) => {
let (a, b) = (self.cond_side(a, &[b]), self.cond_side(b, &[a]));
let op = match op {
Op::Eq => quote!(Eq),
Op::Ne => quote!(Ne),
Op::Lt => quote!(Lt),
Op::Le => quote!(Le),
Op::Gt => quote!(Gt),
Op::Ge => quote!(Ge),
};
quote!(::kleene_datalog::compare(#a, ::kleene_datalog::Cmp::#op, #b))
}
Lit::Within(x, lo, hi) => {
let (x, lo, hi) = (
self.cond_side(x, &[lo, hi]),
self.cond_side(lo, &[x, hi]),
self.cond_side(hi, &[x, lo]),
);
quote!(::kleene_datalog::within(#x, #lo, #hi))
}
Lit::Text(x, op, pat) => {
// the pattern is a string whatever it meets
let str_ty = quote!(::core::option::Option::Some(::kleene_datalog::Type::Str));
let (x, pat) = (self.term(x), self.place(pat, str_ty));
let op = match op {
TextOp::StartsWith => quote!(StartsWith),
TextOp::EndsWith => quote!(EndsWith),
TextOp::Contains => quote!(Contains),
};
quote!(::kleene_datalog::text(#x, ::kleene_datalog::TextOp::#op, #pat))
}
Lit::Null(x, null) => {
let x = self.term(x);
if *null {
quote!(::kleene_datalog::is_null(#x))
} else {
quote!(::kleene_datalog::is_not_null(#x))
}
}
Lit::Compute(v, e) => {
let id = self.see_var(v);
let e = self.expr(e);
quote!(::kleene_datalog::compute(#id, #e))
}
Lit::OneOf(x, list, not) => self.one_of(x, list, *not),
})
}
/// A list test: the list made in a `let` before the rule's call
/// (`__private::list`), its literals coded for the left side's type, then
/// `one_of(x, list)` or `not_one_of(x, list)`.
fn one_of(&mut self, x: &Ex, list: &List, not: bool) -> TokenStream {
let ty = match x {
Ex::Term(Term::Var(v)) => match self.binds.get(&v.unraw().to_string()) {
Some((rel, j)) => self.col_type(rel, *j),
None => quote!(::core::option::Option::None),
},
e => self
.expr_type(e)
.unwrap_or_else(|| quote!(::core::option::Option::None)),
};
let (name, members) = match list {
List::Members(ts) => {
let ms: Vec<TokenStream> = ts
.iter()
.map(|t| match t {
Term::Rust(e) => {
let span = t.span();
quote_spanned!(span=> ::kleene_datalog::__private::member(#e))
}
t => {
let c = literal(t);
quote!(::kleene_datalog::ListMember::Const(#c))
}
})
.collect();
(
quote!(::core::option::Option::None),
quote!(::std::vec![#(#ms),*]),
)
}
List::Whole(e) => {
let span = e.span();
let name = quote!(#e).to_string().replace(' ', "");
(
quote!(::core::option::Option::Some(#name)),
quote_spanned!(span=> ::kleene_datalog::__private::members(#e)),
)
}
};
let x = self.expr(x);
let id = format_ident!("__datalog_c{}", self.consts, span = Span::mixed_site());
self.consts += 1;
let (p, fail) = (&self.p, &self.fail);
self.pre.push(quote! {
let #id = {
let ty: ::core::option::Option<::kleene_datalog::Type> = #ty;
match ::kleene_datalog::__private::list(&mut *#p, ty, #name, #members) {
::core::result::Result::Ok(l) => l,
::core::result::Result::Err(e) => #fail(e),
}
};
});
if not {
quote!(::kleene_datalog::not_one_of(#x, #id))
} else {
quote!(::kleene_datalog::one_of(#x, #id))
}
}
/// A side of a condition: a bare term typed by the sides beside it (as
/// [`Ctx::cond_term`]; an expression beside gives its operands' type), else an
/// expression.
fn cond_side(&mut self, e: &Ex, others: &[&Ex]) -> TokenStream {
let Ex::Term(t) = e else {
return self.expr(e);
};
for o in others {
match o {
Ex::Term(Term::Var(v)) if self.binds.contains_key(&v.unraw().to_string()) => {
return self.cond_term(t, &[o.term().expect("a term")]);
}
Ex::Term(_) => {}
ex => {
if let Some(ty) = self.expr_type(ex) {
return self.place(t, ty);
}
}
}
}
self.place(t, quote!(::core::option::Option::None))
}
/// The type an expression's value takes beside a constant (an `Option<Type>`
/// expression): str for `concat` and `substr`; else f64 if one of its variables bound
/// by an atom is, else i64 if one is, else u64; `None` with no such variable.
fn expr_type(&self, e: &Ex) -> Option<TokenStream> {
// a string function that makes a string: a string
if let Ex::Call(f, _) = e
&& ["concat", "substr"].contains(&f.unraw().to_string().as_str())
{
return Some(quote!(::core::option::Option::Some(
::kleene_datalog::Type::Str
)));
}
let tys: Vec<TokenStream> = e
.vars()
.into_iter()
.filter_map(|v| self.binds.get(&v.unraw().to_string()))
.map(|(rel, j)| self.col_type(rel, *j))
.collect();
if tys.is_empty() {
return None;
}
Some(quote! {{
let ts: &[::core::option::Option<::kleene_datalog::Type>] = &[#(#tys),*];
let has = |t| ts.contains(&::core::option::Option::Some(t));
::core::option::Option::Some(if has(::kleene_datalog::Type::F64) {
::kleene_datalog::Type::F64
} else if has(::kleene_datalog::Type::I64) {
::kleene_datalog::Type::I64
} else {
::kleene_datalog::Type::U64
})
}})
}
/// An expression: a bare term as a `Term`, else an `Expr`. A literal inside an
/// expression is a number: unsigned (`-1` is `-` of 1), a float literal a float code.
fn expr(&mut self, e: &Ex) -> TokenStream {
match e {
Ex::Term(Term::Neg(span, l)) => {
let span = *span;
quote_spanned!(span=> ::kleene_datalog::Expr::unary(
::kleene_datalog::UnOp::Neg,
::kleene_datalog::Expr::from({ let x: u64 = #l; x }),
))
}
Ex::Term(t) => self.term(t),
Ex::Op(op, a, b) => {
let (a, b) = (self.expr(a), self.expr(b));
let op = op.tokens();
quote!(::kleene_datalog::Expr::op(::kleene_datalog::BinOp::#op, #a, #b))
}
Ex::Un(neg, a) => {
let a = self.expr(a);
let op = if *neg { quote!(Neg) } else { quote!(Not) };
quote!(::kleene_datalog::Expr::unary(::kleene_datalog::UnOp::#op, #a))
}
Ex::Call(f, args) => {
let name = f.unraw().to_string();
let variant = FUNCS
.iter()
.find(|x| x.0 == name)
.map(|x| Ident::new(x.1, f.span()))
.expect("a known function");
// a literal in a string place (every argument of concat, the first of substr
// and len) is a string constant
let str_ty = quote!(::core::option::Option::Some(::kleene_datalog::Type::Str));
let args: Vec<TokenStream> = args
.iter()
.enumerate()
.map(|(i, a)| match a {
Ex::Term(t) if name == "concat" || i == 0 => self.place(t, str_ty.clone()),
_ => self.expr(a),
})
.collect();
quote!(::kleene_datalog::Expr::call(
::kleene_datalog::Func::#variant,
[#(::kleene_datalog::Expr::from(#args)),*]
))
}
}
}
fn agg_vars(&mut self, vs: &[Ident]) -> TokenStream {
let ids: Vec<Ident> = vs.iter().map(|v| self.see_var(v)).collect();
quote!([#(#ids),*])
}
fn rule(&mut self, r: &Rule, fail: &TokenStream) -> syn::Result<TokenStream> {
check_rule(r)?;
let p = &self.p.clone();
self.binds.clear();
for l in &r.body {
if let Lit::Pos(a) = l {
let rel = self.rel_tokens(&a.rel);
for (j, t) in a.terms.iter().enumerate() {
if let Term::Var(v) = t {
self.binds
.entry(v.unraw().to_string())
.or_insert_with(|| (rel.clone(), j));
}
}
}
}
// the head first, so the variables are made in the order they are written
let head = self.atom(&r.head, true)?;
let agg = match &r.agg {
None => None,
Some(a) => {
let ts = match &a.kind {
AggKind::Bag(o) => {
self.see_var(o);
self.agg_vars(&a.group);
TokenStream::new()
}
AggKind::Many(reds) => {
let mut ts = Vec::new();
for (red, o, of) in reds {
let o = self.see_var(o);
let x = of.first().map(|v| self.see_var(v));
let of = self.agg_vars(of);
ts.push(match red {
Red::Count if x.is_none() => {
quote!(::kleene_datalog::Reduce::count(#o))
}
Red::Count => {
quote!(::kleene_datalog::Reduce::count_of(#of, #o).distinct())
}
Red::Sum => quote!(::kleene_datalog::Reduce::sum(#x, #o)),
Red::Avg => quote!(::kleene_datalog::Reduce::avg(#x, #o)),
Red::Least => quote!(::kleene_datalog::Reduce::min(#x, #o)),
Red::Greatest => quote!(::kleene_datalog::Reduce::max(#x, #o)),
});
}
let group = self.agg_vars(&a.group);
quote!(::kleene_datalog::Aggregate::many(#group, [#(#ts),*]))
}
AggKind::Count(o) => {
let o = self.see_var(o);
let of = self.agg_vars(&a.of);
let group = self.agg_vars(&a.group);
quote!(::kleene_datalog::Aggregate::count(#group, #of, #o))
}
AggKind::Rank(o) => {
let o = self.see_var(o);
let of = self.agg_vars(&a.of);
let group = self.agg_vars(&a.group);
quote!(::kleene_datalog::Aggregate::rank(#group, #of, #o))
}
AggKind::Set(o, table) => {
self.check_table(table, a.of.len())?;
let t = self.rel_tokens(table);
let o = self.see_var(o);
let of = self.agg_vars(&a.of);
let group = self.agg_vars(&a.group);
quote!(::kleene_datalog::Aggregate::set_number(
#group, #of, #o, ::kleene_datalog::Rel::id(&#t)
))
}
k => {
let of = self.agg_vars(&a.of);
let group = self.agg_vars(&a.group);
match k {
AggKind::Min => {
quote!(::kleene_datalog::Aggregate::min_by(#group, #of))
}
AggKind::Max => {
quote!(::kleene_datalog::Aggregate::max_by(#group, #of))
}
_ => quote!(::kleene_datalog::Aggregate::exactly_one(#group, #of)),
}
}
};
Some((ts, a.span))
}
};
let body: Vec<TokenStream> = r
.body
.iter()
.map(|l| self.lit(l))
.collect::<syn::Result<_>>()?;
let bag = matches!(&r.agg, Some(a) if matches!(a.kind, AggKind::Bag(_)));
let call = match agg {
None => quote!(#p.rule(#head, [#(#body),*])),
Some((_, span)) if bag => {
quote_spanned!(span=> #p.count_rule(#head, [#(#body),*]))
}
Some((agg, span)) => {
quote_spanned!(span=> #p.aggregate(#head, #agg, [#(#body),*]))
}
};
let pre = std::mem::take(&mut self.pre);
Ok(quote!({
#(#pre)*
if let ::core::result::Result::Err(e) = #call { #fail(e); }
}))
}
}
fn expand(s: &Source) -> syn::Result<TokenStream> {
let p = Ident::new("__datalog_p", Span::mixed_site());
let label = syn::Lifetime::new("'__datalog", Span::mixed_site());
let fail = quote!(break #label ::core::result::Result::Err);
let mut cx = Ctx {
known: HashMap::new(),
closed: s.program.is_none(),
vars: Vec::new(),
firsts: Vec::new(),
pre: Vec::new(),
consts: 0,
binds: HashMap::new(),
fail: fail.clone(),
p: p.clone(),
};
let mut decls = Vec::new();
let mut stmts = Vec::new();
for item in &s.items {
match item {
Item::Decl(ds) => {
for d in ds {
let handle = d.name.unraw().to_string();
let twice = cx.known.contains_key(&d.key)
|| cx.known.values().any(|k| k.handle.unraw() == handle);
if twice {
return Err(syn::Error::new(
d.name.span(),
format!("`{}` is declared twice (its handle `{handle}`)", d.key),
));
}
cx.known.insert(
d.key.clone(),
Known {
kind: d.kind,
arity: d.arity,
handle: d.name.clone(),
},
);
stmts.push(decl_stmt(d, &p, &fail));
decls.push(d);
}
}
Item::Rounds(parts) => {
let mut ts = Vec::new();
for (rel, keep) in parts {
if let Some(k) = cx.known_of(rel) {
if !matches!(k.kind, Kind::Derived | Kind::Sets) {
return Err(syn::Error::new(
rel.span(),
format!(
"`{}` is not derived, so it cannot be a part of rounds",
rel.show()
),
));
}
} else if cx.closed {
return Err(syn::Error::new(
rel.span(),
format!("unknown relation `{}`", rel.show()),
));
}
let r = cx.rel_tokens(rel);
let part = if *keep {
quote!(::kleene_datalog::Part::Keep)
} else {
quote!(::kleene_datalog::Part::Fresh)
};
ts.push(quote!((::kleene_datalog::Rel::id(&#r), #part)));
}
stmts.push(quote! {
if let ::core::result::Result::Err(e) = #p.rounds([#(#ts),*]) { #fail(e); }
});
}
Item::Rule(r) => stmts.push(cx.rule(r, &fail)?),
}
}
let var_lets: Vec<TokenStream> = cx
.vars
.iter()
.enumerate()
.map(|(i, name)| {
let id = Ctx::var_ident(i);
let name = if name.is_empty() { "_" } else { name.as_str() };
quote!(let #id = #p.var(#name);)
})
.collect();
// A variable named like a constant, unit struct or static in scope is refused here: a
// binding of that name is then a pattern of the wrong type (the note says which).
let firsts = &cx.firsts;
let guard = quote! {
#[allow(unused_variables, non_snake_case, clippy::let_unit_value)]
{
#(let #firsts: [(); 0] = [];)*
}
};
let fields: Vec<TokenStream> = decls
.iter()
.map(|d| {
let (name, n) = (&d.name, proc_macro2::Literal::usize_unsuffixed(d.arity));
quote!(pub #name: ::kleene_datalog::Rel<#n>)
})
.collect();
let names: Vec<&Ident> = decls.iter().map(|d| &d.name).collect();
let rels = Ident::new("Rels", Span::mixed_site());
let body = quote! {
/// The relations this `datalog!` declared.
#[allow(dead_code, non_snake_case)]
#[derive(Clone, Copy, Debug)]
struct #rels { #(#fields,)* }
#(#stmts)*
::core::result::Result::Ok::<_, ::kleene_datalog::DatalogError>(#rels { #(#names,)* })
};
Ok(match &s.program {
Some(prog) => quote! {
{
#guard
let #p: &mut ::kleene_datalog::Program = #prog;
#(#var_lets)*
#label: { #body }
}
},
None => {
let prog = Ident::new("__datalog_program", Span::mixed_site());
let res = Ident::new("__datalog_res", Span::mixed_site());
let r = Ident::new("__datalog_rels", Span::mixed_site());
quote! {
{
#guard
let mut #prog = ::kleene_datalog::Program::new();
let #res = {
let #p: &mut ::kleene_datalog::Program = &mut #prog;
#(#var_lets)*
#label: { #body }
};
#res.map(|#r| (#prog, #r))
}
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
/// The build error `datalog!` gives for `text`, as its message.
fn error(text: &str) -> String {
let ts: TokenStream = syn::parse_str(text).expect("tokens");
match syn::parse2::<Source>(split_floats(ts)).and_then(|s| expand(&s)) {
Ok(_) => panic!("no error for: {text}"),
Err(e) => e.to_string(),
}
}
fn builds(text: &str) {
let ts: TokenStream = syn::parse_str(text).expect("tokens");
if let Err(e) = syn::parse2::<Source>(split_floats(ts)).and_then(|s| expand(&s)) {
panic!("{text}: {e}");
}
}
/// The text of a table of sets, as written in the order's rules.
#[test]
fn sets_text_builds() {
builds(
"input edge/3, eps/2, start/2.
sets state/2 limit 1000.
derived clo/2, first/2, step/3.
clo(X, X) :- start(_, X).
clo(Z, Z) :- edge(_, _, Z).
clo(X, Z) :- clo(X, Y), eps(Y, Z).
first(K, N) :- N = set(X) by (K) in state: start(K, S), clo(S, X).
step(P, A, N) :- N = set(Y) by (P, A) in state: state(P, X), edge(X, A, Z), clo(Z, Y).
rounds first: keep, step: keep, state: keep.",
);
builds(
"input member/2. sets sets/2 as \"s\". derived id/2.
id(K, N) :- N = set(E) by (K) in sets: member(K, E).",
);
builds("input m/2. sets t/2. derived all/1. all(N) :- N = set(X) in t: m(X, _).");
builds("p => all(N) :- N = set(X, Y) in t: m(X, Y).");
}
#[test]
fn sets_build_errors() {
assert_eq!(
error(
"input m/2. derived d/2, id/2.
id(K, N) :- N = set(X) by (K) in d: m(K, X)."
),
"`d` is not a table of sets: declare it with `sets d/2.`"
);
assert_eq!(
error("input m/2. derived id/2. id(K, N) :- N = set(X) by (K) in t: m(K, X)."),
"unknown table of sets `t`: declare it with `sets t/2.`"
);
assert_eq!(
error("sets x/1."),
"a table of sets has a number and an element: `sets NAME/2` or more"
);
assert_eq!(
error("input m/2. sets t/2. derived id/2. id(K, N) :- N = set(X) by (K): m(K, X)."),
"a set number names its table of sets: `N = set(..) by (..) in NAME:`"
);
assert_eq!(
error("input m/2. sets t/2. t(K, X) :- m(K, X)."),
"`t` is a table of sets: no rule derives it; rules number into it (`N = set(..) in t`)"
);
assert_eq!(
error("sets t/2 limit 0."),
"a table of sets with limit 0 can number no set: the limit is 1 or more"
);
assert_eq!(
error(
"input m/2. sets t/3. derived id/2. id(K, N) :- N = set(X) by (K) in t: m(K, X)."
),
"`t` holds sets of elements of 2 columns; this set's have 1"
);
assert_eq!(
error("input m/2. sets t/2. derived id/2. id(K, N) :- set(X) by (K) in t: m(K, X)."),
"a set number names its result: `N = set(..) in NAME`"
);
assert_eq!(
error("input m/2. derived d/1 limit 3."),
"only a table of sets has a limit: `sets NAME/N limit INT.`"
);
assert_eq!(
error(
"input m/2. sets t/2. derived id/3.
id(K, N, C) :- N = set(X), C = count(X) by (K) in t: m(K, X)."
),
"a set number stands alone in its rule"
);
}
}