crates/kleene-gql/src/parser.rs
//! A recursive-descent parser for the GQL subset (from the parked openCypher parser).
//!
//! ```text
//! query := [call] match* return [';'] -- at least one MATCH or a CALL; a CALL alone may leave out RETURN
//! call := CALL name ('.' name)* '(' [arg (',' arg)*] ')' [YIELD name [AS name] (',' name [AS name])*] [WHERE cond]
//! arg := name | int | '$' name
//! match := MATCH path (',' path)* [WHERE cond]
//! path := [name '='] [ANY [SHORTEST] | ALL SHORTEST] [WALK] [PATH | PATHS] pattern
//! | [name '='] (shortestPath | allShortestPaths) '(' pattern ')'
//! pattern := node (edge node)*
//! node := '(' [name] [labels] ')'
//! labels := (':' | IS) label ('|' label)* -- one of them
//! edge := ('-' | '<-') '[' body ']' ('->' | '-') [quant] -- '-[]-', '<-[]->': either way
//! | ('->' | '<-' | '-' | '-->' | '<--' | '--') [quant] -- any label
//! body := [name] [labels] ['*' [int] ['..' [int]]] -- Cypher length
//! quant := '*' | '+' | '{' [int] [',' [int]] '}' -- GQL quantifier
//! cond := xor (OR xor)*
//! xor := and (XOR and)*
//! and := not (AND not)*
//! not := NOT not | '(' cond ')' | operand op operand
//! | operand IN ('(' | '[') [operand (',' operand)*] (')' | ']')
//! | operand IS [NOT] NULL | operand (STARTS WITH | ENDS WITH | CONTAINS) operand
//! operand := name | name '.' key | ['-'] int | ['-'] float | string | '$' name
//! | TRUE | FALSE | NULL
//! value := sum ('||' sum)* -- string concatenation
//! | (char_length | character_length) '(' value ')' | substring '(' value ',' value [',' value] ')'
//! return := RETURN [DISTINCT] item (',' item)* [ORDER BY key (',' key)*]
//! [(OFFSET | SKIP) int] [LIMIT int]
//! key := name ['.' key] [ASC | ASCENDING | DESC | DESCENDING]
//! item := (name ['.' key] | agg | length '(' name ')' | nodes '(' name ')') [AS name]
//! agg := count '(' '*' ')' | (count | min | max | sum | avg) '(' [DISTINCT] name ['.' key] ')'
//! ```
use crate::ast::*;
use crate::error::{GqlError, Result};
use crate::lexer::{Tok, Token, lex};
/// Parse a query.
pub fn parse(text: &str) -> Result<Query> {
let mut p = Parser {
toks: lex(text)?,
at: 0,
text,
maps: Vec::new(),
anon: 0,
};
p.query()
}
/// Words that are never variable names.
const RESERVED: &[&str] = &[
"MATCH", "WHERE", "RETURN", "DISTINCT", "LIMIT", "AND", "OR", "NOT", "AS", "IS", "XOR", "IN",
"TRUE", "FALSE", "NULL", "CALL", "YIELD", "OPTIONAL", "UNION", "WITH", "UNWIND",
];
struct Parser<'t> {
toks: Vec<Token>,
at: usize,
text: &'t str,
/// The equalities of node property maps (`{key: value}`) read in the current clause,
/// taken into its WHERE.
maps: Vec<Condition>,
/// Names given to unnamed nodes with a property map.
anon: usize,
}
impl Parser<'_> {
fn peek(&self) -> &Tok {
&self.toks[self.at].kind
}
fn pos(&self) -> usize {
self.toks[self.at].start
}
fn bump(&mut self) -> Tok {
let t = self.toks[self.at].kind.clone();
if self.at + 1 < self.toks.len() {
self.at += 1;
}
t
}
fn err<T>(&self, msg: impl Into<String>) -> Result<T> {
Err(GqlError::Syntax {
pos: self.pos(),
msg: msg.into(),
})
}
fn is_kw(&self, kw: &str) -> bool {
matches!(self.peek(), Tok::Ident(s) if s.eq_ignore_ascii_case(kw))
}
fn eat_kw(&mut self, kw: &str) -> bool {
if self.is_kw(kw) {
self.bump();
true
} else {
false
}
}
fn eat(&mut self, t: &Tok) -> bool {
if self.peek() == t {
self.bump();
true
} else {
false
}
}
fn expect(&mut self, t: &Tok, what: &str) -> Result<()> {
if self.eat(t) {
Ok(())
} else {
self.err(format!("expected {what}"))
}
}
fn is_name(&self) -> bool {
match self.peek() {
Tok::Ident(s) => !RESERVED.iter().any(|r| r.eq_ignore_ascii_case(s)),
Tok::Quoted(_) => true,
_ => false,
}
}
/// A variable name: an identifier that is not reserved, or a back-quoted one.
fn name(&mut self) -> Result<String> {
if !self.is_name() {
return self.err("expected a name");
}
match self.bump() {
Tok::Ident(s) | Tok::Quoted(s) => Ok(s),
_ => unreachable!("is_name checked the token"),
}
}
/// A label or property key: any identifier, keywords included.
fn symbol(&mut self) -> Result<String> {
match self.peek().clone() {
Tok::Ident(s) | Tok::Quoted(s) => {
self.bump();
Ok(s)
}
_ => self.err("expected a name"),
}
}
fn int(&mut self, what: &str) -> Result<u64> {
match *self.peek() {
Tok::Int(i) => {
self.bump();
Ok(i)
}
_ => self.err(format!("expected {what} (an unsigned integer)")),
}
}
/// A query, then `UNION [ALL] query` parts (all `UNION` or all `UNION ALL`), then the end.
fn query(&mut self) -> Result<Query> {
let mut q = self.part()?;
let mut all: Option<bool> = None;
while self.eat_kw("UNION") {
let a = self.eat_kw("ALL");
if all.is_some_and(|x| x != a) {
return self.err("UNION and UNION ALL mixed in one query");
}
all = Some(a);
let p = self.part()?;
q.union.push(p);
}
q.union_all = all.unwrap_or(false);
self.eat(&Tok::Semi);
if self.peek() != &Tok::Eof {
return self.err("unexpected text after the end");
}
Ok(q)
}
/// `[CALL ...] (MATCH | OPTIONAL MATCH ...)* (RETURN ... | WITH ... [WHERE ...] part)`.
fn part(&mut self) -> Result<Query> {
self.part_after(None, Vec::new())
}
/// A part; after a `WITH` (`prior`, its `WHERE` `with_filter`) it may begin with
/// `OPTIONAL MATCH` or have no `MATCH` at all.
fn part_after(
&mut self,
prior: Option<Box<Query>>,
with_filter: Vec<Condition>,
) -> Result<Query> {
let mut prior = prior;
let unwind = if self.eat_kw("UNWIND") {
let u = self.unwind()?;
Some(match prior.as_deref_mut() {
Some(before) => self.edge_unwind(u, before)?,
None => u,
})
} else {
None
};
let call = if prior.is_none() && unwind.is_none() && self.eat_kw("CALL") {
Some(self.call()?)
} else {
None
};
let mut matches: Vec<Match> = Vec::new();
loop {
let optional = self.eat_kw("OPTIONAL");
if !self.eat_kw("MATCH") {
if optional {
return self.err("expected MATCH after OPTIONAL");
}
break;
}
if !optional && matches.iter().any(|m| m.optional) {
return self.err(
"a MATCH after an OPTIONAL MATCH is not read yet: put a WITH between them",
);
}
let mut m = self.match_clause()?;
m.optional = optional;
matches.push(m);
}
let first = call.is_none() && prior.is_none() && unwind.is_none();
if matches.first().is_some_and(|m| m.optional) && first {
return self.err("OPTIONAL MATCH first: a MATCH (or CALL) before it");
}
if matches.is_empty() && first {
return self.err("expected MATCH or CALL");
}
// An UNWIND after clauses: their rows (every name they bind) the part before it.
if self.is_kw("UNWIND") {
let mut ret = Return {
distinct: false,
items: scope(&matches, prior.as_deref())
.iter()
.map(|v| var_item(v))
.collect(),
order: Vec::new(),
offset: None,
limit: None,
};
if let Some(u) = &unwind
&& !ret.items.iter().any(|it| it.name() == u.alias)
{
ret.items.push(var_item(&u.alias));
}
lengths(&matches, &mut ret);
hide(&matches, prior.as_deref(), &mut ret);
let before = Query {
prior,
with_filter,
unwind,
call,
matches,
ret,
union: Vec::new(),
union_all: false,
};
return self.part_after(Some(Box::new(before)), Vec::new());
}
if self.is_kw("CALL") && self.toks[self.at + 1].kind == Tok::LBrace {
return self.subquery(prior, with_filter, unwind, call, matches);
}
let with = self.eat_kw("WITH");
let mut ret = if with || self.eat_kw("RETURN") {
self.ret()?
} else if call.is_some()
&& matches.is_empty()
&& (matches!(self.peek(), Tok::Eof | Tok::Semi) || self.is_kw("UNION"))
{
Return {
distinct: false,
items: Vec::new(),
order: Vec::new(),
offset: None,
limit: None,
}
} else {
return self.err("expected MATCH, WHERE, WITH or RETURN");
};
// `shortestPath(...) AS p` as an item: the path of an OPTIONAL MATCH (a MATCH
// when it is the first), the item the path variable.
for it in &mut ret.items {
if let ReturnValue::Path(p) = &it.value {
let Some(alias) = it.alias.clone() else {
return self.err("a path function as an item needs AS name");
};
let mut p = (**p).clone();
p.var = Some(alias.clone());
matches.push(Match {
paths: vec![p],
filter: Vec::new(),
optional: !matches.is_empty() || call.is_some() || prior.is_some(),
});
it.value = ReturnValue::Value(Operand::Var(alias));
it.alias = None;
}
}
if with {
lengths(&matches, &mut ret);
hide(&matches, prior.as_deref(), &mut ret);
}
let q = Query {
prior,
with_filter,
unwind,
call,
matches,
ret,
union: Vec::new(),
union_all: false,
};
if !with {
return Ok(q);
}
let mut filter = Vec::new();
if self.eat_kw("WHERE") {
self.cond(&mut filter)?;
}
self.part_after(Some(Box::new(q)), filter)
}
/// `CALL { [WITH v, ...] part RETURN ... }` after the clauses of a part: the part's rows
/// (every name it binds) as the subquery's first rows, the subquery's rows with its
/// returned columns and the outer names, then the rest of the query on those.
fn subquery(
&mut self,
prior: Option<Box<Query>>,
with_filter: Vec<Condition>,
unwind: Option<Unwind>,
call: Option<CallClause>,
matches: Vec<Match>,
) -> Result<Query> {
if matches.is_empty() && prior.is_none() {
return self.err("CALL { ... } first: a MATCH before it, in this version");
}
self.bump();
self.bump();
let mut names = scope(&matches, prior.as_deref());
if let Some(u) = &unwind
&& !names.contains(&u.alias)
{
names.push(u.alias.clone());
}
let mut ret = Return {
distinct: false,
items: names.iter().map(|v| var_item(v)).collect(),
order: Vec::new(),
offset: None,
limit: None,
};
lengths(&matches, &mut ret);
hide(&matches, prior.as_deref(), &mut ret);
let outer = Query {
prior,
with_filter,
unwind,
call,
matches,
ret,
union: Vec::new(),
union_all: false,
};
let names: Vec<String> = outer.ret.items.iter().map(ReturnItem::name).collect();
let pass: Vec<ReturnItem> = outer
.ret
.items
.iter()
.map(|it| match it.value {
ReturnValue::Length(_) => ReturnItem {
value: ReturnValue::Length(it.name()),
alias: Some(it.name()),
},
_ => var_item(&it.name()),
})
.collect();
// The importing WITH: names of the outer part.
if self.eat_kw("WITH") {
loop {
let at = self.pos();
let v = self.name()?;
if !names.contains(&v) {
return Err(GqlError::Syntax {
pos: at,
msg: format!("`{v}` is not bound before the subquery"),
});
}
if !self.eat(&Tok::Comma) {
break;
}
}
}
let mut inner = self.part_after(Some(Box::new(outer)), Vec::new())?;
if inner.ret.items.is_empty() {
return self.err("a subquery that returns nothing is not read yet");
}
if !inner.ret.order.is_empty() || inner.ret.offset.is_some() || inner.ret.limit.is_some() {
return self
.err("ORDER BY, SKIP or LIMIT inside CALL { } (per outer row) is not read yet");
}
// A subquery of aggregates alone gives one row per outer row (a count of none is
// 0): its one MATCH an OPTIONAL MATCH.
let aggregates = inner
.ret
.items
.iter()
.all(|it| matches!(it.value, ReturnValue::Aggregate { .. }));
if aggregates && inner.matches.len() == 1 {
inner.matches[0].optional = true;
}
// The outer names go on beside the subquery's columns.
for it in pass {
if !inner.ret.items.iter().any(|x| x.name() == it.name()) {
inner.ret.items.push(it);
}
}
lengths(&inner.matches, &mut inner.ret);
hide(&inner.matches, inner.prior.as_deref(), &mut inner.ret);
self.expect(&Tok::RBrace, "} to close the subquery")?;
self.part_after(Some(Box::new(inner)), Vec::new())
}
/// `name ('.' name)* '(' [arg (',' arg)*] ')' [YIELD column [AS name], ...] [WHERE cond]`.
fn call(&mut self) -> Result<CallClause> {
let mut procedure = self.symbol()?;
while self.eat(&Tok::Dot) {
procedure.push('.');
procedure.push_str(&self.symbol()?);
}
self.expect(&Tok::LParen, "( after the procedure's name")?;
let mut args = Vec::new();
if !self.eat(&Tok::RParen) {
loop {
let arg = match self.peek().clone() {
Tok::Int(_) | Tok::Param(_) => CallArg::Value(self.operand()?),
_ if self.is_kw("NULL") => {
self.bump();
CallArg::Value(Operand::Null)
}
Tok::Ident(s) | Tok::Quoted(s) => {
self.bump();
CallArg::Name(s)
}
Tok::Str => {
let s = crate::lexer::string_at(self.text, self.pos())?;
self.bump();
CallArg::Name(s)
}
_ => {
return self.err(
"an argument: an edge label, a key, an integer, a $parameter or NULL",
);
}
};
args.push(arg);
if self.eat(&Tok::RParen) {
break;
}
self.expect(&Tok::Comma, ", or ) in the arguments")?;
}
}
let mut yields = Vec::new();
if self.eat_kw("YIELD") {
loop {
let column = self.symbol()?;
let alias = if self.eat_kw("AS") {
Some(self.name()?)
} else {
None
};
yields.push(YieldItem { column, alias });
if !self.eat(&Tok::Comma) {
break;
}
}
}
let mut filter = Vec::new();
if self.eat_kw("WHERE") {
if yields.is_empty() {
return self.err("WHERE after CALL needs a YIELD");
}
self.cond(&mut filter)?;
}
Ok(CallClause {
procedure,
args,
yields,
filter,
})
}
fn match_clause(&mut self) -> Result<Match> {
let mut paths = vec![self.path()?];
while self.eat(&Tok::Comma) {
paths.push(self.path()?);
}
let mut filter = std::mem::take(&mut self.maps);
if self.eat_kw("WHERE") {
self.cond(&mut filter)?;
}
Ok(Match {
paths,
filter,
optional: false,
})
}
/// `[p =] [ANY [SHORTEST] | ALL SHORTEST] [WALK] [PATH | PATHS] pattern`, or Cypher's
/// `[p =] shortestPath(pattern)` and `allShortestPaths(pattern)`.
fn path(&mut self) -> Result<PathPattern> {
let var = if self.is_name() && self.toks[self.at + 1].kind == Tok::Eq {
let v = self.name()?;
self.bump();
Some(v)
} else {
None
};
let cypher = match self.peek() {
Tok::Ident(s) if self.toks[self.at + 1].kind == Tok::LParen => {
match s.to_ascii_lowercase().as_str() {
"shortestpath" => Some(Selector::AnyShortest),
"allshortestpaths" => Some(Selector::AllShortest),
"any" | "all" | "shortest" => None,
other => return self.err(format!("no path function `{other}`")),
}
}
_ => None,
};
if let Some(sel) = cypher {
self.bump();
self.bump();
let mut p = self.pattern()?;
self.expect(&Tok::RParen, ") to close the shortest path")?;
p.var = var;
p.selector = Some(sel);
return Ok(p);
}
let selector = if self.eat_kw("ANY") {
if matches!(self.peek(), Tok::Int(_)) {
return self.err("ANY k: one path per pair only (ANY or ANY SHORTEST)");
}
if self.eat_kw("SHORTEST") {
Some(Selector::AnyShortest)
} else {
Some(Selector::Any)
}
} else if self.eat_kw("ALL") {
if !self.eat_kw("SHORTEST") {
return self
.err("ALL paths: a walk pattern can have infinitely many; ALL SHORTEST");
}
Some(Selector::AllShortest)
} else if self.eat_kw("SHORTEST") {
return self.err("SHORTEST k [GROUP]: ANY SHORTEST or ALL SHORTEST only");
} else {
None
};
for mode in ["TRAIL", "SIMPLE", "ACYCLIC"] {
if self.eat_kw(mode) {
return self.err(format!("path mode {mode}: only WALK (the default)"));
}
}
self.eat_kw("WALK");
if !self.eat_kw("PATHS") {
self.eat_kw("PATH");
}
let mut p = self.pattern()?;
p.var = var;
p.selector = selector;
Ok(p)
}
fn pattern(&mut self) -> Result<PathPattern> {
let start = self.node()?;
let mut steps = Vec::new();
while matches!(self.peek(), Tok::Minus | Tok::Lt) {
let e = self.edge()?;
let n = self.node()?;
steps.push((e, n));
}
Ok(PathPattern {
var: None,
selector: None,
start,
steps,
})
}
/// `:Label`, `IS Label` or `:A|B|...` (one of them); none: empty.
fn labels(&mut self) -> Result<Vec<String>> {
if !(self.eat(&Tok::Colon) || self.eat_kw("IS")) {
return Ok(Vec::new());
}
let mut out = vec![self.symbol()?];
while self.eat(&Tok::Pipe) {
out.push(self.symbol()?);
}
if matches!(self.peek(), Tok::Colon) {
return self.err("one label or label alternatives (:A|B) per pattern in this version");
}
Ok(out)
}
fn node(&mut self) -> Result<NodePattern> {
self.expect(&Tok::LParen, "( to open a node")?;
let mut n = NodePattern::default();
if self.is_name() {
n.var = Some(self.name()?);
}
n.labels = self.labels()?;
if self.eat(&Tok::LBrace) {
// `{key: value, ...}`: `var.key = value` in the clause's WHERE; an unnamed node
// gets a name no query can write.
let var = match &n.var {
Some(v) => v.clone(),
None => {
self.anon += 1;
let v = format!("#{}", self.anon);
n.var = Some(v.clone());
v
}
};
loop {
let key = self.name()?;
self.expect(&Tok::Colon, ": after a property's key")?;
let value = self.operand()?;
self.maps.push(Condition::Cmp(Comparison {
left: Operand::Prop(var.clone(), key),
op: CmpOp::Eq,
right: value,
}));
if !self.eat(&Tok::Comma) {
break;
}
}
self.expect(&Tok::RBrace, "} to close a property map")?;
}
self.expect(&Tok::RParen, ") to close a node")?;
Ok(n)
}
fn edge(&mut self) -> Result<EdgePattern> {
let left = self.eat(&Tok::Lt);
self.expect(&Tok::Minus, "-")?;
if !self.eat(&Tok::LBracket) {
// No brackets: `->`, `<-`, `-`, or Cypher's `-->`, `<--`, `--`.
self.eat(&Tok::Minus);
let right = self.eat(&Tok::Gt);
let dir = match (left, right) {
(false, true) => Dir::Out,
(true, false) => Dir::In,
_ => Dir::Any,
};
let quant = self.quantifier()?;
return Ok(EdgePattern {
var: None,
labels: Vec::new(),
dir,
quant,
});
}
let var = if self.is_name() {
Some(self.name()?)
} else {
None
};
let labels = self.labels()?;
let mut quant = None;
if self.eat(&Tok::Star) {
// Cypher's length inside the brackets: `*` and `*..n` start at 1.
let lo = if let Tok::Int(i) = *self.peek() {
self.bump();
Some(i)
} else {
None
};
quant = Some(if self.eat(&Tok::DotDot) {
let hi = if let Tok::Int(i) = *self.peek() {
self.bump();
Some(i)
} else {
None
};
Quantifier {
min: lo.unwrap_or(1),
max: hi,
}
} else {
match lo {
Some(n) => Quantifier {
min: n,
max: Some(n),
},
None => Quantifier { min: 1, max: None },
}
});
}
self.expect(&Tok::RBracket, "] to close an edge")?;
self.expect(&Tok::Minus, "-")?;
let right = self.eat(&Tok::Gt);
let dir = match (left, right) {
(false, true) => Dir::Out,
(true, false) => Dir::In,
_ => Dir::Any,
};
if let Some(q) = self.quantifier()? {
if quant.is_some() {
return self.err("a length inside the brackets and a quantifier after them");
}
quant = Some(q);
}
if let Some(Quantifier {
min,
max: Some(max),
}) = quant
&& max < min
{
return self.err(format!("a path length range {min}..{max} holds nothing"));
}
Ok(EdgePattern {
var,
labels,
dir,
quant,
})
}
/// GQL's quantifier after an edge pattern: `*`, `+`, `{m,n}`, `{m,}`, `{,n}`, `{m}`.
fn quantifier(&mut self) -> Result<Option<Quantifier>> {
if self.eat(&Tok::Star) {
return Ok(Some(Quantifier { min: 0, max: None }));
}
if self.eat(&Tok::Plus) {
return Ok(Some(Quantifier { min: 1, max: None }));
}
if !self.eat(&Tok::LBrace) {
return Ok(None);
}
// `{,n}`: from 0.
let from_zero = matches!(self.peek(), Tok::Comma);
let min = if from_zero {
0
} else {
self.int("the fewest edges")?
};
let max = if self.eat(&Tok::Comma) {
if let Tok::Int(i) = *self.peek() {
self.bump();
Some(i)
} else {
None
}
} else {
Some(min)
};
if from_zero && max.is_none() {
return self.err("`{,}` has no bound: write `*` or `{0,}`");
}
self.expect(&Tok::RBrace, "} to close a quantifier")?;
Ok(Some(Quantifier { min, max }))
}
/// A condition, its top-level `AND` parts pushed in order (brackets around an `AND`
/// at the top flattened too).
fn cond(&mut self, out: &mut Vec<Condition>) -> Result<()> {
fn flat(c: Condition, out: &mut Vec<Condition>) {
match c {
Condition::And(parts) => parts.into_iter().for_each(|p| flat(p, out)),
c => out.push(c),
}
}
let c = self.or()?;
flat(c, out);
Ok(())
}
fn or(&mut self) -> Result<Condition> {
let mut parts = vec![self.xor()?];
while self.eat_kw("OR") {
parts.push(self.xor()?);
}
Ok(if parts.len() == 1 {
parts.pop().expect("one part")
} else {
Condition::Or(parts)
})
}
fn xor(&mut self) -> Result<Condition> {
let mut c = self.and()?;
while self.eat_kw("XOR") {
let r = self.and()?;
c = Condition::Xor(Box::new(c), Box::new(r));
}
Ok(c)
}
fn and(&mut self) -> Result<Condition> {
let mut parts = vec![self.not()?];
while self.eat_kw("AND") {
parts.push(self.not()?);
}
Ok(if parts.len() == 1 {
parts.pop().expect("one part")
} else {
Condition::And(parts)
})
}
fn not(&mut self) -> Result<Condition> {
if self.eat_kw("NOT") {
return Ok(Condition::Not(Box::new(self.not()?)));
}
if self.eat(&Tok::LParen) {
let c = self.or()?;
self.expect(&Tok::RParen, ") to close a condition")?;
return Ok(c);
}
if let Tok::Ident(f) = self.peek()
&& self.toks[self.at + 1].kind == Tok::LParen
{
let quant = match f.to_ascii_lowercase().as_str() {
"all" => Some(ListQuant::All),
"any" => Some(ListQuant::Any),
"none" => Some(ListQuant::None),
"single" => Some(ListQuant::Single),
_ => None,
};
if let Some(quant) = quant {
self.bump();
self.bump();
let var = self.name()?;
if !self.eat_kw("IN") {
return self.err(format!("expected IN after {}({var}", quant.name()));
}
let list = self.name()?;
if !self.eat_kw("WHERE") {
return self.err(format!("expected WHERE in {}(...)", quant.name()));
}
let pred = self.or()?;
self.expect(&Tok::RParen, ") to close the list predicate")?;
return Ok(Condition::EdgeList {
quant,
var,
list,
pred: Box::new(pred),
});
}
}
let left = self.expr()?;
if self.eat_kw("IN") {
let close = if self.eat(&Tok::LParen) {
Tok::RParen
} else if self.eat(&Tok::LBracket) {
Tok::RBracket
} else {
return self.err("expected a list after IN: (v, ...) or [v, ...]");
};
let mut list = Vec::new();
if !self.eat(&close) {
loop {
list.push(self.operand()?);
if self.eat(&close) {
break;
}
self.expect(&Tok::Comma, ", or the end of the list")?;
}
}
return Ok(Condition::In { value: left, list });
}
if self.eat_kw("IS") {
let null = !self.eat_kw("NOT");
if !self.eat_kw("NULL") {
return self.err("expected NULL after IS [NOT]");
}
return Ok(Condition::IsNull { value: left, null });
}
let text = if self.eat_kw("STARTS") {
Some(TextOp::StartsWith)
} else if self.eat_kw("ENDS") {
Some(TextOp::EndsWith)
} else if self.eat_kw("CONTAINS") {
Some(TextOp::Contains)
} else {
None
};
if let Some(op) = text {
if op != TextOp::Contains && !self.eat_kw("WITH") {
return self.err("expected WITH");
}
let pattern = self.operand()?;
return Ok(Condition::Text {
value: left,
op,
pattern,
});
}
Ok(Condition::Cmp(self.comparison_from(left)?))
}
fn comparison_from(&mut self, left: Operand) -> Result<Comparison> {
let op = match self.peek() {
Tok::Eq => CmpOp::Eq,
Tok::Ne => CmpOp::Ne,
Tok::Lt => CmpOp::Lt,
Tok::Le => CmpOp::Le,
Tok::Gt => CmpOp::Gt,
Tok::Ge => CmpOp::Ge,
_ => return self.err("expected a comparison (=, <>, <, <=, >, >=)"),
};
self.bump();
let right = self.expr()?;
Ok(Comparison { left, op, right })
}
fn operand(&mut self) -> Result<Operand> {
match self.peek() {
Tok::Int(_) => Ok(Operand::Int(self.int("a value")?)),
Tok::Param(p) => {
let p = p.clone();
self.bump();
Ok(Operand::Param(p))
}
Tok::Str => {
let s = crate::lexer::string_at(self.text, self.pos())?;
self.bump();
Ok(Operand::Str(s))
}
Tok::Float => {
let x = crate::lexer::float_at(self.text, self.pos())?;
self.bump();
Ok(Operand::Float(Float(x)))
}
Tok::Minus => {
let at = self.pos();
self.bump();
match *self.peek() {
Tok::Int(n) => {
self.bump();
if n == 0 {
return Ok(Operand::Int(0));
}
0i64.checked_sub_unsigned(n)
.map(Operand::Signed)
.ok_or(GqlError::Syntax {
pos: at,
msg: "integer out of range".into(),
})
}
Tok::Float => {
let x = crate::lexer::float_at(self.text, self.pos())?;
self.bump();
Ok(Operand::Float(Float(-x)))
}
// `-x` of a value
_ => Ok(Operand::Unary(UnOp::Neg, Box::new(self.factor()?))),
}
}
_ if self.is_kw("TRUE") || self.is_kw("FALSE") => {
let b = self.is_kw("TRUE");
self.bump();
Ok(Operand::Bool(b))
}
_ if self.is_kw("NULL") => {
self.bump();
Ok(Operand::Null)
}
_ => self.reference(),
}
}
/// A value: sums joined by `||` (string concatenation, binding looser than `+ -`).
fn expr(&mut self) -> Result<Operand> {
let mut a = self.sum()?;
while self.eat(&Tok::Concat) {
let b = self.sum()?;
a = Operand::Call(Func::Concat, vec![a, b]);
}
Ok(a)
}
/// An operand, or arithmetic over operands: `* / %` before `+ -`, left to right,
/// brackets around a part.
fn sum(&mut self) -> Result<Operand> {
let mut a = self.term()?;
loop {
let op = match self.peek() {
Tok::Plus => BinOp::Add,
Tok::Minus => BinOp::Sub,
_ => return Ok(a),
};
self.bump();
let b = self.term()?;
a = Operand::Arith(Box::new(a), op, Box::new(b));
}
}
fn term(&mut self) -> Result<Operand> {
let mut a = self.factor()?;
loop {
let op = match self.peek() {
Tok::Star => BinOp::Mul,
Tok::Slash => BinOp::Div,
Tok::Percent => BinOp::Rem,
_ => return Ok(a),
};
self.bump();
let b = self.factor()?;
a = Operand::Arith(Box::new(a), op, Box::new(b));
}
}
fn factor(&mut self) -> Result<Operand> {
if self.eat(&Tok::LParen) {
let e = self.expr()?;
self.expect(&Tok::RParen, ") to close a bracket")?;
return Ok(e);
}
self.operand()
}
/// `UNWIND [v, ...] AS name` or `UNWIND $list AS name`.
fn unwind(&mut self) -> Result<Unwind> {
let list = match self.peek().clone() {
Tok::Param(p) => {
self.bump();
UnwindList::Param(p)
}
Tok::LBracket => {
self.bump();
let mut items = Vec::new();
if !self.eat(&Tok::RBracket) {
loop {
items.push(self.expr()?);
if self.eat(&Tok::RBracket) {
break;
}
self.expect(&Tok::Comma, ", or ] in the list")?;
}
}
UnwindList::Items(items)
}
Tok::Ident(_) => match self.reference()? {
Operand::Prop(v, k) => UnwindList::Prop(v, k),
_ => {
return self.err(
"UNWIND takes a list [v, ...], a $parameter or a list property n.key",
);
}
},
_ => {
return self
.err("UNWIND takes a list [v, ...], a $parameter or a list property n.key");
}
};
if !self.eat_kw("AS") {
return self.err("expected AS name after the UNWIND list");
}
let alias = self.name()?;
Ok(Unwind { list, alias })
}
/// `UNWIND e.key` of an edge variable `e` of the `MATCH` just before
/// ([`UnwindList::EdgeProp`]): its two nodes, named when they have no name, passed on by
/// the part before. Any other `UNWIND` as it is.
fn edge_unwind(&mut self, u: Unwind, before: &mut Query) -> Result<Unwind> {
let UnwindList::Prop(v, key) = &u.list else {
return Ok(u);
};
let Some((n, k)) = before.matches.iter().enumerate().find_map(|(n, m)| {
m.paths
.iter()
.enumerate()
.find_map(|(k, p)| {
p.steps
.iter()
.any(|s| s.0.var.as_deref() == Some(v.as_str()))
.then_some(k)
})
.map(|k| (n, k))
}) else {
return Ok(u);
};
let (v, key) = (v.clone(), key.clone());
let path = &mut before.matches[n].paths[k];
let i = path
.steps
.iter()
.position(|s| s.0.var.as_deref() == Some(v.as_str()))
.expect("found");
let edge = path.steps[i].0.clone();
if edge.quant.is_some() {
return self.err(format!(
"UNWIND {v}.{key}: `{v}` is a quantified edge (a list per edge of a path)"
));
}
// its nodes, named
let mut names = Vec::with_capacity(2);
for at in [i, i + 1] {
let node = if at == 0 {
&mut path.start
} else {
&mut path.steps[at - 1].1
};
let name = match &node.var {
Some(name) => name.clone(),
None => {
self.anon += 1;
let name = format!("#{}", self.anon);
node.var = Some(name.clone());
name
}
};
if !before.ret.items.iter().any(|it| it.name() == name) {
before.ret.items.push(var_item(&name));
}
names.push(name);
}
let [before_node, after_node]: [String; 2] = names.try_into().expect("two");
// and its row
let row = format!("#row({v})");
if !before.ret.items.iter().any(|it| it.name() == row) {
before.ret.items.push(ReturnItem {
value: ReturnValue::Value(Operand::EdgeRow(v.clone())),
alias: Some(row.clone()),
});
}
let (from, to) = match edge.dir {
Dir::Out => (before_node, after_node),
Dir::In => (after_node, before_node),
Dir::Any => {
return self.err(format!(
"UNWIND {v}.{key}: `{v}` goes either way; give it a direction"
));
}
};
Ok(Unwind {
list: UnwindList::EdgeProp {
edge: v,
from,
to,
labels: edge.labels,
row,
key,
},
alias: u.alias,
})
}
/// `var`, `var.key`, `id(var)`, `length(var)` or `hex(var.key)`.
fn reference(&mut self) -> Result<Operand> {
if let Tok::Ident(f) = self.peek()
&& self.toks[self.at + 1].kind == Tok::LParen
{
let f = f.to_ascii_lowercase();
let bin = match f.as_str() {
"bitand" => Some(BinOp::And),
"bitor" => Some(BinOp::Or),
"bitxor" => Some(BinOp::Xor),
"shiftleft" => Some(BinOp::Shl),
"shiftright" => Some(BinOp::Shr),
_ => None,
};
if let Some(op) = bin {
self.bump();
self.bump();
let a = self.expr()?;
self.expect(&Tok::Comma, &format!(", between the two arguments of {f}"))?;
let b = self.expr()?;
self.expect(&Tok::RParen, &format!(") after the arguments of {f}"))?;
return Ok(Operand::Arith(Box::new(a), op, Box::new(b)));
}
let string = match f.as_str() {
"char_length" | "character_length" => Some((Func::Len, 1, 1)),
"substring" => Some((Func::Substr, 2, 3)),
_ => None,
};
if let Some((func, lo, hi)) = string {
self.bump();
self.bump();
let mut args = vec![self.expr()?];
while self.eat(&Tok::Comma) {
args.push(self.expr()?);
}
self.expect(&Tok::RParen, &format!(") after the arguments of {f}"))?;
if args.len() < lo || args.len() > hi {
return self.err(format!(
"{f} takes {}, not {}",
if lo == hi {
"1 argument".to_string()
} else {
format!("{lo} or {hi} arguments")
},
args.len()
));
}
return Ok(Operand::Call(func, args));
}
if f == "bitnot" {
self.bump();
self.bump();
let a = self.expr()?;
self.expect(&Tok::RParen, ") after the argument of bitnot")?;
return Ok(Operand::Unary(UnOp::Not, Box::new(a)));
}
if f == "hex" {
// `hex(v.key)`: property `key` as the hex of its bytes (relation `L.key@hex`)
self.bump();
self.bump();
let v = self.name()?;
self.expect(&Tok::Dot, ". after the variable in hex(...)")?;
let k = self.symbol()?;
self.expect(&Tok::RParen, ") after the property")?;
return Ok(Operand::Prop(v, format!("{k}@hex")));
}
if f == "length" || f == "id" {
self.bump();
self.bump();
let v = self.name()?;
self.expect(&Tok::RParen, ") after the variable")?;
return Ok(if f == "length" {
Operand::Length(v)
} else {
Operand::Id(v)
});
}
}
let v = self.name()?;
if self.eat(&Tok::Dot) {
let k = self.symbol()?;
return Ok(Operand::Prop(v, k));
}
Ok(Operand::Var(v))
}
/// `var`, `var.key`, or an aggregate: `count(*)`, `f([DISTINCT] var[.key])`.
fn return_value(&mut self) -> Result<ReturnValue> {
let func = match self.peek() {
Tok::Ident(s) if self.toks[self.at + 1].kind == Tok::LParen => {
match s.to_ascii_lowercase().as_str() {
"count" => AggFn::Count,
"min" => AggFn::Min,
"max" => AggFn::Max,
"sum" => AggFn::Sum,
"avg" => AggFn::Avg,
"shortestpath" | "allshortestpaths" => {
return Ok(ReturnValue::Path(Box::new(self.path()?)));
}
"id" | "hex" => return Ok(ReturnValue::Value(self.reference()?)),
"bitand" | "bitor" | "bitxor" | "bitnot" | "shiftleft" | "shiftright"
| "char_length" | "character_length" | "substring" => {
return Ok(ReturnValue::Value(self.expr()?));
}
"rank" => return self.rank(),
f @ ("labels" | "type" | "properties" | "relationships") => {
let f = match f {
"labels" => WholeFn::Labels,
"type" => WholeFn::Type,
"properties" => WholeFn::Properties,
_ => WholeFn::Relationships,
};
self.bump();
self.bump();
let x = self.name()?;
self.expect(&Tok::RParen, ") after the variable")?;
return Ok(ReturnValue::Whole(f, x));
}
f @ ("length" | "nodes") => {
let f = f.to_string();
self.bump();
self.bump();
let p = self.name()?;
self.expect(&Tok::RParen, ") after the path variable")?;
return Ok(if f == "length" {
ReturnValue::Length(p)
} else {
ReturnValue::Nodes(p)
});
}
other => return self.err(format!("no function `{other}` here")),
}
}
_ => return Ok(ReturnValue::Value(self.expr()?)),
};
self.bump();
self.bump();
if func == AggFn::Count && self.eat(&Tok::Star) {
self.expect(&Tok::RParen, ") after count(*")?;
return Ok(ReturnValue::Aggregate {
func,
distinct: false,
arg: None,
});
}
let distinct = self.eat_kw("DISTINCT");
let arg = self.reference()?;
self.expect(&Tok::RParen, ") to close the aggregate")?;
Ok(ReturnValue::Aggregate {
func,
distinct,
arg: Some(arg),
})
}
/// `rank(x [BY g, ..])`.
fn rank(&mut self) -> Result<ReturnValue> {
self.bump();
self.bump();
let arg = self.reference()?;
let mut by = Vec::new();
if self.eat_kw("BY") {
loop {
by.push(self.reference()?);
if !self.eat(&Tok::Comma) {
break;
}
}
}
self.expect(&Tok::RParen, ") to close rank(")?;
Ok(ReturnValue::Rank { arg, by })
}
fn ret(&mut self) -> Result<Return> {
let distinct = self.eat_kw("DISTINCT");
let mut items = Vec::new();
loop {
let value = self.return_value()?;
let alias = if self.eat_kw("AS") {
Some(self.name()?)
} else {
None
};
items.push(ReturnItem { value, alias });
if !self.eat(&Tok::Comma) {
break;
}
}
let mut order = Vec::new();
if self.eat_kw("ORDER") {
if !self.eat_kw("BY") {
return self.err("expected BY after ORDER");
}
loop {
let value = self.reference()?;
let descending = if self.eat_kw("DESC") || self.eat_kw("DESCENDING") {
true
} else {
let _ = self.eat_kw("ASC") || self.eat_kw("ASCENDING");
false
};
order.push(OrderKey { value, descending });
if !self.eat(&Tok::Comma) {
break;
}
}
}
let offset = if self.eat_kw("OFFSET") || self.eat_kw("SKIP") {
Some(self.int("a row count after OFFSET")?)
} else {
None
};
let limit = if self.eat_kw("LIMIT") {
Some(self.int("a row count after LIMIT")?)
} else {
None
};
Ok(Return {
distinct,
items,
order,
offset,
limit,
})
}
}
/// Without DISTINCT or an aggregate, the nodes a WITH (`ret`) leaves out go on as hidden
/// columns (`#name`), so each match stays a row of its own.
fn hide(matches: &[Match], prior: Option<&Query>, ret: &mut Return) {
let grouped = ret
.items
.iter()
.any(|it| matches!(it.value, ReturnValue::Aggregate { .. }));
if !ret.distinct && !grouped {
let mut hidden: Vec<(String, String)> = Vec::new();
for p in matches.iter().flat_map(|m| &m.paths) {
for n in std::iter::once(&p.start).chain(p.steps.iter().map(|s| &s.1)) {
if let Some(v) = &n.var {
let h = if v.starts_with('#') {
v.clone()
} else {
format!("#{v}")
};
hidden.push((v.clone(), h));
}
}
}
if let Some(pq) = prior {
for it in &pq.ret.items {
if let Some(a) = it.alias.as_ref().filter(|a| a.starts_with('#')) {
hidden.push((a.clone(), a.clone()));
}
}
}
for (v, h) in hidden {
let shown = ret.items.iter().any(|it| {
it.name() == h
|| (it.alias.is_none()
&& it.value == ReturnValue::Value(Operand::Var(v.clone())))
});
if !shown {
ret.items.push(ReturnItem {
value: ReturnValue::Value(Operand::Var(v)),
alias: Some(h),
});
}
}
}
}
/// A path through a WITH is its length (its nodes stay behind).
fn lengths(matches: &[Match], ret: &mut Return) {
let paths: Vec<String> = matches
.iter()
.flat_map(|m| &m.paths)
.filter_map(|p| p.var.clone())
.collect();
for it in &mut ret.items {
if let ReturnValue::Value(Operand::Var(v)) = &it.value
&& paths.contains(v)
{
let v = v.clone();
it.alias.get_or_insert(v.clone());
it.value = ReturnValue::Length(v);
}
}
}
/// The names a part binds: its named nodes and paths, then those its prior passes on.
fn scope(matches: &[Match], prior: Option<&Query>) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut add = |v: &str| {
if !names.iter().any(|n| n == v) {
names.push(v.to_string());
}
};
if let Some(pq) = prior {
for it in &pq.ret.items {
add(&it.name());
}
}
for p in matches.iter().flat_map(|m| &m.paths) {
for n in std::iter::once(&p.start).chain(p.steps.iter().map(|s| &s.1)) {
if let Some(v) = &n.var {
add(v);
}
}
if let Some(v) = &p.var {
add(v);
}
}
names
}
/// A plain variable as a returned item.
fn var_item(v: &str) -> ReturnItem {
ReturnItem {
value: ReturnValue::Value(Operand::Var(v.to_string())),
alias: None,
}
}