crates/kleene-plan/src/compute.rs
//! Computed values in a rule body: `OUT = expr` ([`Compute`]) and conditions with an
//! expression on a side ([`Test`]), over arithmetic and bit operators ([`BinOp`]) and the
//! string functions ([`Func`]: `concat`, `substr`, `len`).
use std::borrow::Cow;
use std::fmt;
use crate::rules::{Cmp, ListId, Literal, Term, Value, Var};
use crate::typed::{Dict, NULL, Type, f64_code, f64_of, i64_code, i64_of};
/// An operator of an [`Expr`], with Rust's meaning and precedence.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BinOp {
/// `a + b`
Add,
/// `a - b`
Sub,
/// `a * b`
Mul,
/// `a / b` (rounded toward zero)
Div,
/// `a % b` (the remainder of `/`, with the sign of `a`)
Rem,
/// `a & b`
And,
/// `a | b`
Or,
/// `a ^ b`
Xor,
/// `a << b`
Shl,
/// `a >> b`
Shr,
}
impl BinOp {
/// The operator as written.
pub fn symbol(self) -> &'static str {
match self {
BinOp::Add => "+",
BinOp::Sub => "-",
BinOp::Mul => "*",
BinOp::Div => "/",
BinOp::Rem => "%",
BinOp::And => "&",
BinOp::Or => "|",
BinOp::Xor => "^",
BinOp::Shl => "<<",
BinOp::Shr => ">>",
}
}
/// Rust's precedence (higher binds tighter); every one is left-associative.
pub 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,
}
}
/// Whether it is a bit operator (`& | ^ << >>`), refused on floats (as `!` is).
pub fn is_bits(self) -> bool {
matches!(
self,
BinOp::And | BinOp::Or | BinOp::Xor | BinOp::Shl | BinOp::Shr
)
}
}
/// A unary operator of an [`Expr`], binding tighter than every [`BinOp`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UnOp {
/// `-a`
Neg,
/// `!a`: the bits flipped (of a u64 expression the 64-bit complement, of a signed
/// one `-a - 1`, as Rust's `!`)
Not,
}
impl UnOp {
/// The operator as written.
pub fn symbol(self) -> &'static str {
match self {
UnOp::Neg => "-",
UnOp::Not => "!",
}
}
}
/// A function of an [`Expr`] over strings. Lengths and places count characters (Unicode
/// scalar values, as `str::chars`), from 0, so no cut splits a character.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Func {
/// `concat(a, b, ...)`: the strings one after the other (two or more).
Concat,
/// `substr(s, i, n)`: the `n` characters of `s` from place `i`, or `substr(s, i)`: those
/// from `i` to the end. Past the end the piece is shorter (`""` from a place past the
/// end); a negative `i` or `n` has no value.
Substr,
/// `len(s)`: the number of characters of `s`.
Len,
/// `cmp(a, b)`: how string `a` compares with `b` by their bytes, 0 below, 1 equal, 2
/// above. Made by a run for an ordered test of a string a rule made (whose id does not
/// follow the byte order), not written in rules.
Cmp,
/// `starts_with(s, p)`, `ends_with`, `contains`: 1 when the text test holds, else 0.
/// Made by a run for a text test of a string a rule made, not written in rules.
Text(crate::rules::TextOp),
}
impl Func {
/// The function's name as written.
pub fn name(self) -> &'static str {
match self {
Func::Concat => "concat",
Func::Substr => "substr",
Func::Len => "len",
Func::Cmp => "cmp",
Func::Text(crate::rules::TextOp::StartsWith) => "starts_with",
Func::Text(crate::rules::TextOp::EndsWith) => "ends_with",
Func::Text(crate::rules::TextOp::Contains) => "contains",
}
}
/// Whether it gives a string ([`Func::Concat`], [`Func::Substr`]): a string a rule
/// makes.
pub fn makes_string(self) -> bool {
matches!(self, Func::Concat | Func::Substr)
}
/// Whether argument `i` is a string.
pub fn string_arg(self, i: usize) -> bool {
match self {
Func::Concat | Func::Cmp | Func::Text(_) => true,
Func::Substr | Func::Len => i == 0,
}
}
/// The numbers of arguments it takes, `(least, most)`.
pub fn arity(self) -> (usize, usize) {
match self {
Func::Concat => (2, usize::MAX),
Func::Substr => (2, 3),
Func::Len => (1, 1),
Func::Cmp | Func::Text(_) => (2, 2),
}
}
}
/// An expression over terms: a term, a unary operator over an expression, or an operator
/// over two.
///
/// ```
/// use kleene_plan::{Expr, Plan};
/// let mut p = Plan::new();
/// let (lo, i) = (p.var("LO"), p.var("I"));
/// let e = Expr::from(lo) + i;
/// assert_eq!(e.vars(), vec![lo, i]);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Expr {
/// A variable or a constant.
Term(Term),
/// `left op right`.
Op(BinOp, Box<Expr>, Box<Expr>),
/// `op inner`.
Unary(UnOp, Box<Expr>),
/// `f(args)`: a string function ([`Func`]).
Call(Func, Vec<Expr>),
}
impl Expr {
/// `a op b`.
pub fn op(op: BinOp, a: impl Into<Expr>, b: impl Into<Expr>) -> Expr {
Expr::Op(op, Box::new(a.into()), Box::new(b.into()))
}
/// `op a`.
pub fn unary(op: UnOp, a: impl Into<Expr>) -> Expr {
Expr::Unary(op, Box::new(a.into()))
}
/// `concat(a, b, ...)` of two or more strings.
pub fn concat<E: Into<Expr>>(parts: impl IntoIterator<Item = E>) -> Expr {
Expr::Call(Func::Concat, parts.into_iter().map(Into::into).collect())
}
/// `substr(s, i, n)`: `n` characters of `s` from place `i` (from 0).
pub fn substr(s: impl Into<Expr>, i: impl Into<Expr>, n: impl Into<Expr>) -> Expr {
Expr::Call(Func::Substr, vec![s.into(), i.into(), n.into()])
}
/// `substr(s, i)`: the characters of `s` from place `i` (from 0) to the end.
pub fn substr_from(s: impl Into<Expr>, i: impl Into<Expr>) -> Expr {
Expr::Call(Func::Substr, vec![s.into(), i.into()])
}
/// `len(s)`: the number of characters of `s`.
pub fn len(s: impl Into<Expr>) -> Expr {
Expr::Call(Func::Len, vec![s.into()])
}
/// `f(args)`.
pub fn call(f: Func, args: impl IntoIterator<Item = Expr>) -> Expr {
Expr::Call(f, args.into_iter().collect())
}
/// The term, when the expression is one bare term.
pub fn term(&self) -> Option<Term> {
match self {
Expr::Term(t) => Some(*t),
Expr::Op(..) | Expr::Unary(..) | Expr::Call(..) => None,
}
}
/// Whether its value is a string: a [`Func::makes_string`] call.
pub fn is_string(&self) -> bool {
matches!(self, Expr::Call(f, _) if f.makes_string())
}
/// Whether it calls a function that makes a string ([`Func::makes_string`]).
pub fn makes_string(&self) -> bool {
match self {
Expr::Term(_) => false,
Expr::Op(_, a, b) => a.makes_string() || b.makes_string(),
Expr::Unary(_, a) => a.makes_string(),
Expr::Call(f, args) => f.makes_string() || args.iter().any(Expr::makes_string),
}
}
/// Whether it calls [`Func::Concat`] (a string that can grow).
pub fn concats(&self) -> bool {
match self {
Expr::Term(_) => false,
Expr::Op(_, a, b) => a.concats() || b.concats(),
Expr::Unary(_, a) => a.concats(),
Expr::Call(f, args) => *f == Func::Concat || args.iter().any(Expr::concats),
}
}
/// Whether it calls a function ([`Expr::Call`]).
pub(crate) fn calls(&self) -> bool {
match self {
Expr::Term(_) => false,
Expr::Op(_, a, b) => a.calls() || b.calls(),
Expr::Unary(_, a) => a.calls(),
Expr::Call(..) => true,
}
}
/// Every term with whether it stands in a string place (a string argument of a call),
/// left to right.
pub(crate) fn each_term_placed(&self, f: &mut impl FnMut(Term, bool)) {
fn walk(e: &Expr, text: bool, f: &mut impl FnMut(Term, bool)) {
match e {
Expr::Term(t) => f(*t, text),
Expr::Op(_, a, b) => {
walk(a, false, f);
walk(b, false, f);
}
Expr::Unary(_, a) => walk(a, false, f),
Expr::Call(g, args) => {
for (i, a) in args.iter().enumerate() {
walk(a, g.string_arg(i), f);
}
}
}
}
walk(self, false, f)
}
/// The terms in a string place ([`Expr::each_term_placed`]), mutably.
pub(crate) fn string_consts_mut(&mut self, f: &mut impl FnMut(&mut Term)) {
fn walk(e: &mut Expr, text: bool, f: &mut impl FnMut(&mut Term)) {
match e {
Expr::Term(t) => {
if text {
f(t)
}
}
Expr::Op(_, a, b) => {
walk(a, false, f);
walk(b, false, f);
}
Expr::Unary(_, a) => walk(a, false, f),
Expr::Call(g, args) => {
let g = *g;
for (i, a) in args.iter_mut().enumerate() {
walk(a, g.string_arg(i), f);
}
}
}
}
walk(self, false, f)
}
/// The variables, left to right (repeats kept).
pub fn vars(&self) -> Vec<Var> {
let mut out = Vec::new();
self.each_term(&mut |t| {
if let Term::Var(v) = t {
out.push(v);
}
});
out
}
/// Every term, left to right.
pub(crate) fn each_term(&self, f: &mut impl FnMut(Term)) {
match self {
Expr::Term(t) => f(*t),
Expr::Op(_, a, b) => {
a.each_term(f);
b.each_term(f);
}
Expr::Unary(_, a) => a.each_term(f),
Expr::Call(_, args) => {
for a in args {
a.each_term(f);
}
}
}
}
/// Whether it has a bit operator (`& | ^ << >> !`).
pub(crate) fn has_bits(&self) -> bool {
match self {
Expr::Term(_) => false,
Expr::Op(op, a, b) => op.is_bits() || a.has_bits() || b.has_bits(),
Expr::Unary(op, a) => *op == UnOp::Not || a.has_bits(),
Expr::Call(_, args) => args.iter().any(Expr::has_bits),
}
}
/// The expression as text, its terms by `term`, parenthesized only where Rust's
/// precedence needs it.
pub fn show(&self, term: &dyn Fn(Term) -> String) -> String {
self.show_with(term, term)
}
/// [`Expr::show`] with the terms in a string place (a string argument of a call) by
/// `text`.
pub fn show_with(
&self,
term: &dyn Fn(Term) -> String,
text: &dyn Fn(Term) -> String,
) -> String {
self.show_at(&(term, text), 0, false)
}
fn show_at(&self, by: &Shown<'_>, outer: u8, right: bool) -> String {
let term = by.0;
match self {
Expr::Term(t) => term(*t),
Expr::Call(f, args) => {
let shown: Vec<String> = args
.iter()
.enumerate()
.map(|(i, a)| match (a, f.string_arg(i)) {
(Expr::Term(t), true) => (by.1)(*t),
_ => a.show_at(by, 0, false),
})
.collect();
format!("{}({})", f.name(), shown.join(", "))
}
Expr::Op(op, a, b) => {
let p = op.precedence();
let s = format!(
"{} {} {}",
a.show_at(by, p, false),
op.symbol(),
b.show_at(by, p, true)
);
if p < outer || (right && p == outer) {
format!("({s})")
} else {
s
}
}
Expr::Unary(op, a) => format!("{}{}", op.symbol(), a.show_at(by, u8::MAX, false)),
}
}
}
/// How an expression's terms are shown: in a number place, in a string place.
type Shown<'a> = (&'a dyn Fn(Term) -> String, &'a dyn Fn(Term) -> String);
impl std::ops::Neg for Expr {
type Output = Expr;
fn neg(self) -> Expr {
Expr::Unary(UnOp::Neg, Box::new(self))
}
}
impl std::ops::Not for Expr {
type Output = Expr;
fn not(self) -> Expr {
Expr::Unary(UnOp::Not, Box::new(self))
}
}
impl From<Term> for Expr {
fn from(t: Term) -> Self {
Expr::Term(t)
}
}
impl From<Var> for Expr {
fn from(v: Var) -> Self {
Expr::Term(Term::Var(v))
}
}
impl From<u32> for Expr {
fn from(c: u32) -> Self {
Expr::Term(Term::Const(c as Value))
}
}
impl From<u64> for Expr {
fn from(c: u64) -> Self {
Expr::Term(Term::Const(c))
}
}
macro_rules! ops {
($($tr:ident $f:ident $op:ident),*) => {$(
impl<R: Into<Expr>> std::ops::$tr<R> for Expr {
type Output = Expr;
fn $f(self, rhs: R) -> Expr {
Expr::op(BinOp::$op, self, rhs)
}
}
)*};
}
ops!(
Add add Add,
Sub sub Sub,
Mul mul Mul,
Div div Div,
Rem rem Rem,
BitAnd bitand And,
BitOr bitor Or,
BitXor bitxor Xor,
Shl shl Shl,
Shr shr Shr
);
/// `out = expr`: a body literal that binds `out` to the value of `expr` (its variables
/// bound by positive atoms or by computes before it). Where `out` is already bound (by a
/// positive atom or an earlier compute) it is an equality test.
///
/// The value takes `out`'s type: the type of the column `out` is bound to (a positive
/// atom's, else the head's), else the type [`Compute::typed`] sets, else the operands'
/// type (f64 if one is, else i64 if one is, else u64). An integer expression is computed
/// exactly over its signed and unsigned operands (a constant read as an unsigned number);
/// for a u64 `out` a value below 0 or over 64 bits, a division or remainder by 0, a shift
/// of 64 or more (or of a negative count), or a null operand gives no row (the literal
/// does not hold); for an i64 `out` each of these gives a null value (the row kept). `!x`
/// is the 64-bit complement where `out` and every operand are u64, else `-x - 1`. A float
/// expression (a constant read as a float code) gives null for a null operand and for a
/// division or remainder by 0; a bit operator on a float is refused when the rule is
/// added.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Compute {
/// The variable computed.
pub out: Var,
/// Its expression.
pub expr: Expr,
/// Made for an expression of a [`Test`] (printed in its place).
pub(crate) of_test: bool,
/// The type its variable takes where no atom or head column gives one
/// ([`Compute::typed`]).
pub(crate) ty: Option<Type>,
}
impl Compute {
/// `out = expr`.
pub fn new(out: Var, expr: impl Into<Expr>) -> Self {
Compute {
out,
expr: expr.into(),
of_test: false,
ty: None,
}
}
/// `out = expr` with `out` of type `ty` where no positive atom or head column gives its
/// type (a client's value of a set type, such as GQL's `i64` arithmetic). The plan is
/// typed then.
pub fn typed(out: Var, expr: impl Into<Expr>, ty: Type) -> Self {
Compute {
ty: Some(ty),
..Compute::new(out, expr)
}
}
/// The type set by [`Compute::typed`].
pub fn ty(&self) -> Option<Type> {
self.ty
}
/// Whether the plan made it for an expression of a [`Test`]: its variable stands for
/// the expression, which is printed in its place.
pub fn of_test(&self) -> bool {
self.of_test
}
}
/// A condition with an expression on a side: a comparison, a half-open range or a list
/// test. A side
/// that is an expression is computed (a [`Compute`] the plan adds, of the operands' type)
/// and the condition is a [`crate::Cond`] over it.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Test {
/// `left op right`.
Cmp {
/// The left side.
left: Expr,
/// The comparison.
op: Cmp,
/// The right side.
right: Expr,
},
/// `lo <= x < hi`.
Within {
/// The value tested.
x: Expr,
/// The first value inside.
lo: Expr,
/// The first value past the range.
hi: Expr,
},
/// `x in (k1, ..)` or `!(x in (..))`: a [`crate::Cond::OneOf`] of an expression.
OneOf {
/// The value tested.
x: Expr,
/// The list ([`crate::Plan::list`]).
list: ListId,
/// True: holds when `x` is not a member.
not: bool,
},
}
impl From<Compute> for Literal {
fn from(c: Compute) -> Self {
Literal::Compute(c)
}
}
impl From<Test> for Literal {
fn from(t: Test) -> Self {
Literal::Test(t)
}
}
impl fmt::Display for BinOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.symbol())
}
}
/// The type of an expression's operands: f64 if one is, else i64 if one is, else u64.
pub(crate) fn operand_type(types: &[Type]) -> Type {
if types.contains(&Type::F64) {
Type::F64
} else if types.contains(&Type::I64) {
Type::I64
} else {
Type::U64
}
}
/// A step of a compiled expression (postfix).
#[derive(Clone, Copy, Debug)]
enum Step {
/// The value at a slot, of a type.
Slot(usize, Type),
Const(Value),
Op(BinOp),
Un(UnOp),
}
/// An expression made ready to run: its variables as slots, the type it is computed in and
/// the type of the variable it gives.
#[derive(Clone, Debug)]
pub(crate) struct Compiled {
steps: Vec<Step>,
float: bool,
/// The value and every operand unsigned: `!` is the 64-bit complement.
unsigned: bool,
out: Type,
/// An expression that calls a function, as a tree (its steps are then unused): only
/// such an expression reads or makes strings, so one without keeps the steps' path.
tree: Option<Node>,
}
/// An expression with a call ([`Func`]) made ready to run.
#[derive(Clone, Debug)]
enum Node {
/// The value at a slot, of a type.
Slot(usize, Type),
/// A number constant (a float code in a float expression).
Num(Value),
/// A string constant: its id in the run's dictionary.
Text(Value),
Op(BinOp, Box<Node>, Box<Node>),
Un(UnOp, Box<Node>),
Call(Func, Vec<Node>),
}
/// A value inside an expression with a call.
#[derive(Clone, Debug)]
enum V<'a> {
Int(i128),
Flt(f64),
Str(Cow<'a, str>),
}
/// What a computed value is: none (no row for a u64), a code of the out type, or a string
/// the run's dictionary does not hold yet (made by the rule; the string goes beside).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Got {
/// No row.
#[default]
None,
/// The value's code (a null code for a null of a nullable type).
Value(Value),
/// A string not in the run's dictionary.
Made,
}
impl Compiled {
/// `e` with its variables at `slot(v)` (a slot and the variable's type), computed into
/// a value of type `out`.
pub(crate) fn new(e: &Expr, slot: &dyn Fn(Var) -> (usize, Type), out: Type) -> Self {
fn walk(e: &Expr, slot: &dyn Fn(Var) -> (usize, Type), steps: &mut Vec<Step>) {
match e {
Expr::Term(Term::Var(v)) => {
let (s, t) = slot(*v);
steps.push(Step::Slot(s, t));
}
Expr::Term(Term::Const(c)) => steps.push(Step::Const(*c)),
Expr::Op(op, a, b) => {
walk(a, slot, steps);
walk(b, slot, steps);
steps.push(Step::Op(*op));
}
Expr::Unary(op, a) => {
walk(a, slot, steps);
steps.push(Step::Un(*op));
}
Expr::Call(..) => unreachable!("an expression with a call is a tree"),
}
}
fn node(e: &Expr, text: bool, slot: &dyn Fn(Var) -> (usize, Type)) -> Node {
match e {
Expr::Term(Term::Var(v)) => {
let (s, t) = slot(*v);
Node::Slot(s, t)
}
Expr::Term(Term::Const(c)) if text => Node::Text(*c),
Expr::Term(Term::Const(c)) => Node::Num(*c),
Expr::Op(op, a, b) => Node::Op(
*op,
Box::new(node(a, false, slot)),
Box::new(node(b, false, slot)),
),
Expr::Unary(op, a) => Node::Un(*op, Box::new(node(a, false, slot))),
Expr::Call(f, args) => Node::Call(
*f,
args.iter()
.enumerate()
.map(|(i, a)| node(a, f.string_arg(i), slot))
.collect(),
),
}
}
let (steps, tree) = if e.calls() {
(Vec::new(), Some(node(e, false, slot)))
} else {
let mut steps = Vec::new();
walk(e, slot, &mut steps);
(steps, None)
};
let types: Vec<Type> = e.vars().into_iter().map(|v| slot(v).1).collect();
let float = out == Type::F64 || types.contains(&Type::F64);
// `!` flips 64 bits where the value and every number operand are unsigned
// (else it is the signed `!`: `-x - 1`)
let unsigned =
out == Type::U64 && !types.iter().any(|t| !matches!(t, Type::U64 | Type::Str));
Compiled {
steps,
float,
unsigned,
out,
tree,
}
}
/// The value with each slot's code read by `get`, strings through the run's
/// dictionary `dict`.
pub(crate) fn eval(&self, get: &dyn Fn(usize) -> Value, dict: Option<&Dict>) -> Got {
if let Some(tree) = &self.tree {
return self.eval_tree(tree, get, dict).unwrap_or(Got::Made);
}
if self.float {
return self.eval_float(get);
}
// exact over i128; `None` for no value (a null operand, / 0, a shift out of range,
// an i128 overflow)
let mut stack: Vec<Option<i128>> = Vec::with_capacity(4);
for s in &self.steps {
match *s {
Step::Slot(i, t) => {
let c = get(i);
stack.push(match t {
Type::U64 => Some(c as i128),
Type::I64 if c == NULL => None,
Type::I64 => Some(i64_of(c) as i128),
// (typed out when the rule is added)
_ => None,
});
}
Step::Const(c) => stack.push(Some(c as i128)),
Step::Op(op) => {
let b = stack.pop().expect("two operands");
let a = stack.pop().expect("two operands");
stack.push(a.zip(b).and_then(|(a, b)| int_op(op, a, b)));
}
Step::Un(op) => {
let a = stack.pop().expect("an operand");
stack.push(a.and_then(|a| match op {
UnOp::Neg => a.checked_neg(),
UnOp::Not if self.unsigned => u64::try_from(a).ok().map(|a| i128::from(!a)),
UnOp::Not => Some(!a),
}));
}
}
}
let r = stack.pop().expect("a value");
match self.out {
Type::I64 => Got::Value(
r.and_then(|r| i64::try_from(r).ok())
.filter(|&r| r != i64::MAX)
.map_or(NULL, i64_code),
),
_ => match r.and_then(|r| u64::try_from(r).ok()) {
Some(v) => Got::Value(v),
None => Got::None,
},
}
}
/// Whether its value is a string, which may be one the run's dictionary lacks: then
/// [`Compiled::eval_made`] gives it.
pub(crate) fn makes_string(&self) -> bool {
self.out == Type::Str && self.tree.is_some()
}
/// The value, or the string made where the run's dictionary `dict` lacks it.
pub(crate) fn eval_made(
&self,
get: &dyn Fn(usize) -> Value,
dict: Option<&Dict>,
) -> std::result::Result<Got, String> {
match &self.tree {
Some(tree) => self.eval_tree(tree, get, dict),
None => Ok(self.eval(get, dict)),
}
}
/// The value of an expression with a call (`Err`: a string `dict` lacks).
fn eval_tree(
&self,
tree: &Node,
get: &dyn Fn(usize) -> Value,
dict: Option<&Dict>,
) -> std::result::Result<Got, String> {
let v = self.node(tree, get, dict);
Ok(match self.out {
Type::Str => match v {
Some(V::Str(s)) => match dict.and_then(|d| d.id(&s)) {
Some(id) => Got::Value(Value::from(id)),
None => return Err(s.into_owned()),
},
_ => Got::Value(NULL),
},
Type::F64 => Got::Value(v.and_then(|v| self.flt(v)).map_or(NULL, f64_code)),
Type::I64 => Got::Value(
v.and_then(|v| self.int(v))
.and_then(|r| i64::try_from(r).ok())
.filter(|&r| r != i64::MAX)
.map_or(NULL, i64_code),
),
_ => match v
.and_then(|v| self.int(v))
.and_then(|r| u64::try_from(r).ok())
{
Some(x) => Got::Value(x),
None => Got::None,
},
})
}
fn int(&self, v: V<'_>) -> Option<i128> {
match v {
V::Int(x) => Some(x),
V::Flt(_) | V::Str(_) => None,
}
}
fn flt(&self, v: V<'_>) -> Option<f64> {
match v {
V::Int(x) => Some(x as f64),
V::Flt(x) => Some(x),
V::Str(_) => None,
}
}
/// The value of `n`: `None` where it has none (a null operand, a value out of range).
fn node<'d>(
&self,
n: &Node,
get: &dyn Fn(usize) -> Value,
dict: Option<&'d Dict>,
) -> Option<V<'d>> {
let text = |n: &Node| match self.node(n, get, dict)? {
V::Str(s) => Some(s),
V::Int(_) | V::Flt(_) => None,
};
let int = |n: &Node| self.node(n, get, dict).and_then(|v| self.int(v));
Some(match n {
Node::Slot(i, t) => {
let c = get(*i);
match t {
Type::U64 => V::Int(c as i128),
_ if c == NULL => return None,
Type::I64 => V::Int(i64_of(c) as i128),
Type::F64 => V::Flt(f64_of(c)),
Type::Str => V::Str(Cow::Borrowed(dict?.get(c)?)),
Type::Bool => return None,
}
}
Node::Num(c) if self.float => V::Flt(f64_of(*c)),
Node::Num(c) => V::Int(*c as i128),
Node::Text(c) => V::Str(Cow::Borrowed(dict?.get(*c)?)),
Node::Op(op, a, b) => {
let (a, b) = (self.node(a, get, dict)?, self.node(b, get, dict)?);
if self.float {
let (a, b) = (self.flt(a)?, self.flt(b)?);
V::Flt(float_op(*op, a, b)?)
} else {
V::Int(int_op(*op, self.int(a)?, self.int(b)?)?)
}
}
Node::Un(op, a) => {
let a = self.node(a, get, dict)?;
if self.float {
match op {
UnOp::Neg => V::Flt(-self.flt(a)?),
UnOp::Not => return None,
}
} else {
let a = self.int(a)?;
V::Int(match op {
UnOp::Neg => a.checked_neg()?,
UnOp::Not if self.unsigned => i128::from(!u64::try_from(a).ok()?),
UnOp::Not => !a,
})
}
}
Node::Call(f, args) => match f {
Func::Concat => {
let mut s = String::new();
for a in args {
s.push_str(&text(a)?);
}
V::Str(Cow::Owned(s))
}
Func::Substr => {
let s = text(&args[0])?;
let at = int(&args[1])?;
if at < 0 {
return None;
}
let at = usize::try_from(at).unwrap_or(usize::MAX);
let n = match args.get(2) {
None => usize::MAX,
Some(a) => {
let n = int(a)?;
if n < 0 {
return None;
}
usize::try_from(n).unwrap_or(usize::MAX)
}
};
V::Str(cut(s, at, n))
}
Func::Len => V::Int(text(&args[0])?.chars().count() as i128),
Func::Cmp => {
let (a, b) = (text(&args[0])?, text(&args[1])?);
V::Int(a.as_bytes().cmp(b.as_bytes()) as i128 + 1)
}
Func::Text(op) => {
let (a, b) = (text(&args[0])?, text(&args[1])?);
V::Int(i128::from(op.holds(&a, &b)))
}
},
})
}
fn eval_float(&self, get: &dyn Fn(usize) -> Value) -> Got {
let mut stack: Vec<Option<f64>> = Vec::with_capacity(4);
for s in &self.steps {
match *s {
Step::Slot(i, t) => {
let c = get(i);
stack.push(match t {
Type::U64 => Some(c as f64),
Type::I64 if c == NULL => None,
Type::I64 => Some(i64_of(c) as f64),
Type::F64 if c == NULL => None,
Type::F64 => Some(f64_of(c)),
_ => None,
});
}
Step::Const(c) => stack.push(Some(f64_of(c))),
Step::Op(op) => {
let b = stack.pop().expect("two operands");
let a = stack.pop().expect("two operands");
stack.push(a.zip(b).and_then(|(a, b)| match op {
BinOp::Add => Some(a + b),
BinOp::Sub => Some(a - b),
BinOp::Mul => Some(a * b),
BinOp::Div | BinOp::Rem if b == 0.0 => None,
BinOp::Div => Some(a / b),
BinOp::Rem => Some(a % b),
// (refused when the rule is added)
_ => None,
}));
}
Step::Un(op) => {
let a = stack.pop().expect("an operand");
stack.push(a.and_then(|a| match op {
UnOp::Neg => Some(-a),
// (refused when the rule is added)
UnOp::Not => None,
}));
}
}
}
Got::Value(stack.pop().expect("a value").map_or(NULL, f64_code))
}
}
/// The `n` characters of `s` from character `at` (fewer past the end).
fn cut(s: Cow<'_, str>, at: usize, n: usize) -> Cow<'_, str> {
let start = s.char_indices().nth(at).map_or(s.len(), |(b, _)| b);
let end = s[start..]
.char_indices()
.nth(n)
.map_or(s.len(), |(b, _)| start + b);
match s {
Cow::Borrowed(b) => Cow::Borrowed(&b[start..end]),
Cow::Owned(o) => Cow::Owned(o[start..end].to_string()),
}
}
/// `a op b` over floats, `None` where it has no value.
fn float_op(op: BinOp, a: f64, b: f64) -> Option<f64> {
match op {
BinOp::Add => Some(a + b),
BinOp::Sub => Some(a - b),
BinOp::Mul => Some(a * b),
BinOp::Div | BinOp::Rem if b == 0.0 => None,
BinOp::Div => Some(a / b),
BinOp::Rem => Some(a % b),
// (refused when the rule is added)
_ => None,
}
}
/// `a op b` exactly, `None` where it has no value.
fn int_op(op: BinOp, a: i128, b: i128) -> Option<i128> {
match op {
BinOp::Add => a.checked_add(b),
BinOp::Sub => a.checked_sub(b),
BinOp::Mul => a.checked_mul(b),
BinOp::Div => a.checked_div(b),
BinOp::Rem => a.checked_rem(b),
BinOp::And => Some(a & b),
BinOp::Or => Some(a | b),
BinOp::Xor => Some(a ^ b),
BinOp::Shl => {
let s = u32::try_from(b).ok().filter(|&s| s < 64)?;
a.checked_mul(1i128 << s)
}
BinOp::Shr => {
let s = u32::try_from(b).ok().filter(|&s| s < 64)?;
Some(a >> s)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_an_expression_with_a_call_takes_the_tree() {
let (a, b) = (Var(0), Var(1));
let slot = |v: Var| (v.0 as usize, [Type::U64, Type::Str][v.0 as usize]);
assert!(
Compiled::new(&(Expr::from(a) + 1u64), &slot, Type::U64)
.tree
.is_none()
);
assert!(
Compiled::new(&Expr::len(b), &slot, Type::U64)
.tree
.is_some()
);
}
#[test]
fn substr_counts_characters_and_cuts_short_past_the_end() {
let s = |x: &str, at: usize, n: usize| cut(Cow::Borrowed(x), at, n).into_owned();
assert_eq!(s("ab日本x", 1, 2), "b日");
assert_eq!(s("ab日本x", 3, 9), "本x");
assert_eq!(s("ab日本x", 9, 1), "");
assert_eq!(s("🦀🦀", 1, usize::MAX), "🦀");
}
fn run(e: &Expr, vals: &[(Var, Type, Value)], out: Type) -> Got {
let c = Compiled::new(
e,
&|v| {
let i = vals.iter().position(|x| x.0 == v).expect("a value");
(i, vals[i].1)
},
out,
);
c.eval(&|i| vals[i].2, None)
}
#[test]
fn unsigned_values_that_do_not_fit_give_none() {
let (a, b) = (Var(0), Var(1));
let u = |x: Value, y: Value, e: Expr| {
run(&e, &[(a, Type::U64, x), (b, Type::U64, y)], Type::U64)
};
let ea = || Expr::from(a);
assert_eq!(u(3, 4, ea() + b), Got::Value(7));
assert_eq!(u(3, 4, ea() - b), Got::None);
assert_eq!(u(3, 4, ea() - b + 5u64), Got::Value(4));
assert_eq!(u(u64::MAX, 1, ea() + b), Got::None);
assert_eq!(u(7, 0, ea() / b), Got::None);
assert_eq!(u(7, 0, ea() % b), Got::None);
assert_eq!(u(1, 64, ea() << b), Got::None);
assert_eq!(u(1, 63, ea() << b), Got::Value(1 << 63));
assert_eq!(u(2, 63, ea() << b), Got::None);
assert_eq!(u(0x1234, 0xF, ea() & b), Got::Value(4));
assert_eq!(u(0x1234, 4, ea() >> b), Got::Value(0x123));
assert_eq!(u(5, 64, ea() >> b), Got::None);
assert_eq!(u(0x1234, 0xF, ea() & !Expr::from(b)), Got::Value(0x1230));
assert_eq!(u(5, 0, !ea()), Got::Value(!5));
assert_eq!(u(5, 0, -ea()), Got::None);
assert_eq!(u(0, 0, -ea()), Got::Value(0));
assert_eq!(u(5, 7, -ea() + b), Got::Value(2));
}
#[test]
fn signed_operands_into_unsigned_and_signed() {
let (a, b) = (Var(0), Var(1));
let e = Expr::from(a) + b;
let r = |x: i64, out| run(&e, &[(a, Type::I64, i64_code(x)), (b, Type::U64, 10)], out);
assert_eq!(r(5, Type::U64), Got::Value(15));
assert_eq!(r(-10, Type::U64), Got::Value(0));
assert_eq!(r(-11, Type::U64), Got::None);
assert_eq!(r(-11, Type::I64), Got::Value(i64_code(-1)));
let null = run(&e, &[(a, Type::I64, NULL), (b, Type::U64, 10)], Type::U64);
assert_eq!(null, Got::None);
let null = run(&e, &[(a, Type::I64, NULL), (b, Type::U64, 10)], Type::I64);
assert_eq!(null, Got::Value(NULL));
let big = run(
&e,
&[(a, Type::I64, i64_code(i64::MAX - 1)), (b, Type::U64, 10)],
Type::I64,
);
assert_eq!(big, Got::Value(NULL));
}
#[test]
fn shown_with_rust_precedence() {
let (a, b, c) = (Var(0), Var(1), Var(2));
let name = |t: Term| match t {
Term::Var(v) => ["A", "B", "C"][v.0 as usize].to_string(),
Term::Const(k) => k.to_string(),
};
let e = (Expr::from(a) + b) * c;
assert_eq!(e.show(&name), "(A + B) * C");
let e = Expr::from(a) + Expr::from(b) * c;
assert_eq!(e.show(&name), "A + B * C");
let e = Expr::from(a) - (Expr::from(b) - c);
assert_eq!(e.show(&name), "A - (B - C)");
let e = Expr::from(a) - b - c;
assert_eq!(e.show(&name), "A - B - C");
let e = Expr::from(a) & 15u64;
assert_eq!(e.show(&name), "A & 15");
let e = -(Expr::from(a) + b) * !Expr::from(c);
assert_eq!(e.show(&name), "-(A + B) * !C");
}
}