use relate_core::{Error, Result};
use relate_ir::{
is_agg_expr, CallArgs, Clause, Expr, PathPattern, RemoveItem, SetItem, YieldItems,
};
use relate_names::SmallName;
use crate::agg::{
check_agg_projections, check_aggregating_subclause, check_where_subclause, reject_agg_in_pred,
reject_order_by_agg, SubclauseScope,
};
use crate::binding::{bind_create_path, bind_path, projected_bindings, Binding, Env, EnvBridge};
use crate::expr_check::{check_expr, check_nonneg_int_arg, check_pred, is_delete_target};
use crate::names::{catalog_output_names, query_output_names};
use crate::pattern::{
check_juxtaposition, check_path_exprs, check_write_label_exprs, check_write_rels,
collect_qpp_group_names, element_has_qpp,
};
use super::chain::validate_nested_body;
use super::write::ClausePosition;
use super::{check_remove_item, check_set_item};
pub(super) fn check_catalog_clause(env: &mut Env, command: &relate_parser::Clause) -> Result<()> {
for name in catalog_output_names(command) {
env.insert(name, Binding::Value);
}
Ok(())
}
pub(super) fn check_match_clause(
env: &mut Env,
shadowable: &std::collections::HashSet<String>,
is_write_procedure: &mut impl FnMut(&str) -> bool,
clause: &Clause,
) -> Result<()> {
let Clause::Match {
patterns,
where_clause,
search,
..
} = clause
else {
unreachable!("clause arm");
};
let mut group_names = std::collections::HashSet::new();
for pattern in patterns {
collect_qpp_group_names(&pattern.elements, &mut group_names, env)?;
}
crate::pattern::check_shortest_path_bound_relationships(patterns, env, shadowable)?;
for p in patterns {
check_juxtaposition(p)?;
bind_path(env, p, shadowable)?;
}
for p in patterns {
check_path_exprs(env, is_write_procedure, p)?;
}
let has_qpp = patterns
.iter()
.any(|pattern| pattern.elements.iter().any(element_has_qpp));
if let Some(search) = search {
for expr in search.spec.exprs() {
check_expr(env, is_write_procedure, expr)?;
}
if let Some(score_var) = &search.score_var {
env.insert_name(score_var.clone(), Binding::Value);
}
if let Some(post) = &search.post_where {
check_match_where(env, is_write_procedure, has_qpp, post)?;
}
}
if let Some(w) = where_clause {
check_match_where(env, is_write_procedure, has_qpp, w)?;
}
Ok(())
}
fn check_match_where(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
has_qpp: bool,
w: &Expr,
) -> Result<()> {
match (has_qpp, is_agg_expr(w)) {
(false, _) => {
reject_agg_in_pred(w)?;
check_pred(env, is_write_procedure, w)
}
(true, false) => check_pred(env, is_write_procedure, w),
(true, true) => Ok(()),
}
}
pub(super) fn check_create_clause(
env: &mut Env,
shadowable: &std::collections::HashSet<String>,
is_write_procedure: &mut impl FnMut(&str) -> bool,
patterns: &[PathPattern],
) -> Result<()> {
let input_env = env.clone();
for p in patterns {
check_write_rels(p, true)?;
check_write_label_exprs(&input_env, is_write_procedure, p)?;
}
for p in patterns {
bind_create_path(env, p, shadowable)?;
check_path_exprs(env, is_write_procedure, p)?;
}
Ok(())
}
pub(super) fn check_merge_clause(
env: &mut Env,
shadowable: &std::collections::HashSet<String>,
is_write_procedure: &mut impl FnMut(&str) -> bool,
clause: &Clause,
) -> Result<()> {
let Clause::Merge {
pattern,
on_create,
on_match,
} = clause
else {
unreachable!("clause arm");
};
check_write_rels(pattern, false)?;
let input_env = env.clone();
check_write_label_exprs(&input_env, is_write_procedure, pattern)?;
bind_create_path(env, pattern, shadowable)?;
check_path_exprs(env, is_write_procedure, pattern)?;
for item in on_create.iter().chain(on_match.iter()) {
check_set_item(env, is_write_procedure, item)?;
}
Ok(())
}
pub(super) fn check_call_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
position: ClausePosition<'_>,
args: &CallArgs,
yield_items: &YieldItems,
where_clause: Option<&Expr>,
) -> Result<()> {
for a in args.args() {
check_expr(env, is_write_procedure, a)?;
if is_agg_expr(a) {
return Err(Error::syntax(
"InvalidAggregation: aggregations are not allowed in CALL arguments",
));
}
}
let star = matches!(yield_items, YieldItems::Star);
if star && !position.is_lone_substantive() {
return Err(Error::syntax(
"UnexpectedSyntax: YIELD * is not allowed in in-query CALL",
));
}
for name in yield_items.effective_names() {
if env.contains_name(name) {
return Err(name.with_str(Error::duplicate_variable));
}
}
let mut seen = std::collections::HashSet::new();
for name in yield_items.effective_names() {
if !seen.insert(name.clone()) {
return Err(name.with_str(Error::duplicate_variable));
}
env.insert_name(name.clone(), Binding::Value);
}
if let Some(predicate) = where_clause {
check_pred(env, is_write_procedure, predicate)?;
}
Ok(())
}
fn is_label_predicate(e: &Expr) -> bool {
match e {
Expr::LabelPredicate { .. } => true,
Expr::Unary {
op: relate_ir::UnaryOp::Not,
expr,
} => is_label_predicate(expr),
_ => false,
}
}
pub(super) fn check_delete_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
expressions: &[Expr],
) -> Result<()> {
for e in expressions {
check_expr(env, is_write_procedure, e)?;
if is_label_predicate(e) {
return Err(Error::syntax(
"InvalidDelete: cannot delete a literal or label expression",
));
}
if !is_delete_target(e) {
return Err(Error::syntax(
"InvalidArgumentType: DELETE requires a node, relationship, or path",
));
}
if let Expr::Variable(v) = e {
if matches!(env.get_name(v), Some(&Binding::Scalar | &Binding::List)) {
return Err(Error::syntax("InvalidDelete: cannot delete a non-entity"));
}
}
}
Ok(())
}
pub(super) fn check_set_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
items: &[SetItem],
) -> Result<()> {
for item in items {
check_set_item(env, is_write_procedure, item)?;
}
Ok(())
}
pub(super) fn check_remove_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
items: &[RemoveItem],
) -> Result<()> {
for item in items {
check_remove_item(env, is_write_procedure, item)?;
}
Ok(())
}
pub(super) fn check_with_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
imports: &crate::agg::Imports,
clause: &Clause,
) -> Result<()> {
let Clause::With {
distinct,
items,
group_by,
order,
skip,
limit,
where_clause,
origin,
..
} = clause
else {
unreachable!("clause arm");
};
if *origin == relate_ir::WithOrigin::Let {
for item in items.iter().filter(|item| !matches!(item.expr, Expr::Star)) {
let Some(name) = item.alias.as_ref() else {
continue;
};
if env.contains_name(name) {
return Err(Error::syntax(format!(
"VariableAlreadyBound: LET cannot rebind `{name}`"
)));
}
if is_agg_expr(&item.expr) {
return Err(Error::syntax(
"InvalidAggregation: aggregations are not allowed in LET",
));
}
}
}
let mut seen = std::collections::HashMap::new();
for (i, item) in items.iter().enumerate() {
if matches!(item.expr, Expr::Star) {
continue;
}
if super::is_unaliased_expression(item) {
return Err(Error::syntax(
"NoExpressionAlias: WITH expressions must be aliased",
));
}
let name = item.output_name(i);
if seen.contains_key(&name) {
return Err(Error::syntax(format!(
"ColumnNameConflict: `{name}` is already defined"
)));
}
seen.insert(name, ());
}
for item in items {
check_expr(env, is_write_procedure, &item.expr)?;
}
let has_star = items.iter().any(|item| matches!(item.expr, Expr::Star));
let projected = projected_bindings(env, items);
let effective_imports: crate::agg::Imports = imports
.iter()
.filter(|n| (has_star && env.contains_key(*n)) || projected.contains_key(*n))
.cloned()
.collect();
check_agg_projections(items, group_by.as_deref(), &effective_imports, env)?;
let mut order_env = env.clone();
order_env.extend(projected.clone());
let next = if has_star {
order_env.clone()
} else {
projected
};
let subclauses = SubclauseScope::new(items, group_by.as_deref(), *distinct, imports, env);
reject_order_by_agg(&subclauses, order, &effective_imports)?;
for o in order {
check_aggregating_subclause(&subclauses, &o.expr, "ORDER BY")?;
check_expr(&order_env, is_write_procedure, &o.expr)?;
}
if let Some(s) = skip {
check_expr(&order_env, is_write_procedure, s)?;
check_nonneg_int_arg(s)?;
}
if let Some(l) = limit {
check_expr(&order_env, is_write_procedure, l)?;
check_nonneg_int_arg(l)?;
}
if let Some(w) = where_clause {
check_where_subclause(&subclauses, &effective_imports, w)?;
check_pred(&order_env, is_write_procedure, w)?;
}
*env = next;
Ok(())
}
pub(super) fn check_return_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
imports: &crate::agg::Imports,
clause: &Clause,
) -> Result<()> {
let Clause::Return {
items,
group_by,
order,
skip,
limit,
distinct,
..
} = clause
else {
unreachable!("clause arm");
};
if items.iter().any(|item| matches!(item.expr, Expr::Star)) && env.is_empty() {
return Err(Error::syntax(
"NoVariablesInScope: RETURN * requires variables in scope",
));
}
let mut seen = std::collections::HashMap::new();
for item in items {
let Some(name) = item.alias.clone() else {
continue;
};
if seen.contains_key(&name) {
return Err(Error::syntax(format!(
"ColumnNameConflict: `{name}` is already defined"
)));
}
seen.insert(name, ());
}
for item in items {
check_expr(env, is_write_procedure, &item.expr)?;
}
check_agg_projections(items, group_by.as_deref(), imports, env)?;
let subclauses = SubclauseScope::new(items, group_by.as_deref(), *distinct, imports, env);
reject_order_by_agg(&subclauses, order, imports)?;
if !order.is_empty() || skip.is_some() || limit.is_some() {
let mut order_env = env.clone();
order_env.extend(projected_bindings(env, items));
for o in order {
check_aggregating_subclause(&subclauses, &o.expr, "ORDER BY")?;
check_expr(&order_env, is_write_procedure, &o.expr)?;
}
if let Some(s) = skip {
check_expr(&order_env, is_write_procedure, s)?;
check_nonneg_int_arg(s)?;
}
if let Some(l) = limit {
check_expr(&order_env, is_write_procedure, l)?;
check_nonneg_int_arg(l)?;
}
}
Ok(())
}
pub(super) fn check_unwind_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
expression: &Expr,
alias: &SmallName,
) -> Result<()> {
check_expr(env, is_write_procedure, expression)?;
env.insert_name(alias.clone(), Binding::Value);
Ok(())
}
pub(super) fn check_load_csv_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
url: &Expr,
variable: &SmallName,
) -> Result<()> {
check_expr(env, is_write_procedure, url)?;
env.insert_name(variable.clone(), Binding::Map);
Ok(())
}
pub(super) fn check_conditional_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
clause: &Clause,
) -> Result<()> {
let Clause::Conditional {
branches,
else_query,
} = clause
else {
unreachable!("clause arm");
};
let bodies = branches
.iter()
.map(|(predicate, query)| (Some(predicate), query))
.chain(else_query.as_deref().map(|query| (None, query)));
let mut expected = None;
for (predicate, query) in bodies {
if let Some(predicate) = predicate {
check_pred(env, is_write_procedure, predicate)?;
}
super::refuse_unaliased_terminal_returns(
query,
"NoExpressionAlias: expressions returned by conditional clauses must use AS",
)?;
for part in &query.parts {
validate_nested_body(
&part.clauses,
super::Scope::branch_body(env.clone()),
is_write_procedure,
)?;
}
let names = query_output_names(query)?;
if expected.as_ref().is_some_and(|e| e != &names) {
return Err(Error::syntax(
"ColumnNameConflict: conditional branches must return the same columns",
));
}
expected = Some(names);
}
*env = expected
.unwrap_or_default()
.into_iter()
.map(|name| (name, Binding::Value))
.collect();
Ok(())
}
pub(super) fn check_foreach_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
variable: &SmallName,
list: &Expr,
clauses: &[Clause],
) -> Result<()> {
check_expr(env, is_write_procedure, list)?;
validate_nested_body(
clauses,
super::Scope::foreach_body(env, variable),
is_write_procedure,
)?;
Ok(())
}
pub(super) fn check_use_clause(
env: &mut Env,
is_write_procedure: &mut impl FnMut(&str) -> bool,
position: ClausePosition<'_>,
graph: &Expr,
) -> Result<()> {
let all_use_before = position.clauses[..position.index]
.iter()
.all(crate::clause_kind::clause_is_routing);
let after_importing_with =
position.index == 1 && matches!(position.clauses.first(), Some(Clause::With { .. }));
if !all_use_before && !after_importing_with {
return Err(Error::syntax(
"InvalidPlacementOfUseClause: USE must be the first clause",
));
}
if crate::use_target::static_graph_name(graph).is_none() {
if let Some(args) = crate::use_target::graph_selector_args(graph) {
for arg in args {
check_expr(env, is_write_procedure, arg)?;
}
} else {
check_expr(env, is_write_procedure, graph)?;
}
}
Ok(())
}