use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::sync::Arc;
use relate_core::{integer_args, temporal, Error, Result, Value};
use relate_ir::{BinaryOp, Expr, UnaryOp};
use relate_names::{NamedToken, SmallName};
use crate::overlay::ExecGraph;
use crate::row::Row;
use super::arithmetic::{add, concat, div, mod_op, mul, pow, sub};
use super::function::entity::virtual_own_prop;
use super::regex_cache::regex_is_match;
use super::string::char_range;
use super::{bool_operand, eval, predicate_value_holds};
pub(crate) fn reject_deleted_access(graph: &ExecGraph<'_>, v: &Value) -> Result<()> {
match v {
Value::Node(n) if graph.is_deleted_node(n.id) => Err(Error::execution(
"DeletedEntityAccess: cannot access properties of a deleted node",
)),
Value::Relationship(r) if graph.is_deleted_rel(r.id) => Err(Error::execution(
"DeletedEntityAccess: cannot access properties of a deleted relationship",
)),
_ => Ok(()),
}
}
pub(crate) fn prop(graph: &ExecGraph<'_>, v: &Value, key: &NamedToken) -> Result<Value> {
reject_deleted_access(graph, v)?;
key.0.with_str(|text| {
Ok(match v {
Value::Node(n) => graph
.node_prop_resolved(n.id, key)
.or_else(|| virtual_own_prop(n.id, &n.properties, text))
.unwrap_or(Value::Null),
Value::Relationship(r) => graph
.rel_prop_resolved(r.id, key)
.or_else(|| virtual_own_prop(r.id, &r.properties, text))
.unwrap_or(Value::Null),
Value::Map(m) => m.get(text).cloned().unwrap_or(Value::Null),
Value::Temporal(t) => t.component(text)?,
Value::Point(p) => relate_core::point_component(p, text)?,
Value::Null => Value::Null,
_ => {
return Err(Error::invalid_argument_type(
"property access requires a map, node, relationship, temporal, or point value",
))
}
})
})
}
pub(crate) fn unary(op: UnaryOp, v: Value) -> Result<Value> {
Ok(match op {
UnaryOp::Not => match bool_operand(&v, "NOT")? {
Some(b) => Value::Bool(!b),
None => Value::Null,
},
UnaryOp::Plus => match v {
Value::Int(i) => Value::Int(i),
Value::Float(f) => Value::Float(f),
Value::Temporal(t @ temporal::Temporal::Duration { .. }) => Value::Temporal(t),
Value::Null => Value::Null,
_ => return Err(Error::ty("unary + needs a number")),
},
UnaryOp::Minus => match v {
Value::Int(i) => Value::Int(
i.checked_neg()
.ok_or_else(|| Error::ty("integer out of range"))?,
),
Value::Float(f) => Value::Float(-f),
Value::Temporal(t @ temporal::Temporal::Duration { .. }) => {
Value::Temporal(temporal::negate_duration(&t)?)
}
Value::Null => Value::Null,
_ => return Err(Error::ty("unary - needs a number")),
},
UnaryOp::IsNull => Value::Bool(v.is_null()),
UnaryOp::IsNotNull => Value::Bool(!v.is_null()),
})
}
pub(crate) fn binary(graph: &ExecGraph<'_>, op: BinaryOp, l: Value, r: Value) -> Result<Value> {
binary_inner(Some(graph), op, l, r)
}
pub(crate) fn binary_pure(op: BinaryOp, l: Value, r: Value) -> Result<Value> {
binary_inner(None, op, l, r)
}
fn binary_inner(charge: Option<&ExecGraph<'_>>, op: BinaryOp, l: Value, r: Value) -> Result<Value> {
Ok(match op {
BinaryOp::Eq => l.cypher_eq(&r),
BinaryOp::Neq => match l.cypher_eq(&r) {
Value::Bool(b) => Value::Bool(!b),
other => other,
},
BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Lte | BinaryOp::Gte => {
let ordering =
ordering_operator(op).expect("`op` matched one of the four ordering operators");
cmp_bool(&l, &r, ordering.equality_allowed, ordering.pred)
}
BinaryOp::And => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(false), _) | (_, Some(false)) => Value::Bool(false),
(Some(true), Some(true)) => Value::Bool(true),
_ => Value::Null,
},
BinaryOp::Or => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(true), _) | (_, Some(true)) => Value::Bool(true),
(Some(false), Some(false)) => Value::Bool(false),
_ => Value::Null,
},
BinaryOp::Xor => match (
bool_operand(&l, op.as_str())?,
bool_operand(&r, op.as_str())?,
) {
(Some(a), Some(b)) => Value::Bool(a ^ b),
_ => Value::Null,
},
BinaryOp::Add => match charge {
Some(graph) => add(graph, l, r)?,
None => {
return Err(Error::internal(
"allocating '+' reached the comparison-only binary path",
))
}
},
BinaryOp::Sub => sub(l, r)?,
BinaryOp::Mul => mul(l, r)?,
BinaryOp::Div => div(l, r)?,
BinaryOp::Mod => mod_op(l, r)?,
BinaryOp::Pow => pow(l, r)?,
BinaryOp::Concat => match charge {
Some(graph) => concat(graph, l, r)?,
None => {
return Err(Error::internal(
"allocating '||' reached the comparison-only binary path",
))
}
},
BinaryOp::In => in_op(l, r)?,
BinaryOp::StartsWith => str_pred(l, r, |a, b| a.starts_with(b)),
BinaryOp::EndsWith => str_pred(l, r, |a, b| a.ends_with(b)),
BinaryOp::Contains => str_pred(l, r, |a, b| a.contains(b)),
BinaryOp::Regex => match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::String(a), Value::String(b)) => Value::Bool(regex_is_match(a, b)?),
_ => {
return Err(Error::invalid_argument_type(
"the regex operator requires string operands",
))
}
},
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum OrderingSide {
Greater,
Less,
}
impl OrderingSide {
pub(crate) fn is_greater(self) -> bool {
self == OrderingSide::Greater
}
}
pub(crate) struct OrderingOperator {
pub(crate) side: OrderingSide,
pub(crate) equality_allowed: bool,
pub(crate) pred: fn(Ordering) -> bool,
}
impl OrderingOperator {
const fn new(side: OrderingSide, equality_allowed: bool) -> Self {
let pred: fn(Ordering) -> bool = match (side, equality_allowed) {
(OrderingSide::Less, false) => Ordering::is_lt,
(OrderingSide::Less, true) => Ordering::is_le,
(OrderingSide::Greater, false) => Ordering::is_gt,
(OrderingSide::Greater, true) => Ordering::is_ge,
};
Self {
side,
equality_allowed,
pred,
}
}
}
pub(crate) fn ordering_operator(op: BinaryOp) -> Option<OrderingOperator> {
Some(match op {
BinaryOp::Lt => OrderingOperator::new(OrderingSide::Less, false),
BinaryOp::Gt => OrderingOperator::new(OrderingSide::Greater, false),
BinaryOp::Lte => OrderingOperator::new(OrderingSide::Less, true),
BinaryOp::Gte => OrderingOperator::new(OrderingSide::Greater, true),
_ => return None,
})
}
pub(crate) fn cmp_bool(
l: &Value,
r: &Value,
equality_allowed: bool,
pred: impl Fn(std::cmp::Ordering) -> bool,
) -> Value {
let ln = l.as_number();
let rn = r.as_number();
if ln.is_some_and(|f| f.is_nan()) || rn.is_some_and(|f| f.is_nan()) {
return if ln.is_some() && rn.is_some() {
Value::Bool(false)
} else {
Value::Null
};
}
match l.compare(r) {
Some(o) => Value::Bool(pred(o)),
None if equality_allowed => match l.cypher_eq(r) {
Value::Bool(true) => Value::Bool(true),
_ => Value::Null,
},
None => Value::Null,
}
}
pub(crate) fn in_rhs(value: &Value) -> Result<Option<&Arc<Vec<Value>>>> {
if value.is_null() {
return Ok(None);
}
match value {
Value::List(xs) => Ok(Some(xs)),
_ => Err(Error::invalid_argument_type(
"IN requires a list on the right-hand side",
)),
}
}
pub(crate) fn in_op(l: Value, r: Value) -> Result<Value> {
Ok(match in_rhs(&r)? {
Some(list) => super::member_of(&l, list),
None => Value::Null,
})
}
pub(crate) fn str_pred(l: Value, r: Value, f: impl Fn(&str, &str) -> bool) -> Value {
match (&l, &r) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::String(a), Value::String(b)) => Value::Bool(f(a, b)),
_ => Value::Null,
}
}
pub(crate) fn subscript(graph: &ExecGraph<'_>, v: &Value, index: Value) -> Result<Value> {
Ok(match (v, index) {
(Value::Null, _) | (_, Value::Null) => Value::Null,
(Value::List(xs), idx) => {
let i = match idx {
Value::Int(i) => i,
_ => {
return Err(Error::invalid_argument_type(
integer_args::LIST_INDEX.type_error,
))
}
};
let n = xs.len() as i64;
let i = if i < 0 { n + i } else { i };
if i < 0 || i >= n {
Value::Null
} else {
xs[i as usize].clone()
}
}
(_, Value::String(k)) => prop(
graph,
v,
&relate_names::unresolved(SmallName::from_name(&k)),
)?,
(Value::Vector { .. }, _) => {
return Err(Error::invalid_argument_type(
"vector indexing is not supported",
))
}
(Value::Map(_), _) | (Value::Node(_), _) | (Value::Relationship(_), _) => {
return Err(Error::ty(
"MapElementAccessByNonString: map index must be a string",
))
}
_ => {
return Err(Error::invalid_argument_type(
"subscript requires a list or map",
))
}
})
}
pub(crate) fn slice(v: &Value, start: Option<Value>, end: Option<Value>) -> Result<Value> {
let (start, end) = (start.as_ref(), end.as_ref());
Ok(match v {
Value::Null => Value::Null,
Value::List(xs) => match slice_bounds(xs.len(), start, end)? {
Some(range) => Value::List(xs[range].to_vec().into()),
None => Value::Null,
},
Value::String(s) => match slice_bounds(s.chars().count(), start, end)? {
Some(range) => Value::String(char_range(s, range).into()),
None => Value::Null,
},
_ => return Err(Error::ty("slice needs a list")),
})
}
fn slice_bounds(
len: usize,
start: Option<&Value>,
end: Option<&Value>,
) -> Result<Option<std::ops::Range<usize>>> {
if matches!(start, Some(Value::Null)) || matches!(end, Some(Value::Null)) {
return Ok(None);
}
let n = len as i64;
let bound = |b: Option<&Value>, missing: i64, what: &str| -> Result<usize> {
let i = match b {
None => missing,
Some(Value::Float(f)) => {
super::numeric::float_to_i64(*f).clamp(i64::from(i32::MIN), i64::from(i32::MAX))
}
Some(Value::Int(i)) => *i,
Some(_) => return Err(Error::ty(what)),
};
Ok((if i < 0 { i + n } else { i }).clamp(0, n) as usize)
};
let s = bound(start, 0, "slice start")?;
let e = bound(end, n, "slice end")?;
Ok(Some(s..e.max(s)))
}
pub(crate) fn eval_case(
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
when_then: &[(Expr, Expr)],
else_expr: &Option<Box<Expr>>,
) -> Result<Value> {
eval_case_with(when_then, else_expr, |expr| eval(graph, row, expr, params))
}
pub(crate) fn eval_case_with<'e>(
when_then: &'e [(Expr, Expr)],
else_expr: &'e Option<Box<Expr>>,
mut eval_expr: impl FnMut(&'e Expr) -> Result<Value>,
) -> Result<Value> {
for (when, then) in when_then {
if predicate_value_holds(&eval_expr(when)?)? {
return eval_expr(then);
}
}
match else_expr {
Some(e) => eval_expr(e),
None => Ok(Value::Null),
}
}
#[cfg(test)]
mod tests;