use relate_core::{Error, Result};
use relate_front::agg::is_aggregate_name as is_agg_fn;
use relate_ir::{BinaryOp, Clause, Expr, MapProjectionItem, UnaryOp};
use relate_names::SmallName;
use crate::binding::{pattern_local_bindings, require_bound, Binding, Env, EnvBridge};
use crate::expr_text::graph_call_text;
use crate::names::query_output_names_with_seed;
use crate::names::query_with_persistent_imports;
use crate::pattern::{check_path_exprs, check_pattern_pred_vars};
use crate::validate::{clause_is_write, validate_part_with_env};
mod function_meta;
pub(crate) mod literal;
pub(crate) mod shadowing;
use function_meta::apply_function_meta;
pub(crate) use literal::float_integer_site;
use literal::{is_non_integer_literal, is_static_non_bool};
use shadowing::{reject_binding_shadowing, reject_projection_shadowing};
#[derive(Clone, Copy)]
enum ExprPos {
Value,
Boolean(&'static str),
}
impl ExprPos {
fn allows_pattern_pred(self) -> bool {
matches!(self, ExprPos::Boolean(_))
}
fn of_binary_operands(op: BinaryOp) -> Self {
if op.is_boolean() {
ExprPos::Boolean(op.as_str())
} else {
ExprPos::Value
}
}
fn reject_static_non_bool(self, expr: &Expr) -> Result<()> {
match self {
ExprPos::Boolean(context) if is_static_non_bool(expr) => {
Err(Error::static_requires_boolean(context))
}
_ => Ok(()),
}
}
}
pub(crate) fn check_expr(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
expr: &Expr,
) -> Result<()> {
check_expr_ctx(env, is_write_procedure, expr, ExprPos::Value)
}
pub(crate) fn check_pred(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
expr: &Expr,
) -> Result<()> {
let pos = ExprPos::Boolean("predicate");
pos.reject_static_non_bool(expr)?;
if let Expr::Variable(v) = expr {
if matches!(
env.get_name(v),
Some(Binding::Node | Binding::Rel | Binding::Path)
) {
return Err(Error::invalid_argument_type(
"an entity or path is not a boolean predicate",
)
.into_syntax());
}
}
check_expr_ctx(env, is_write_procedure, expr, pos)
}
pub(crate) fn is_delete_target(expr: &Expr) -> bool {
matches!(
expr,
Expr::Variable(_)
| Expr::Property { .. }
| Expr::Subscript { .. }
| Expr::Function { .. }
| Expr::Case { .. }
| Expr::Null
)
}
fn reject_property_on_non_map(env: &Env, v: &SmallName) -> Result<()> {
if matches!(
env.get_name(v),
Some(&Binding::Path | &Binding::Scalar | &Binding::List)
) {
return Err(Error::syntax(
"InvalidArgumentType: property access on a non-map value",
));
}
Ok(())
}
pub(crate) fn check_nonneg_int_arg(expr: &Expr) -> Result<()> {
let negative = matches!(expr, Expr::Int(i) if *i < 0)
|| matches!(
expr,
Expr::Unary {
op: UnaryOp::Minus,
expr,
} if matches!(expr.as_ref(), Expr::Int(i) if *i > 0)
);
if negative {
return Err(Error::syntax(relate_core::negative_page_bound_text()));
}
Ok(())
}
pub(crate) fn check_positive_int_arg(expr: &Expr, what: &str) -> Result<()> {
match expr {
Expr::Int(i) if *i <= 0 => Err(Error::syntax(format!(
"InvalidArgument: {what} must be a positive integer"
))),
Expr::Unary {
op: UnaryOp::Minus,
expr,
} if matches!(expr.as_ref(), Expr::Int(_) | Expr::Float(_)) => Err(Error::syntax(format!(
"InvalidArgument: {what} must be a positive integer"
))),
_ if is_non_integer_literal(expr) => Err(Error::syntax(format!(
"InvalidArgumentType: {what} must be an integer"
))),
_ => Ok(()),
}
}
pub(crate) fn expr_non_static(expr: &Expr) -> bool {
expr.any(&mut |e| {
matches!(
e,
Expr::Variable(_)
| Expr::MapProjection { .. }
| Expr::PatternPred { .. }
| Expr::PatternComp { .. }
| Expr::ShortestPath { .. }
| Expr::ExistsSubquery { .. }
| Expr::CountSubquery { .. }
| Expr::CollectSubquery { .. }
)
})
}
fn expr_contains_rand(expr: &Expr) -> bool {
expr.any(&mut |e| {
matches!(e, Expr::Function { name, .. }
if name.with_str(|n| n.eq_ignore_ascii_case("rand")))
})
}
fn is_known_function(name: &str) -> bool {
relate_front::is_known_function(name)
}
fn check_subquery_expression(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
query: &relate_ir::Query,
) -> Result<Vec<String>> {
let imported: Vec<String> = env.keys().cloned().collect();
reject_projection_shadowing(query, &imported)?;
reject_binding_shadowing(query, env)?;
let scoped_query = query_with_persistent_imports(query, &imported);
if query
.parts
.iter()
.any(|part| matches!(part.clauses.last(), Some(Clause::Finish)))
{
return Err(Error::syntax(
"InvalidClauseComposition: FINISH is not allowed in a subquery expression",
));
}
for part in &scoped_query.parts {
if part
.clauses
.iter()
.any(|clause| clause_is_write(clause, is_write_procedure))
{
return Err(Error::syntax(
"InvalidClauseComposition: writes are not allowed in subquery expressions",
));
}
validate_part_with_env(
part,
crate::validate::Scope::expression_body(env.clone()),
is_write_procedure,
)?;
}
query_output_names_with_seed(&scoped_query, imported, &std::collections::HashSet::new())
}
fn check_expr_ctx(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
expr: &Expr,
pos: ExprPos,
) -> Result<()> {
match expr {
Expr::Variable(v) => {
require_bound(env, v)?;
}
Expr::Star => {}
Expr::Function { name, args, .. } => {
check_call(env, is_write_procedure, name, args)?;
}
Expr::Property { expr: inner, .. } => {
if let Expr::Variable(v) = inner.as_ref() {
reject_property_on_non_map(env, v)?;
}
expr.try_each_child(&mut |child| check_expr(env, &mut *is_write_procedure, child))?;
}
Expr::Unary { op, expr: operand } => {
let operand_pos = match op {
UnaryOp::Not => ExprPos::Boolean("NOT"),
UnaryOp::Plus | UnaryOp::Minus | UnaryOp::IsNull | UnaryOp::IsNotNull => {
ExprPos::Value
}
};
check_operands(env, is_write_procedure, operand_pos, &[operand.as_ref()])?;
}
Expr::Binary { op, left, right } => {
check_binary(env, is_write_procedure, *op, left, right)?;
}
Expr::Case {
when_then,
else_expr,
} => {
for (when, then) in when_then {
check_pred(env, is_write_procedure, when)?;
check_expr_ctx(env, is_write_procedure, then, pos)?;
}
if let Some(e) = else_expr {
check_expr_ctx(env, is_write_procedure, e, pos)?;
}
}
Expr::ListComp {
ident,
list,
predicate,
projection,
} => {
check_expr(env, is_write_procedure, list)?;
let mut inner = env.clone();
inner.insert_name(ident.clone(), Binding::Value);
if let Some(p) = predicate {
check_pred(&inner, is_write_procedure, p)?;
}
check_expr(&inner, is_write_procedure, projection)?;
}
Expr::MapComp {
key_ident,
value_ident,
source,
predicate,
key_expr,
value_expr,
} => {
check_expr(env, is_write_procedure, source)?;
let mut inner = env.clone();
if let Some(k) = key_ident {
inner.insert_name(k.clone(), Binding::Value);
}
inner.insert_name(value_ident.clone(), Binding::Value);
if let Some(p) = predicate {
check_pred(&inner, is_write_procedure, p)?;
}
check_expr(&inner, is_write_procedure, key_expr)?;
check_expr(&inner, is_write_procedure, value_expr)?;
}
Expr::Quantifier {
ident,
list,
predicate,
..
} => {
check_expr(env, is_write_procedure, list)?;
let mut inner = env.clone();
inner.insert_name(ident.clone(), Binding::Value);
check_pred(&inner, is_write_procedure, predicate)?;
}
Expr::Reduce {
accumulator,
initial,
ident,
list,
expression,
} => {
check_expr(env, is_write_procedure, initial)?;
check_expr(env, is_write_procedure, list)?;
let mut inner = env.clone();
inner.insert_name(accumulator.clone(), Binding::Value);
inner.insert_name(ident.clone(), Binding::Value);
check_expr(&inner, is_write_procedure, expression)?;
}
Expr::AllReduce {
accumulator,
initial,
ident,
list,
expression,
predicate,
} => {
check_expr(env, is_write_procedure, initial)?;
check_expr(env, is_write_procedure, list)?;
let mut inner = env.clone();
inner.insert_name(accumulator.clone(), Binding::Value);
inner.insert_name(ident.clone(), Binding::Value);
check_expr(&inner, is_write_procedure, expression)?;
check_pred(&inner, is_write_procedure, predicate)?;
}
Expr::PatternPred { path } => {
if !pos.allows_pattern_pred() {
return Err(Error::syntax(
"UnexpectedSyntax: pattern predicates are only valid in WHERE",
));
}
check_pattern_pred_vars(env, is_write_procedure, path)?;
if path.rels.is_empty() {
return Err(Error::syntax(
"InvalidArgumentType: a node pattern is not a valid predicate",
));
}
check_path_exprs(env, is_write_procedure, path)?;
}
Expr::ShortestPath { path, .. } => {
check_pattern_pred_vars(env, is_write_procedure, path)?;
check_path_exprs(env, is_write_procedure, path)?;
}
Expr::PatternComp {
path,
predicate,
projection,
} => {
let mut inner = env.clone();
for (name, binding) in pattern_local_bindings(path) {
inner.insert_name(name.clone(), binding);
}
check_path_exprs(&inner, is_write_procedure, path)?;
if let Some(p) = predicate {
check_pred(&inner, is_write_procedure, p)?;
}
check_expr(&inner, is_write_procedure, projection)?;
}
Expr::MapProjection {
expr: target,
items,
} => {
check_expr(env, is_write_procedure, target)?;
for item in items {
match item {
MapProjectionItem::KeyValue { value, .. } => {
check_expr(env, is_write_procedure, value)?
}
MapProjectionItem::Property { .. } => {
if let Expr::Variable(v) = target.as_ref() {
reject_property_on_non_map(env, v)?;
}
}
MapProjectionItem::Variable { name } => {
require_bound(env, name)?;
}
MapProjectionItem::AllProperties => {}
}
}
}
Expr::ExistsSubquery { query } | Expr::CountSubquery { query } => {
check_subquery_expression(env, is_write_procedure, query)?;
}
Expr::CollectSubquery { query } => {
let names = check_subquery_expression(env, is_write_procedure, query)?;
if names.len() != 1 {
return Err(Error::syntax(
"CollectExpressionMustReturnSingleColumn: COLLECT { } requires one column",
));
}
}
Expr::Subscript { expr: inner, index } => {
literal::reject_float_integer_site(expr)?;
check_expr(env, is_write_procedure, inner)?;
check_expr(env, is_write_procedure, index)?;
}
Expr::Slice { .. } => {
literal::reject_float_integer_site(expr)?;
expr.try_each_child(&mut |child| check_expr(env, &mut *is_write_procedure, child))?;
}
other => {
other.try_each_child(&mut |child| check_expr(env, &mut *is_write_procedure, child))?;
}
}
Ok(())
}
fn check_call(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
name: &SmallName,
args: &[Expr],
) -> Result<()> {
let n = name.with_str(str::to_ascii_lowercase);
if relate_core::is_graph_selector_function_name(&n) {
let call_text = graph_call_text(name, args);
relate_core::ce_messages::check_graph_selector_arity(&call_text, &n, args.len())?;
return Err(relate_core::ce_messages::composite_only_graph_function(
&call_text,
));
}
if !is_known_function(&n) {
return Err(name.with_str(Error::unknown_function));
}
apply_function_meta(env, &n, args)?;
let arg_pos = if n == "exists" {
ExprPos::Boolean("exists")
} else {
ExprPos::Value
};
if is_agg_fn(&n) && args.iter().any(expr_contains_rand) {
return Err(Error::syntax(
"NonConstantExpression: aggregations cannot contain rand()",
));
}
for (index, a) in args.iter().enumerate() {
if n == "property_exists" && index == 1 {
continue;
}
check_expr_ctx(env, is_write_procedure, a, arg_pos)?;
}
Ok(())
}
fn check_operands(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
pos: ExprPos,
operands: &[&Expr],
) -> Result<()> {
for operand in operands {
check_expr_ctx(env, is_write_procedure, operand, pos)?;
}
for operand in operands {
pos.reject_static_non_bool(operand)?;
}
Ok(())
}
fn check_binary(
env: &Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
op: BinaryOp,
left: &Expr,
right: &Expr,
) -> Result<()> {
if op.absorbing_constant(left, right).is_some() {
return Ok(());
}
check_operands(
env,
is_write_procedure,
ExprPos::of_binary_operands(op),
&[left, right],
)?;
if op == BinaryOp::In {
if let Expr::Bool(_) | Expr::Int(_) | Expr::Float(_) | Expr::String(_) = right {
return Err(Error::syntax(format!(
"InvalidArgumentType: {} requires a list",
BinaryOp::In.as_str()
)));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use relate_names::SmallName;
#[test]
fn static_boolean_requiring_sites_raise_the_syntax_class() {
let mut env = Env::new();
env.insert("n".to_string(), Binding::Node);
let err = check_pred(&env, &mut |_| false, &Expr::Int(1)).unwrap_err();
assert!(matches!(err, Error::Syntax(_)), "predicate: {err:?}");
assert!(
err.to_string().contains("predicate requires a boolean"),
"{err}"
);
let err = check_pred(
&env,
&mut |_| false,
&Expr::Variable(SmallName::from_name("n")),
)
.unwrap_err();
assert!(matches!(err, Error::Syntax(_)), "entity: {err:?}");
assert!(
err.to_string()
.contains("an entity or path is not a boolean predicate"),
"{err}"
);
let and = Expr::Binary {
op: BinaryOp::And,
left: Box::new(Expr::Int(1)),
right: Box::new(Expr::Bool(true)),
};
let err = check_expr(&env, &mut |_| false, &and).unwrap_err();
assert!(matches!(err, Error::Syntax(_)), "{err:?}");
assert!(err.to_string().contains("AND requires a boolean"), "{err}");
let not = Expr::Unary {
op: UnaryOp::Not,
expr: Box::new(Expr::Int(1)),
};
let err = check_expr(&env, &mut |_| false, ¬).unwrap_err();
assert!(matches!(err, Error::Syntax(_)), "{err:?}");
assert!(err.to_string().contains("NOT requires a boolean"), "{err}");
}
#[test]
fn a_folded_away_boolean_operand_is_exempt_from_the_static_rule() {
let env = Env::new();
let or = Expr::Binary {
op: BinaryOp::Or,
left: Box::new(Expr::Int(1)),
right: Box::new(Expr::Bool(true)),
};
check_expr(&env, &mut |_| false, &or)
.unwrap_or_else(|e| panic!("folded-away operand rejected: {e}"));
}
}