Skip to main content

core_query/cypher/
parser.rs

1//! Recursive-descent parser for the Cypher subset. Never panics on any token sequence.
2
3use super::ast::{
4    AggArg, AggFunc, ArithOp, CreateEdge, CreateNode, CreateStmt, EdgeDelete, Expr, HopRange,
5    LimitSkip, MatchDeleteNodeStmt, MatchDeleteStmt, MatchSetStmt, MergeStmt, NodePat, Operand,
6    OptionalClause, OrderItem, OrderTarget, Pattern, Query, RelDir, RelPat, RetItem, RetVal,
7    SetClause, UnwindClause, UnwindExpr, WithStage, WriteStatement,
8};
9use super::Tok;
10use crate::filter::CmpOp;
11use core_storage::Value;
12
13/// Max parenthesized-expression nesting. Deeper input is `Err`, not a stack overflow.
14const MAX_PAREN_DEPTH: usize = 64;
15
16/// Parse a tokenized Cypher subset query. Every failure is `Err(String)`; this
17/// function never panics on a well-formed `&[Tok]` (including empty / garbage).
18pub fn parse(tokens: &[Tok]) -> Result<Query, String> {
19    let mut p = Parser {
20        toks: tokens,
21        pos: 0,
22    };
23    let q = p.query()?;
24    if p.pos < p.toks.len() {
25        // A single-query parse: a trailing `UNION` (or anything else) is an
26        // error here. Use `parse_read` to accept a `UNION` chain.
27        return Err(p.unsupported_or_unexpected("unexpected tokens after query"));
28    }
29    Ok(q)
30}
31
32/// A read query that may be a single query or a `UNION` / `UNION ALL` chain.
33/// `all_flags[i]` is `true` when the boundary before `parts[i + 1]` was
34/// `UNION ALL` (bag union); `false` for `UNION` (distinct). Length is
35/// `parts.len() - 1`.
36#[derive(Debug, Clone, PartialEq)]
37pub struct UnionQuery {
38    pub parts: Vec<Query>,
39    pub all_flags: Vec<bool>,
40}
41
42/// Parse a read query, accepting a `UNION` / `UNION ALL` chain.
43pub fn parse_read(tokens: &[Tok]) -> Result<UnionQuery, String> {
44    let mut p = Parser {
45        toks: tokens,
46        pos: 0,
47    };
48    let mut parts = vec![p.query()?];
49    let mut all_flags = Vec::new();
50    while p.peek_is_union() {
51        p.pos += 1; // consume UNION
52        let all = matches!(p.peek(), Some(Tok::Ident(s)) if s.eq_ignore_ascii_case("all"));
53        if all {
54            p.pos += 1; // consume ALL
55        }
56        all_flags.push(all);
57        parts.push(p.query()?);
58    }
59    if p.pos < p.toks.len() {
60        return Err(p.err("unexpected tokens after UNION query"));
61    }
62    Ok(UnionQuery { parts, all_flags })
63}
64
65/// Parse a tokenized write statement (CREATE / MATCH…SET / MATCH…DELETE / MERGE).
66/// Returns `Err` for read queries or malformed write statements.
67pub fn parse_write(tokens: &[Tok]) -> Result<WriteStatement, String> {
68    let mut p = Parser {
69        toks: tokens,
70        pos: 0,
71    };
72    p.write_statement()
73}
74
75/// Return true if the token stream starts with a write keyword, or is a MATCH
76/// statement followed by SET or DELETE.  Used for fast server-side dispatch
77/// without a full parse.
78pub fn is_write_tokens(tokens: &[Tok]) -> bool {
79    match tokens.first() {
80        Some(Tok::Create) | Some(Tok::Merge) => true,
81        Some(Tok::Match) => tokens.iter().any(|t| matches!(t, Tok::Set | Tok::Delete)),
82        _ => false,
83    }
84}
85
86struct Parser<'a> {
87    toks: &'a [Tok],
88    pos: usize,
89}
90
91impl<'a> Parser<'a> {
92    fn peek(&self) -> Option<&'a Tok> {
93        self.toks.get(self.pos)
94    }
95
96    fn eat(&mut self, want: &Tok) -> bool {
97        if self.peek() == Some(want) {
98            self.pos += 1;
99            true
100        } else {
101            false
102        }
103    }
104
105    fn err(&self, msg: &str) -> String {
106        match self.peek() {
107            Some(tok) => format!("parse error at token {}: {msg} (found {tok:?})", self.pos),
108            None => format!(
109                "parse error at token {}: {msg} (found end of input)",
110                self.pos
111            ),
112        }
113    }
114
115    fn expect(&mut self, want: &Tok, what: &str) -> Result<(), String> {
116        if self.eat(want) {
117            Ok(())
118        } else {
119            Err(self.err(what))
120        }
121    }
122
123    fn ident(&mut self, what: &str) -> Result<String, String> {
124        match self.peek() {
125            Some(Tok::Ident(s)) => {
126                let s = s.clone();
127                self.pos += 1;
128                Ok(s)
129            }
130            _ => Err(self.err(what)),
131        }
132    }
133
134    fn query(&mut self) -> Result<Query, String> {
135        let mut matches = Vec::new();
136        while self.peek() == Some(&Tok::Match) {
137            matches.extend(self.match_clause()?);
138        }
139        if matches.is_empty() {
140            return Err(self.err("expected MATCH"));
141        }
142        // Optional WHERE clause that follows the required MATCH(es) — may come
143        // before or after OPTIONAL MATCH.  In standard Cypher, WHERE applies to
144        // the preceding MATCH, so `MATCH (a) WHERE … OPTIONAL MATCH … RETURN`
145        // is legal.  Parse it here, then parse OPTIONAL MATCHes, then check
146        // again in case WHERE follows the OPTIONAL MATCHes instead.
147        let where_expr_pre = if self.eat(&Tok::Where) {
148            Some(self.expr(0)?)
149        } else {
150            None
151        };
152        // Optional MATCH clauses (zero or more, after required MATCHes + WHERE).
153        let mut optional_clauses = Vec::new();
154        while self.peek() == Some(&Tok::Optional) {
155            optional_clauses.push(self.optional_match_clause()?);
156        }
157        // WHERE may also appear *after* OPTIONAL MATCHes (if not already seen).
158        let where_expr = if where_expr_pre.is_some() {
159            where_expr_pre
160        } else if self.eat(&Tok::Where) {
161            Some(self.expr(0)?)
162        } else {
163            None
164        };
165        // Optional top-level UNWIND clauses (after WHERE, before WITH).
166        let mut unwinds = Vec::new();
167        while self.peek() == Some(&Tok::Unwind) {
168            unwinds.push(self.unwind_clause()?);
169        }
170        // Optional WHERE that follows UNWIND (references UNWIND aliases).
171        let post_unwind_where = if !unwinds.is_empty() && self.eat(&Tok::Where) {
172            Some(self.expr(0)?)
173        } else {
174            None
175        };
176        // WITH pipeline stages (zero or more).
177        let mut stages = Vec::new();
178        while self.peek() == Some(&Tok::With) {
179            stages.push(self.with_stage()?);
180        }
181        let (distinct, returns) = self.return_clause()?;
182        let aliases: Vec<&str> = returns.iter().filter_map(|r| r.alias.as_deref()).collect();
183        let order_by = if self.peek() == Some(&Tok::Order) {
184            self.order_clause(&aliases)?
185        } else {
186            Vec::new()
187        };
188        let skip = if self.eat(&Tok::Skip) {
189            Some(self.uint("SKIP")?)
190        } else {
191            None
192        };
193        let limit = if self.eat(&Tok::Limit) {
194            Some(self.uint("LIMIT")?)
195        } else {
196            None
197        };
198        // NOTE: the leftover-token check lives in `parse` / `parse_read`, not
199        // here, so `query()` can stop cleanly at a `UNION` boundary.
200        Ok(Query {
201            matches,
202            optional_clauses,
203            where_expr,
204            unwinds,
205            post_unwind_where,
206            stages,
207            returns,
208            distinct,
209            order_by,
210            skip,
211            limit,
212        })
213    }
214
215    /// True if the next token is the `UNION` keyword (an ordinary identifier).
216    fn peek_is_union(&self) -> bool {
217        matches!(self.peek(), Some(Tok::Ident(s)) if s.eq_ignore_ascii_case("union"))
218    }
219
220    /// Named errors for still-unsupported Cypher forms (`UNION`, `CASE`).
221    fn unsupported_or_unexpected(&self, msg: &str) -> String {
222        match self.peek() {
223            Some(Tok::Ident(s)) if s.eq_ignore_ascii_case("union") => {
224                "UNION is not supported".to_string()
225            }
226            Some(Tok::Ident(s)) if s.eq_ignore_ascii_case("case") => {
227                "CASE is not supported".to_string()
228            }
229            _ => self.err(msg),
230        }
231    }
232
233    /// Consume an identifier keyword (case-insensitive). Keywords that are
234    /// not lexer tokens (`IN`, `DISTINCT`, `ON`) stay `Ident` so they can
235    /// still be used as variable names in other positions.
236    fn eat_ident_kw(&mut self, kw: &str) -> bool {
237        if let Some(Tok::Ident(s)) = self.peek() {
238            if s.eq_ignore_ascii_case(kw) {
239                self.pos += 1;
240                return true;
241            }
242        }
243        false
244    }
245
246    /// Parse one `OPTIONAL MATCH pattern [WHERE expr]` clause.
247    ///
248    /// Standard openCypher allows exactly one MATCH per OPTIONAL MATCH.
249    fn optional_match_clause(&mut self) -> Result<OptionalClause, String> {
250        self.expect(&Tok::Optional, "expected OPTIONAL")?;
251        self.expect(&Tok::Match, "expected MATCH after OPTIONAL")?;
252        let patterns = vec![self.pattern()?];
253        // Optional WHERE inside the optional scope.
254        let where_expr = if self.eat(&Tok::Where) {
255            Some(self.expr(0)?)
256        } else {
257            None
258        };
259        Ok(OptionalClause {
260            patterns,
261            where_expr,
262        })
263    }
264
265    /// Parse one `WITH <items> [WHERE] [ORDER BY] [SKIP] [LIMIT] [MATCH]* [UNWIND]* [WHERE]`
266    /// stage and return a `WithStage`.
267    fn with_stage(&mut self) -> Result<WithStage, String> {
268        self.expect(&Tok::With, "expected WITH")?;
269        let mut items = vec![self.ret_item()?];
270        while self.eat(&Tok::Comma) {
271            items.push(self.ret_item()?);
272        }
273        // Optional WHERE / HAVING immediately after WITH items.
274        let where_expr = if self.eat(&Tok::Where) {
275            Some(self.expr(0)?)
276        } else {
277            None
278        };
279        // Optional ORDER BY inside WITH.
280        let aliases: Vec<&str> = items.iter().filter_map(|r| r.alias.as_deref()).collect();
281        let order_by = if self.peek() == Some(&Tok::Order) {
282            self.order_clause(&aliases)?
283        } else {
284            Vec::new()
285        };
286        let skip = if self.eat(&Tok::Skip) {
287            Some(self.uint("SKIP")?)
288        } else {
289            None
290        };
291        let limit = if self.eat(&Tok::Limit) {
292            Some(self.uint("LIMIT")?)
293        } else {
294            None
295        };
296        // Optional MATCH clauses that follow this WITH.
297        let mut matches = Vec::new();
298        while self.peek() == Some(&Tok::Match) {
299            matches.extend(self.match_clause()?);
300        }
301        // Optional OPTIONAL MATCH clauses that follow those MATCHes.
302        let mut optional_clauses = Vec::new();
303        while self.peek() == Some(&Tok::Optional) {
304            optional_clauses.push(self.optional_match_clause()?);
305        }
306        // Optional UNWIND clauses that follow those MATCHes.
307        let mut stage_unwinds = Vec::new();
308        while self.peek() == Some(&Tok::Unwind) {
309            stage_unwinds.push(self.unwind_clause()?);
310        }
311        // Optional WHERE that follows those MATCHes / UNWINDs.
312        let post_where = if self.peek() == Some(&Tok::Where)
313            && (!matches.is_empty() || !optional_clauses.is_empty() || !stage_unwinds.is_empty())
314        {
315            self.pos += 1; // consume WHERE
316            Some(self.expr(0)?)
317        } else {
318            None
319        };
320        Ok(WithStage {
321            items,
322            where_expr,
323            order_by,
324            skip,
325            limit,
326            matches,
327            optional_clauses,
328            unwinds: stage_unwinds,
329            post_where,
330        })
331    }
332
333    /// Parse `UNWIND <expr> AS <alias>`.
334    fn unwind_clause(&mut self) -> Result<UnwindClause, String> {
335        self.expect(&Tok::Unwind, "expected UNWIND")?;
336        let list = self.unwind_expr()?;
337        self.expect(&Tok::As, "expected AS after UNWIND expression")?;
338        let alias = self.ident("expected alias identifier after AS")?;
339        Ok(UnwindClause { list, alias })
340    }
341
342    /// Parse the list expression in an UNWIND clause:
343    /// - `[v1, v2, …]` — literal list.
344    /// - `var.field`   — property reference.
345    /// - `var`         — bare variable (alias from a prior WITH).
346    fn unwind_expr(&mut self) -> Result<UnwindExpr, String> {
347        match self.peek() {
348            Some(Tok::LBracket) => {
349                self.pos += 1; // consume '['
350                let mut vals = Vec::new();
351                if !self.eat(&Tok::RBracket) {
352                    loop {
353                        vals.push(self.literal_value("UNWIND list element")?);
354                        if self.eat(&Tok::Comma) {
355                            continue;
356                        }
357                        self.expect(&Tok::RBracket, "expected ']' to close UNWIND list")?;
358                        break;
359                    }
360                }
361                Ok(UnwindExpr::Lit(vals))
362            }
363            Some(Tok::Ident(_)) => {
364                let name = self.ident("expected variable or property in UNWIND")?;
365                if self.eat(&Tok::Dot) {
366                    let field = self.ident("expected field name after '.' in UNWIND")?;
367                    Ok(UnwindExpr::Prop { var: name, field })
368                } else {
369                    Ok(UnwindExpr::Var(name))
370                }
371            }
372            _ => Err(self.err("expected list literal, property, or variable in UNWIND")),
373        }
374    }
375
376    /// Parse one `MATCH p1 [, p2, …]` clause.
377    ///
378    /// Comma-separated patterns in a single MATCH are the openCypher way to
379    /// write an intersection — `MATCH (t)-[:A]->(c), (t)-[:B]->(c)` binds the
380    /// *same* `t` and `c` across both patterns — and every multihop question
381    /// an assistant asks is that shape. The returned patterns are appended to
382    /// the same `Vec<Pattern>` a run of separate MATCH clauses produces, so
383    /// the two spellings plan and execute identically.
384    fn match_clause(&mut self) -> Result<Vec<Pattern>, String> {
385        self.expect(&Tok::Match, "expected MATCH")?;
386        let mut out = vec![self.match_pattern()?];
387        while self.eat(&Tok::Comma) {
388            out.push(self.match_pattern()?);
389        }
390        Ok(out)
391    }
392
393    /// One pattern inside a MATCH clause: `shortestPath(…)` or a plain chain.
394    fn match_pattern(&mut self) -> Result<Pattern, String> {
395        // Detect `shortestPath(...)`.
396        if let Some(Tok::Ident(s)) = self.peek() {
397            if s.eq_ignore_ascii_case("shortestpath") {
398                return self.shortest_path_clause();
399            }
400        }
401        self.pattern()
402    }
403
404    fn shortest_path_clause(&mut self) -> Result<Pattern, String> {
405        self.pos += 1; // consume "shortestPath" identifier
406        self.expect(&Tok::LParen, "expected '(' after shortestPath")?;
407        let start = self.node()?;
408        let rel = self.rel()?;
409        if rel.hops.is_none() {
410            return Err(
411                self.err("shortestPath requires a variable-length relationship (e.g. [*..5])")
412            );
413        }
414        let dest = self.node()?;
415        self.expect(&Tok::RParen, "expected ')' to close shortestPath")?;
416        Ok(Pattern {
417            start,
418            chain: vec![(rel, dest)],
419            shortest: true,
420        })
421    }
422
423    fn pattern(&mut self) -> Result<Pattern, String> {
424        let start = self.node()?;
425        let mut chain = Vec::new();
426        while matches!(self.peek(), Some(Tok::Dash) | Some(Tok::Lt)) {
427            let rel = self.rel()?;
428            let dest = self.node()?;
429            chain.push((rel, dest));
430        }
431        Ok(Pattern {
432            start,
433            chain,
434            shortest: false,
435        })
436    }
437
438    fn node(&mut self) -> Result<NodePat, String> {
439        self.expect(&Tok::LParen, "expected '(' to start a node pattern")?;
440        let var = match self.peek() {
441            Some(Tok::Ident(s)) => {
442                let s = s.clone();
443                self.pos += 1;
444                Some(s)
445            }
446            _ => None,
447        };
448        let label = if self.eat(&Tok::Colon) {
449            Some(self.ident("expected label identifier after ':'")?)
450        } else {
451            None
452        };
453        let props = if self.peek() == Some(&Tok::LBrace) {
454            self.props()?
455        } else {
456            Vec::new()
457        };
458        self.expect(&Tok::RParen, "expected ')' to close a node pattern")?;
459        Ok(NodePat { var, label, props })
460    }
461
462    fn props(&mut self) -> Result<Vec<(String, Operand)>, String> {
463        self.expect(&Tok::LBrace, "expected '{'")?;
464        let mut out = Vec::new();
465        loop {
466            let key = self.ident("expected property key")?;
467            self.expect(&Tok::Colon, "expected ':' after property key")?;
468            let val = self.operand()?;
469            out.push((key, val));
470            if self.eat(&Tok::Comma) {
471                continue;
472            }
473            break;
474        }
475        self.expect(&Tok::RBrace, "expected '}' to close property map")?;
476        Ok(out)
477    }
478
479    fn rel(&mut self) -> Result<RelPat, String> {
480        if self.eat(&Tok::Lt) {
481            self.expect(
482                &Tok::Dash,
483                "expected '-' after '<' in a left-directed relationship",
484            )?;
485            let (var, etypes, hops) = self.rel_body()?;
486            self.expect(
487                &Tok::Dash,
488                "expected '-' to close a left-directed relationship",
489            )?;
490            return Ok(RelPat {
491                var,
492                etypes,
493                dir: RelDir::Left,
494                hops,
495            });
496        }
497        self.expect(&Tok::Dash, "expected '-' to start a relationship")?;
498        let (var, etypes, hops) = self.rel_body()?;
499        self.expect(&Tok::Dash, "expected '-' after ']'")?;
500        let dir = if self.eat(&Tok::Gt) {
501            RelDir::Right
502        } else {
503            RelDir::Undirected
504        };
505        Ok(RelPat {
506            var,
507            etypes,
508            dir,
509            hops,
510        })
511    }
512
513    #[allow(clippy::type_complexity)]
514    fn rel_body(&mut self) -> Result<(Option<String>, Vec<String>, Option<HopRange>), String> {
515        self.expect(&Tok::LBracket, "expected '[' in a relationship pattern")?;
516        let var = match self.peek() {
517            Some(Tok::Ident(s)) => {
518                let s = s.clone();
519                self.pos += 1;
520                Some(s)
521            }
522            _ => None,
523        };
524        // `:A`, or `:A|:B|:C` alternation. Empty = any type.
525        let mut etypes = Vec::new();
526        if self.eat(&Tok::Colon) {
527            etypes.push(self.ident("expected relationship type identifier after ':'")?);
528            while self.eat(&Tok::Pipe) {
529                // Both `|:B` (openCypher) and the lenient `|B` are accepted.
530                self.eat(&Tok::Colon);
531                etypes.push(self.ident("expected relationship type identifier after '|'")?);
532            }
533        }
534        let hops = if self.eat(&Tok::Star) {
535            Some(self.parse_hop_range()?)
536        } else {
537            None
538        };
539        self.expect(
540            &Tok::RBracket,
541            "expected ']' to close a relationship pattern",
542        )?;
543        Ok((var, etypes, hops))
544    }
545
546    /// Parse the hop-count range that follows `*` inside a relationship bracket.
547    ///
548    /// Recognised forms (after `*` is already consumed):
549    /// - `]`        → bare `*`, treated as `1..10`
550    /// - `n`        → exactly n hops (`n..n`)
551    /// - `n..m`     → n..m hops
552    /// - `..m`      → 1..m hops
553    /// - `n..`      → unbounded → hard-cap error
554    ///
555    /// Hard cap: max > 10 or unbounded → Err("variable-length paths are capped at 10 hops").
556    fn parse_hop_range(&mut self) -> Result<HopRange, String> {
557        const CAP_ERR: &str = "variable-length paths are capped at 10 hops";
558
559        match self.peek() {
560            // bare `*`  →  min=1, max=10
561            Some(Tok::RBracket) => Ok(HopRange { min: 1, max: 10 }),
562
563            // `*n`  or  `*n..`  or  `*n..m`
564            Some(Tok::Int(n)) => {
565                let n = *n;
566                self.pos += 1;
567                if self.eat(&Tok::Dot) {
568                    self.expect(&Tok::Dot, "expected '..' separator in hop range")?;
569                    match self.peek() {
570                        Some(Tok::Int(m)) => {
571                            let m = *m;
572                            self.pos += 1;
573                            // `*n..m`
574                            self.validate_hop_range(n, m, CAP_ERR)
575                        }
576                        _ => {
577                            // `*n..` — unbounded
578                            Err(CAP_ERR.to_string())
579                        }
580                    }
581                } else {
582                    // `*n` — exact hops
583                    self.validate_hop_range(n, n, CAP_ERR)
584                }
585            }
586
587            // `*..m`
588            Some(Tok::Dot) => {
589                self.pos += 1; // consume first '.'
590                self.expect(&Tok::Dot, "expected '..' range separator after '*'")?;
591                match self.peek() {
592                    Some(Tok::Int(m)) => {
593                        let m = *m;
594                        self.pos += 1;
595                        self.validate_hop_range(1, m, CAP_ERR)
596                    }
597                    _ => Err(self.err("expected max-hop integer after '*..'")),
598                }
599            }
600
601            // Anything else after `*` — treat as bare `*`
602            _ => Ok(HopRange { min: 1, max: 10 }),
603        }
604    }
605
606    fn validate_hop_range(
607        &self,
608        min_n: i64,
609        max_n: i64,
610        cap_err: &str,
611    ) -> Result<HopRange, String> {
612        if min_n < 0 || max_n < 0 {
613            return Err(self.err("hop counts must be non-negative"));
614        }
615        if min_n == 0 {
616            return Err(self.err(
617                "zero-length variable-length paths are not supported; minimum hop count is 1",
618            ));
619        }
620        if max_n > 10 {
621            return Err(cap_err.to_string());
622        }
623        let min = min_n as u8;
624        let max = max_n as u8;
625        if min > max {
626            return Err(self.err(&format!(
627                "variable-length path min ({min}) must not exceed max ({max})"
628            )));
629        }
630        Ok(HopRange { min, max })
631    }
632
633    fn expr(&mut self, paren_depth: usize) -> Result<Expr, String> {
634        let mut left = self.term(paren_depth)?;
635        while self.eat(&Tok::Or) {
636            let right = self.term(paren_depth)?;
637            left = Expr::Or(Box::new(left), Box::new(right));
638        }
639        Ok(left)
640    }
641
642    fn term(&mut self, paren_depth: usize) -> Result<Expr, String> {
643        let mut left = self.factor(paren_depth)?;
644        while self.eat(&Tok::And) {
645            let right = self.factor(paren_depth)?;
646            left = Expr::And(Box::new(left), Box::new(right));
647        }
648        Ok(left)
649    }
650
651    fn factor(&mut self, paren_depth: usize) -> Result<Expr, String> {
652        let negated = self.eat(&Tok::Not);
653        let inner = if self.eat(&Tok::LParen) {
654            if paren_depth >= MAX_PAREN_DEPTH {
655                return Err(self.err("expression nesting too deep"));
656            }
657            let e = self.expr(paren_depth + 1)?;
658            self.expect(
659                &Tok::RParen,
660                "expected ')' to close parenthesized expression",
661            )?;
662            e
663        } else {
664            self.cmp()?
665        };
666        if negated {
667            Ok(Expr::Not(Box::new(inner)))
668        } else {
669            Ok(inner)
670        }
671    }
672
673    fn cmp(&mut self) -> Result<Expr, String> {
674        let lhs = self.arith_expr()?;
675        // Check for IS NULL / IS NOT NULL postfix.
676        if let Some(Tok::Ident(s)) = self.peek() {
677            if s.eq_ignore_ascii_case("is") {
678                self.pos += 1; // consume "IS"
679                               // Optional NOT.
680                let negated = self.eat(&Tok::Not);
681                // Expect NULL identifier.
682                match self.peek() {
683                    Some(Tok::Ident(n)) if n.eq_ignore_ascii_case("null") => {
684                        self.pos += 1; // consume "NULL"
685                        return Ok(if negated {
686                            Expr::IsNotNull(lhs)
687                        } else {
688                            Expr::IsNull(lhs)
689                        });
690                    }
691                    _ => {
692                        return Err(self.err(if negated {
693                            "expected NULL after IS NOT"
694                        } else {
695                            "expected NULL after IS"
696                        }));
697                    }
698                }
699            }
700        }
701        // `IN [a, b, $p]` or `IN $list`.
702        if self.eat_ident_kw("in") {
703            let list = self.in_list()?;
704            return Ok(Expr::In { expr: lhs, list });
705        }
706        // Infix string predicates: `STARTS WITH`, `ENDS WITH`, `CONTAINS`.
707        // These desugar to the scalar functions of the same name that the
708        // executor already implements, so null- and non-string handling is
709        // shared with the `startsWith(a, b)` call spelling. Only the infix
710        // form is what an assistant writes, and it used to be a parse error.
711        if let Some(name) = self.eat_infix_string_op()? {
712            let rhs = self.arith_expr()?;
713            return Ok(Expr::Truthy(Operand::FuncCall {
714                name: name.to_string(),
715                args: vec![lhs, rhs],
716            }));
717        }
718        // If no comparison operator follows, treat the operand as a standalone
719        // boolean predicate (Expr::Truthy).  This enables:
720        //   WHERE textMatches(n.bio, 'query')
721        // without requiring an explicit `= true` or similar.
722        match self.cmp_op() {
723            Ok(op) => {
724                let rhs = self.arith_expr()?;
725                Ok(Expr::Cmp { lhs, op, rhs })
726            }
727            Err(_) => Ok(Expr::Truthy(lhs)),
728        }
729    }
730
731    /// Consume `STARTS WITH` / `ENDS WITH` / `CONTAINS` if one follows, and
732    /// return the scalar function it desugars to.
733    ///
734    /// `STARTS` and `ENDS` are ordinary identifiers to the lexer, so a bare
735    /// `STARTS` not followed by `WITH` is a named error rather than a silent
736    /// reinterpretation of the token as a variable.
737    fn eat_infix_string_op(&mut self) -> Result<Option<&'static str>, String> {
738        let Some(Tok::Ident(s)) = self.peek() else {
739            return Ok(None);
740        };
741        let word = s.to_ascii_lowercase();
742        match word.as_str() {
743            "contains" => {
744                self.pos += 1;
745                Ok(Some("contains"))
746            }
747            "starts" | "ends" => {
748                self.pos += 1;
749                // `WITH` is a lexer keyword token here, not an identifier.
750                if !self.eat(&Tok::With) {
751                    let kw = if word == "starts" { "STARTS" } else { "ENDS" };
752                    return Err(self.err(&format!("expected WITH after {kw}")));
753                }
754                Ok(Some(if word == "starts" {
755                    "startsWith"
756                } else {
757                    "endsWith"
758                }))
759            }
760            _ => Ok(None),
761        }
762    }
763
764    /// Parse the list operand of `IN`: `[a, b, $p]` or a single operand (`$cities`).
765    fn in_list(&mut self) -> Result<Vec<Operand>, String> {
766        if self.eat(&Tok::LBracket) {
767            let mut items = Vec::new();
768            if !self.eat(&Tok::RBracket) {
769                loop {
770                    items.push(self.arith_expr()?);
771                    if self.eat(&Tok::Comma) {
772                        continue;
773                    }
774                    self.expect(&Tok::RBracket, "expected ']' to close IN list")?;
775                    break;
776                }
777            }
778            Ok(items)
779        } else {
780            Ok(vec![self.arith_expr()?])
781        }
782    }
783
784    // ── Arithmetic expression parsing (precedence: * / > + -) ──────────────
785    //
786    // Grammar:
787    //   arith_expr  = arith_add
788    //   arith_add   = arith_mul ((+ | -) arith_mul)*
789    //   arith_mul   = arith_unary ((* | /) arith_unary)*
790    //   arith_unary = - arith_atom | arith_atom
791    //   arith_atom  = literal | param | ident | ident.field | ident(args…) | (arith_add)
792
793    /// Parse a full arithmetic expression (additive level).
794    fn arith_expr(&mut self) -> Result<Operand, String> {
795        let mut left = self.arith_mul()?;
796        loop {
797            let op = if self.eat(&Tok::Plus) {
798                ArithOp::Add
799            } else if self.eat(&Tok::Dash) {
800                // Dash is `-`; but we must not consume a Dash that starts a
801                // relationship pattern (those appear at the top-level pattern
802                // parser, not inside an expression). Inside expressions `-`
803                // is always subtraction.
804                ArithOp::Sub
805            } else {
806                break;
807            };
808            let right = self.arith_mul()?;
809            left = Operand::BinArith {
810                op,
811                left: Box::new(left),
812                right: Box::new(right),
813            };
814        }
815        Ok(left)
816    }
817
818    /// Parse a multiplicative-level arithmetic expression.
819    fn arith_mul(&mut self) -> Result<Operand, String> {
820        let mut left = self.arith_unary()?;
821        loop {
822            let op = if self.eat(&Tok::Star) {
823                ArithOp::Mul
824            } else if self.eat(&Tok::Slash) {
825                ArithOp::Div
826            } else {
827                break;
828            };
829            let right = self.arith_unary()?;
830            left = Operand::BinArith {
831                op,
832                left: Box::new(left),
833                right: Box::new(right),
834            };
835        }
836        Ok(left)
837    }
838
839    /// Parse a unary-level arithmetic expression (handles unary `-`).
840    fn arith_unary(&mut self) -> Result<Operand, String> {
841        if self.eat(&Tok::Dash) {
842            // Unary minus: fold into the next atom.
843            return match self.peek() {
844                Some(Tok::Int(n)) => {
845                    let n = *n;
846                    self.pos += 1;
847                    let neg = n
848                        .checked_neg()
849                        .ok_or_else(|| self.err("integer negation overflow"))?;
850                    Ok(Operand::Lit(Value::Int(neg)))
851                }
852                Some(Tok::Float(x)) => {
853                    let x = *x;
854                    self.pos += 1;
855                    Ok(Operand::Lit(Value::Float(-x)))
856                }
857                _ => Err(self.err("unary minus only applies to numeric literals")),
858            };
859        }
860        self.arith_atom()
861    }
862
863    /// Parse an atomic operand (leaf of the arithmetic expression tree).
864    fn arith_atom(&mut self) -> Result<Operand, String> {
865        // Parenthesized arithmetic expression.
866        if self.eat(&Tok::LParen) {
867            let inner = self.arith_expr()?;
868            self.expect(&Tok::RParen, "expected ')' to close arithmetic expression")?;
869            return Ok(inner);
870        }
871        // Delegate to the existing atom parser (no unary minus here — handled above).
872        let atom = self.operand_atom()?;
873        self.subscripts(atom)
874    }
875
876    /// Apply any postfix `[index]` subscripts to an already-parsed operand.
877    ///
878    /// `n.location[0]` is how an assistant reads one end of a `[lat, lon]`
879    /// pair, and it used to stop the parse dead at the `[`. Chained
880    /// subscripts (`n.grid[0][1]`) parse; only the first level is ever
881    /// non-null for the list shapes the graph stores.
882    fn subscripts(&mut self, mut base: Operand) -> Result<Operand, String> {
883        while self.eat(&Tok::LBracket) {
884            let index = self.arith_expr()?;
885            self.expect(&Tok::RBracket, "expected ']' to close a list subscript")?;
886            base = Operand::Index {
887                base: Box::new(base),
888                index: Box::new(index),
889            };
890        }
891        Ok(base)
892    }
893
894    fn cmp_op(&mut self) -> Result<CmpOp, String> {
895        let op = match self.peek() {
896            Some(Tok::Eq) => CmpOp::Eq,
897            Some(Tok::Ne) => CmpOp::Ne,
898            Some(Tok::Lt) => CmpOp::Lt,
899            Some(Tok::Le) => CmpOp::Le,
900            Some(Tok::Gt) => CmpOp::Gt,
901            Some(Tok::Ge) => CmpOp::Ge,
902            _ => return Err(self.err("expected comparison operator")),
903        };
904        self.pos += 1;
905        Ok(op)
906    }
907
908    /// Parse a single atomic operand (no arithmetic wrapping — use `arith_expr`
909    /// for full expression support).  This is the leaf parser for literals,
910    /// parameters, property references, variable references, and function calls.
911    fn operand_atom(&mut self) -> Result<Operand, String> {
912        match self.peek() {
913            Some(Tok::Int(n)) => {
914                let n = *n;
915                self.pos += 1;
916                Ok(Operand::Lit(Value::Int(n)))
917            }
918            Some(Tok::Float(x)) => {
919                let x = *x;
920                self.pos += 1;
921                Ok(Operand::Lit(Value::Float(x)))
922            }
923            Some(Tok::Str(s)) => {
924                let s = s.clone();
925                self.pos += 1;
926                Ok(Operand::Lit(Value::Str(s)))
927            }
928            Some(Tok::Param(s)) => {
929                let s = s.clone();
930                self.pos += 1;
931                Ok(Operand::Param(s))
932            }
933            Some(Tok::Ident(_)) => {
934                let name = self.ident("expected identifier")?;
935                if name.eq_ignore_ascii_case("case") {
936                    return self.parse_case();
937                }
938                if name.eq_ignore_ascii_case("collect") && self.peek() == Some(&Tok::LParen) {
939                    // collect() is a top-level RETURN/WITH aggregate (handled in
940                    // ret_item); it is not valid inside a larger expression.
941                    return Err(
942                        "collect() is only supported as a top-level RETURN/WITH aggregate"
943                            .to_string(),
944                    );
945                }
946                if self.peek() == Some(&Tok::LParen) {
947                    // Scalar function call: name(arg, ...)
948                    // Function arguments may be arbitrary arithmetic expressions.
949                    self.pos += 1; // consume '('
950                    let mut args = Vec::new();
951                    if self.peek() != Some(&Tok::RParen) {
952                        args.push(self.arith_expr()?);
953                        while self.eat(&Tok::Comma) {
954                            args.push(self.arith_expr()?);
955                        }
956                    }
957                    self.expect(&Tok::RParen, "expected ')' to close function call")?;
958                    Ok(Operand::FuncCall { name, args })
959                } else if self.eat(&Tok::Dot) {
960                    let field = self.ident("expected field name after '.'")?;
961                    Ok(Operand::Prop { var: name, field })
962                } else {
963                    // Bare variable reference (e.g. alias name in WITH … WHERE c > 2).
964                    Ok(Operand::Var(name))
965                }
966            }
967            _ => Err(self.err("expected operand (property, literal, or parameter)")),
968        }
969    }
970
971    /// Parse a generic `CASE WHEN <cond> THEN <value> … [ELSE <value>] END`.
972    /// The `CASE` keyword has already been consumed. `WHEN`/`THEN`/`ELSE`/`END`
973    /// are ordinary identifiers to the lexer, matched case-insensitively.
974    fn parse_case(&mut self) -> Result<Operand, String> {
975        let is_kw = |tok: Option<&Tok>, kw: &str| matches!(tok, Some(Tok::Ident(s)) if s.eq_ignore_ascii_case(kw));
976        let mut branches = Vec::new();
977        while is_kw(self.peek(), "when") {
978            self.pos += 1; // consume WHEN
979            let cond = self.expr(0)?;
980            if !is_kw(self.peek(), "then") {
981                return Err(self.err("expected THEN in a CASE branch"));
982            }
983            self.pos += 1; // consume THEN
984            let value = self.arith_expr()?;
985            branches.push((cond, value));
986        }
987        if branches.is_empty() {
988            return Err(self.err("CASE requires at least one WHEN ... THEN branch"));
989        }
990        let default = if is_kw(self.peek(), "else") {
991            self.pos += 1; // consume ELSE
992            Some(Box::new(self.arith_expr()?))
993        } else {
994            None
995        };
996        if !is_kw(self.peek(), "end") {
997            return Err(self.err("expected END to close CASE"));
998        }
999        self.pos += 1; // consume END
1000        Ok(Operand::Case { branches, default })
1001    }
1002
1003    /// Parse a full arithmetic expression (additive + multiplicative + unary +
1004    /// atom).  This is the primary operand entry point for WHERE, RETURN, SET,
1005    /// and function arguments.  Use `operand_atom` for contexts that truly
1006    /// require a single atom (e.g., MATCH property map values where arithmetic
1007    /// would be syntactically ambiguous with the `}` delimiter).
1008    fn operand(&mut self) -> Result<Operand, String> {
1009        // In contexts where `operand` is called for MATCH props, the parser
1010        // never sees arithmetic operators (`+`/`/`) because they can't appear
1011        // inside `{key: val}` maps.  Delegating to `arith_expr` is safe here.
1012        self.arith_expr()
1013    }
1014
1015    fn return_clause(&mut self) -> Result<(bool, Vec<RetItem>), String> {
1016        if !self.eat(&Tok::Return) {
1017            return Err(self.unsupported_or_unexpected("expected RETURN"));
1018        }
1019        let distinct = self.eat_ident_kw("distinct");
1020        let mut items = vec![self.ret_item()?];
1021        while self.eat(&Tok::Comma) {
1022            items.push(self.ret_item()?);
1023        }
1024        Ok((distinct, items))
1025    }
1026
1027    fn return_items(&mut self) -> Result<Vec<RetItem>, String> {
1028        let mut items = vec![self.ret_item()?];
1029        while self.eat(&Tok::Comma) {
1030            items.push(self.ret_item()?);
1031        }
1032        Ok(items)
1033    }
1034
1035    fn ret_item(&mut self) -> Result<RetItem, String> {
1036        // Check for an aggregate function name (COUNT/SUM/AVG/MIN/MAX).
1037        // These are ordinary identifiers in the lexer, so we peek and check
1038        // the lowercased string before deciding the parse branch.
1039        if let Some(Tok::Ident(s)) = self.peek() {
1040            let func = match s.to_ascii_lowercase().as_str() {
1041                "count" => Some(AggFunc::Count),
1042                "sum" => Some(AggFunc::Sum),
1043                "avg" => Some(AggFunc::Avg),
1044                "min" => Some(AggFunc::Min),
1045                "max" => Some(AggFunc::Max),
1046                "collect" => Some(AggFunc::Collect),
1047                _ => None,
1048            };
1049            if let Some(func) = func {
1050                self.pos += 1; // consume the function name
1051                self.expect(&Tok::LParen, "expected '(' after aggregate function name")?;
1052                // `count(DISTINCT t)` — DISTINCT is an ordinary identifier to
1053                // the lexer, so it is only a modifier here when something
1054                // follows it inside the parens.
1055                let distinct = matches!(self.peek(), Some(Tok::Ident(s)) if s.eq_ignore_ascii_case("distinct"))
1056                    && !matches!(self.toks.get(self.pos + 1), Some(Tok::RParen));
1057                if distinct {
1058                    self.pos += 1;
1059                    if self.peek() == Some(&Tok::Star) {
1060                        return Err(self.err("DISTINCT * is not a valid aggregate argument"));
1061                    }
1062                }
1063                let arg = if self.eat(&Tok::Star) {
1064                    AggArg::Star
1065                } else {
1066                    let var = self.ident("expected variable or '*' in aggregate argument")?;
1067                    if self.eat(&Tok::Dot) {
1068                        let field =
1069                            self.ident("expected field name after '.' in aggregate argument")?;
1070                        AggArg::Prop { var, field }
1071                    } else {
1072                        AggArg::Var(var)
1073                    }
1074                };
1075                let arg = if distinct {
1076                    AggArg::Distinct(Box::new(arg))
1077                } else {
1078                    arg
1079                };
1080                self.expect(&Tok::RParen, "expected ')' to close aggregate function")?;
1081                let alias = if self.eat(&Tok::As) {
1082                    Some(self.ident("expected alias identifier after AS")?)
1083                } else {
1084                    None
1085                };
1086                return Ok(RetItem {
1087                    value: RetVal::Agg { func, arg },
1088                    alias,
1089                });
1090            }
1091        }
1092
1093        // Non-aggregate RETURN item: parse as a full arithmetic expression,
1094        // then convert the resulting Operand to the appropriate RetVal variant.
1095        // This unified path handles:
1096        //   n          → RetVal::Var
1097        //   n.prop     → RetVal::Prop
1098        //   f(...)     → RetVal::FuncCall
1099        //   n.age + 1  → RetVal::ScalarExpr(BinArith)
1100        //   42         → RetVal::ScalarExpr(Lit)
1101        let op = self.arith_expr()?;
1102        let value = match op {
1103            Operand::Var(name) => RetVal::Var(name),
1104            Operand::Prop { var, field } => RetVal::Prop { var, field },
1105            Operand::FuncCall { name, args } => RetVal::FuncCall { name, args },
1106            other => RetVal::ScalarExpr(other),
1107        };
1108        let alias = if self.eat(&Tok::As) {
1109            Some(self.ident("expected alias identifier after AS")?)
1110        } else {
1111            None
1112        };
1113        Ok(RetItem { value, alias })
1114    }
1115
1116    fn order_clause(&mut self, aliases: &[&str]) -> Result<Vec<OrderItem>, String> {
1117        self.expect(&Tok::Order, "expected ORDER")?;
1118        self.expect(&Tok::By, "expected BY after ORDER")?;
1119        let mut items = vec![self.order_item(aliases)?];
1120        while self.eat(&Tok::Comma) {
1121            items.push(self.order_item(aliases)?);
1122        }
1123        Ok(items)
1124    }
1125
1126    fn order_item(&mut self, aliases: &[&str]) -> Result<OrderItem, String> {
1127        let name = self.ident("expected ORDER BY target")?;
1128        let target = if self.eat(&Tok::Dot) {
1129            let field = self.ident("expected field name after '.'")?;
1130            OrderTarget::Prop { var: name, field }
1131        } else if aliases.contains(&name.as_str()) {
1132            OrderTarget::Alias(name)
1133        } else {
1134            OrderTarget::Var(name)
1135        };
1136        let descending = if self.eat(&Tok::Desc) {
1137            true
1138        } else {
1139            let _ = self.eat(&Tok::Asc);
1140            false
1141        };
1142        Ok(OrderItem { target, descending })
1143    }
1144
1145    fn uint(&mut self, what: &str) -> Result<LimitSkip, String> {
1146        match self.peek() {
1147            Some(Tok::Int(n)) if *n >= 0 => {
1148                let n = *n as u64;
1149                self.pos += 1;
1150                Ok(LimitSkip::Exact(n))
1151            }
1152            Some(Tok::Int(_)) => Err(self.err(&format!("{what} must be a non-negative integer"))),
1153            Some(Tok::Param(_)) => {
1154                let name = match self.toks.get(self.pos) {
1155                    Some(Tok::Param(s)) => s.clone(),
1156                    _ => unreachable!(),
1157                };
1158                self.pos += 1;
1159                Ok(LimitSkip::Param(name))
1160            }
1161            _ => Err(self.err(&format!("expected integer or $parameter after {what}"))),
1162        }
1163    }
1164
1165    // ── Write statement parsing ───────────────────────────────────────────────
1166
1167    fn write_statement(&mut self) -> Result<WriteStatement, String> {
1168        match self.peek() {
1169            Some(Tok::Create) => self.create_stmt(),
1170            Some(Tok::Merge) => self.merge_stmt(),
1171            Some(Tok::Match) => self.match_write_stmt(),
1172            _ => Err(self
1173                .err("expected CREATE, MERGE, or MATCH … SET/DELETE (write statement required)")),
1174        }
1175    }
1176
1177    // ── CREATE ────────────────────────────────────────────────────────────────
1178
1179    fn create_stmt(&mut self) -> Result<WriteStatement, String> {
1180        self.expect(&Tok::Create, "expected CREATE")?;
1181        let mut stmt = self.create_pattern()?;
1182        // Optional RETURN clause: `CREATE (n:L {…}) RETURN n` or `RETURN n.id AS id`.
1183        if self.eat(&Tok::Return) {
1184            stmt.returns = Some(self.return_items()?);
1185        }
1186        if self.pos < self.toks.len() {
1187            return Err(self.err("unexpected tokens after CREATE"));
1188        }
1189        Ok(WriteStatement::Create(stmt))
1190    }
1191
1192    fn create_pattern(&mut self) -> Result<CreateStmt, String> {
1193        // Parse the first (possibly only) node.
1194        let first = self.create_node(0)?;
1195        let first_var = first.var.clone().unwrap_or_else(|| format!("_cn{}", 0));
1196        let mut nodes: Vec<CreateNode> = vec![first];
1197        let mut edges: Vec<CreateEdge> = Vec::new();
1198
1199        // Chain: (-[:T]-> | <-[:T]-) followed by another node.
1200        while matches!(self.peek(), Some(Tok::Dash) | Some(Tok::Lt)) {
1201            let (etype, src_is_left) = self.create_rel()?;
1202            let idx = nodes.len();
1203            let next = self.create_node(idx)?;
1204            let next_var = next.var.clone().unwrap_or_else(|| format!("_cn{idx}"));
1205            let prev_var = nodes.last().unwrap().var.clone().unwrap_or_else(|| {
1206                if nodes.len() == 1 {
1207                    first_var.clone()
1208                } else {
1209                    format!("_cn{}", nodes.len() - 1)
1210                }
1211            });
1212            let (src_var, dst_var) = if src_is_left {
1213                // <-[:T]- means next→prev i.e. next is src
1214                (next_var.clone(), prev_var)
1215            } else {
1216                // -[:T]-> means prev→next
1217                (prev_var, next_var.clone())
1218            };
1219            edges.push(CreateEdge {
1220                src_var,
1221                etype,
1222                dst_var,
1223            });
1224            nodes.push(next);
1225        }
1226        Ok(CreateStmt {
1227            nodes,
1228            edges,
1229            returns: None,
1230        })
1231    }
1232
1233    fn create_node(&mut self, idx: usize) -> Result<CreateNode, String> {
1234        self.expect(&Tok::LParen, "expected '(' in CREATE node pattern")?;
1235        let var = match self.peek() {
1236            Some(Tok::Ident(s)) => {
1237                let s = s.clone();
1238                self.pos += 1;
1239                Some(s)
1240            }
1241            _ => None,
1242        };
1243        if !self.eat(&Tok::Colon) {
1244            return Err(self.err("CREATE node requires a label (e.g., (n:Label {…}))"));
1245        }
1246        let label = self.ident("expected label identifier after ':'")?;
1247        let props = if self.peek() == Some(&Tok::LBrace) {
1248            self.literal_props()?
1249        } else {
1250            Vec::new()
1251        };
1252        self.expect(&Tok::RParen, "expected ')' to close CREATE node pattern")?;
1253        let var = Some(var.unwrap_or_else(|| format!("_cn{idx}")));
1254        Ok(CreateNode { var, label, props })
1255    }
1256
1257    /// Parse `{key: literal, …}` where all values must be literals (no params, no props).
1258    fn literal_props(&mut self) -> Result<Vec<(String, Value)>, String> {
1259        self.expect(&Tok::LBrace, "expected '{'")?;
1260        let mut out = Vec::new();
1261        if self.eat(&Tok::RBrace) {
1262            return Ok(out);
1263        }
1264        loop {
1265            let key = self.ident("expected property key")?;
1266            self.expect(&Tok::Colon, "expected ':' after property key")?;
1267            let val = self.literal_value("property value")?;
1268            out.push((key, val));
1269            if self.eat(&Tok::Comma) {
1270                continue;
1271            }
1272            break;
1273        }
1274        self.expect(&Tok::RBrace, "expected '}' to close property map")?;
1275        Ok(out)
1276    }
1277
1278    /// Parse a literal value (int, float, or string). Parameters and property
1279    /// references are not accepted in write statements (v1 limitation).
1280    fn literal_value(&mut self, what: &str) -> Result<Value, String> {
1281        if self.eat(&Tok::Dash) {
1282            return match self.peek() {
1283                Some(Tok::Int(n)) => {
1284                    let n = *n;
1285                    self.pos += 1;
1286                    Ok(Value::Int(-n))
1287                }
1288                Some(Tok::Float(x)) => {
1289                    let x = *x;
1290                    self.pos += 1;
1291                    Ok(Value::Float(-x))
1292                }
1293                _ => Err(self.err("unary minus only applies to numeric literals")),
1294            };
1295        }
1296        match self.peek() {
1297            Some(Tok::Int(n)) => {
1298                let n = *n;
1299                self.pos += 1;
1300                Ok(Value::Int(n))
1301            }
1302            Some(Tok::Float(x)) => {
1303                let x = *x;
1304                self.pos += 1;
1305                Ok(Value::Float(x))
1306            }
1307            Some(Tok::Str(s)) => {
1308                let s = s.clone();
1309                self.pos += 1;
1310                Ok(Value::Str(s))
1311            }
1312            // List literal: `[]`, `[v1, v2, …]`, nesting allowed. Elements are
1313            // themselves literal values (recursion), matching the UNWIND list
1314            // form and downstream `Value::List` support in the store.
1315            Some(Tok::LBracket) => {
1316                self.pos += 1; // consume '['
1317                let mut items = Vec::new();
1318                if !self.eat(&Tok::RBracket) {
1319                    loop {
1320                        items.push(self.literal_value(what)?);
1321                        if self.eat(&Tok::Comma) {
1322                            continue;
1323                        }
1324                        self.expect(&Tok::RBracket, "expected ']' to close list literal")?;
1325                        break;
1326                    }
1327                }
1328                Ok(Value::List(items))
1329            }
1330            Some(Tok::Param(_)) => Err(self.err(&format!(
1331                "parameter references are not supported in {what} (v1 limitation: use literals only)"
1332            ))),
1333            Some(Tok::Ident(_)) => Err(self.err(&format!(
1334                "expression RHS not supported in {what} (v1 limitation: use literals only)"
1335            ))),
1336            _ => Err(self.err(&format!("expected literal value for {what}"))),
1337        }
1338    }
1339
1340    /// Parse `-[:TYPE]->` or `<-[:TYPE]-`.  Returns `(etype, src_is_left)` where
1341    /// `src_is_left = true` means left node is dst (i.e., next node is src).
1342    fn create_rel(&mut self) -> Result<(String, bool), String> {
1343        if self.eat(&Tok::Lt) {
1344            // <-[:TYPE]-
1345            self.expect(&Tok::Dash, "expected '-' after '<' in relationship")?;
1346            self.expect(&Tok::LBracket, "expected '[' in relationship pattern")?;
1347            self.expect(&Tok::Colon, "expected ':TYPE' in CREATE relationship")?;
1348            let etype = self.ident("expected relationship type")?;
1349            self.expect(&Tok::RBracket, "expected ']'")?;
1350            self.expect(&Tok::Dash, "expected '-'")?;
1351            return Ok((etype, true));
1352        }
1353        // -[:TYPE]->
1354        self.expect(&Tok::Dash, "expected '-' to start relationship")?;
1355        self.expect(&Tok::LBracket, "expected '[' in relationship pattern")?;
1356        self.expect(&Tok::Colon, "expected ':TYPE' in CREATE relationship")?;
1357        let etype = self.ident("expected relationship type")?;
1358        self.expect(&Tok::RBracket, "expected ']'")?;
1359        self.expect(&Tok::Dash, "expected '-'")?;
1360        self.expect(
1361            &Tok::Gt,
1362            "expected '>' — CREATE requires directed relationships",
1363        )?;
1364        Ok((etype, false))
1365    }
1366
1367    // ── MERGE ─────────────────────────────────────────────────────────────────
1368
1369    fn merge_stmt(&mut self) -> Result<WriteStatement, String> {
1370        self.expect(&Tok::Merge, "expected MERGE")?;
1371        self.expect(&Tok::LParen, "expected '(' after MERGE")?;
1372        // Optional var: `MERGE (n:Label {…})` — capture n for RETURN projection.
1373        let var = match self.peek() {
1374            Some(Tok::Ident(_)) => {
1375                let s = match self.toks.get(self.pos) {
1376                    Some(Tok::Ident(s)) => s.clone(),
1377                    _ => unreachable!(),
1378                };
1379                self.pos += 1; // consume var name
1380                Some(s)
1381            }
1382            _ => None,
1383        };
1384        if !self.eat(&Tok::Colon) {
1385            return Err(self.err("MERGE requires a label (e.g., MERGE (n:Label {key: 'x'}))"));
1386        }
1387        let label = self.ident("expected label identifier after ':'")?;
1388        if self.peek() != Some(&Tok::LBrace) {
1389            return Err(self.err(
1390                "MERGE requires a property map with exactly one key (e.g., MERGE (n:Label {id: 'x'}))",
1391            ));
1392        }
1393        let mut props = self.literal_props()?;
1394        if props.len() != 1 {
1395            return Err(format!(
1396                "MERGE supports exactly one key property (got {}); use CREATE for multi-prop nodes",
1397                props.len()
1398            ));
1399        }
1400        self.expect(&Tok::RParen, "expected ')' to close MERGE pattern")?;
1401        let mut on_create = Vec::new();
1402        let mut on_match = Vec::new();
1403        while self.eat_ident_kw("on") {
1404            if self.eat(&Tok::Create) {
1405                self.expect(&Tok::Set, "expected SET after ON CREATE")?;
1406                on_create.extend(self.set_clauses()?);
1407            } else if self.eat(&Tok::Match) {
1408                self.expect(&Tok::Set, "expected SET after ON MATCH")?;
1409                on_match.extend(self.set_clauses()?);
1410            } else {
1411                return Err(self.err("expected CREATE or MATCH after ON"));
1412            }
1413        }
1414        // Optional RETURN clause.
1415        let returns = if self.eat(&Tok::Return) {
1416            Some(self.return_items()?)
1417        } else {
1418            None
1419        };
1420        if self.pos < self.toks.len() {
1421            return Err(self.unsupported_or_unexpected("unexpected tokens after MERGE"));
1422        }
1423        let (key_field, key_value) = props.remove(0);
1424        Ok(WriteStatement::Merge(MergeStmt {
1425            label,
1426            key_field,
1427            key_value,
1428            var,
1429            on_create,
1430            on_match,
1431            returns,
1432        }))
1433    }
1434
1435    // ── MATCH … SET / MATCH … DELETE ─────────────────────────────────────────
1436
1437    fn match_write_stmt(&mut self) -> Result<WriteStatement, String> {
1438        // Parse MATCH clauses (same as read query).
1439        let mut matches = Vec::new();
1440        while self.peek() == Some(&Tok::Match) {
1441            matches.extend(self.match_clause()?);
1442        }
1443        if matches.is_empty() {
1444            return Err(self.err("expected MATCH"));
1445        }
1446        // Optional WHERE.
1447        let where_expr = if self.eat(&Tok::Where) {
1448            Some(self.expr(0)?)
1449        } else {
1450            None
1451        };
1452        // Dispatch on SET, DETACH DELETE, or DELETE.
1453        match self.peek() {
1454            Some(Tok::Set) => {
1455                self.pos += 1; // consume SET
1456                let sets = self.set_clauses()?;
1457                let returns = if self.eat(&Tok::Return) {
1458                    Some(self.return_items()?)
1459                } else {
1460                    None
1461                };
1462                if self.pos < self.toks.len() {
1463                    return Err(self.unsupported_or_unexpected("unexpected tokens after SET"));
1464                }
1465                Ok(WriteStatement::MatchSet(MatchSetStmt {
1466                    matches,
1467                    where_expr,
1468                    sets,
1469                    returns,
1470                }))
1471            }
1472            Some(Tok::Detach) => {
1473                // DETACH DELETE <node_var> [, …]
1474                self.pos += 1; // consume DETACH
1475                self.expect(&Tok::Delete, "expected DELETE after DETACH")?;
1476                let node_vars = self.node_delete_targets(&matches)?;
1477                if self.pos < self.toks.len() {
1478                    return Err(self.err("unexpected tokens after DETACH DELETE"));
1479                }
1480                Ok(WriteStatement::MatchDeleteNode(MatchDeleteNodeStmt {
1481                    matches,
1482                    where_expr,
1483                    node_vars,
1484                    detach: true,
1485                }))
1486            }
1487            Some(Tok::Delete) => {
1488                self.pos += 1; // consume DELETE
1489                               // Try to resolve all targets as edge vars first. If the first
1490                               // target is a node var (not an edge var), fall through to node delete.
1491                match self.delete_targets_or_node(&matches)? {
1492                    DeleteTargetResult::Edges(deletes) => {
1493                        if self.pos < self.toks.len() {
1494                            return Err(self.err("unexpected tokens after DELETE"));
1495                        }
1496                        Ok(WriteStatement::MatchDelete(MatchDeleteStmt {
1497                            matches,
1498                            where_expr,
1499                            deletes,
1500                        }))
1501                    }
1502                    DeleteTargetResult::Nodes(node_vars) => {
1503                        if self.pos < self.toks.len() {
1504                            return Err(self.err("unexpected tokens after DELETE"));
1505                        }
1506                        Ok(WriteStatement::MatchDeleteNode(MatchDeleteNodeStmt {
1507                            matches,
1508                            where_expr,
1509                            node_vars,
1510                            detach: false,
1511                        }))
1512                    }
1513                }
1514            }
1515            _ => Err(self.err(
1516                "expected SET or DELETE after MATCH [WHERE]; \
1517                 combined MATCH…RETURN is a read query, not a write statement",
1518            )),
1519        }
1520    }
1521
1522    fn set_clauses(&mut self) -> Result<Vec<SetClause>, String> {
1523        let mut sets = vec![self.set_clause()?];
1524        while self.eat(&Tok::Comma) {
1525            sets.push(self.set_clause()?);
1526        }
1527        Ok(sets)
1528    }
1529
1530    fn set_clause(&mut self) -> Result<SetClause, String> {
1531        let var = self.ident("expected variable in SET clause")?;
1532        self.expect(&Tok::Dot, "expected '.' after variable in SET")?;
1533        let field = self.ident("expected field name after '.'")?;
1534        self.expect(&Tok::Eq, "expected '=' in SET clause")?;
1535        // Accept Lit, Param, BinArith (arithmetic expression), and FuncCall on
1536        // the RHS. Bare Prop/Var (e.g. `SET n.x = m.y`) remain a named error
1537        // because that form requires join semantics not supported in v1; use
1538        // an arithmetic expression like `m.y + 0` if needed.
1539        let value = match self.peek() {
1540            Some(
1541                Tok::Int(_)
1542                | Tok::Float(_)
1543                | Tok::Str(_)
1544                | Tok::Param(_)
1545                | Tok::Dash
1546                | Tok::Ident(_),
1547            ) => {
1548                let op = self.arith_expr()?;
1549                match &op {
1550                    Operand::Lit(_)
1551                    | Operand::Param(_)
1552                    | Operand::BinArith { .. }
1553                    | Operand::FuncCall { .. }
1554                    | Operand::Index { .. }
1555                    | Operand::Case { .. } => op,
1556                    Operand::Prop { .. } | Operand::Var(_) => {
1557                        return Err(self.err(
1558                            "SET RHS: bare property/variable reference is not supported; \
1559                             use a literal, $parameter, or arithmetic expression (e.g. n.x + 1)",
1560                        ));
1561                    }
1562                }
1563            }
1564            // List-literal RHS: `SET n.tags = ['a', 'b']`. Lists are pure
1565            // literals (no arithmetic), so parse directly into `Operand::Lit`.
1566            Some(Tok::LBracket) => Operand::Lit(self.literal_value("SET value")?),
1567            _ => {
1568                return Err(
1569                    self.err("expected literal, $parameter, or arithmetic expression as SET value")
1570                )
1571            }
1572        };
1573        Ok(SetClause { var, field, value })
1574    }
1575
1576    /// Find the rel-var `var` in `patterns` and return its etype, src node var,
1577    /// and dst node var.  Returns Err if the var is not a rel var or has no type.
1578    fn resolve_edge_var(&self, var: &str, patterns: &[Pattern]) -> Result<EdgeDelete, String> {
1579        for pat in patterns {
1580            let start_var = pat.start.var.as_deref().unwrap_or("_unknown");
1581            let mut from_var = start_var;
1582            for (rel, dest) in &pat.chain {
1583                let to_var = dest.var.as_deref().unwrap_or("_unknown");
1584                if rel.var.as_deref() == Some(var) {
1585                    let etype = match rel.etypes.as_slice() {
1586                        [t] => t.clone(),
1587                        [] => {
1588                            return Err(format!(
1589                                "DELETE `{var}`: relationship has no type; \
1590                                 DELETE requires an explicit edge type (e.g., [r:TYPE])"
1591                            ))
1592                        }
1593                        _ => {
1594                            return Err(format!(
1595                                "DELETE `{var}`: relationship has multiple types; \
1596                                 DELETE requires a single explicit edge type (e.g., [r:TYPE])"
1597                            ))
1598                        }
1599                    };
1600                    let (src_var, dst_var) = match rel.dir {
1601                        RelDir::Right => (from_var.to_string(), to_var.to_string()),
1602                        RelDir::Left => (to_var.to_string(), from_var.to_string()),
1603                        RelDir::Undirected => {
1604                            return Err(format!(
1605                                "DELETE `{var}`: undirected relationship DELETE is not supported; \
1606                                 use a directed pattern (e.g., -[r:TYPE]->)"
1607                            ))
1608                        }
1609                    };
1610                    return Ok(EdgeDelete {
1611                        rel_var: var.to_string(),
1612                        etype,
1613                        src_var,
1614                        dst_var,
1615                    });
1616                }
1617                from_var = to_var;
1618            }
1619        }
1620        Err(format!(
1621            "DELETE `{var}`: variable is not bound as a relationship in any MATCH pattern; \
1622             only relationship variables can be deleted (DELETE edge vars, not node vars)"
1623        ))
1624    }
1625
1626    /// Return `true` if `var` is bound as a node variable in `patterns`.
1627    fn is_node_var(&self, var: &str, patterns: &[Pattern]) -> bool {
1628        for pat in patterns {
1629            if pat.start.var.as_deref() == Some(var) {
1630                return true;
1631            }
1632            for (_, dest) in &pat.chain {
1633                if dest.var.as_deref() == Some(var) {
1634                    return true;
1635                }
1636            }
1637        }
1638        false
1639    }
1640
1641    /// Parse a comma-separated list of node-variable targets for
1642    /// `[DETACH] DELETE`.  All targets must be node variables bound in `patterns`.
1643    fn node_delete_targets(&mut self, patterns: &[Pattern]) -> Result<Vec<String>, String> {
1644        let mut vars = Vec::new();
1645        loop {
1646            let var = self.ident("expected node variable to DELETE")?;
1647            if !self.is_node_var(&var, patterns) {
1648                return Err(format!(
1649                    "DELETE `{var}`: variable is not bound as a node in any MATCH pattern"
1650                ));
1651            }
1652            vars.push(var);
1653            if !self.eat(&Tok::Comma) {
1654                break;
1655            }
1656        }
1657        Ok(vars)
1658    }
1659
1660    /// Try to parse DELETE targets as edge vars; if the first target is a node
1661    /// var, fall back to parsing all targets as node vars.
1662    fn delete_targets_or_node(
1663        &mut self,
1664        patterns: &[Pattern],
1665    ) -> Result<DeleteTargetResult, String> {
1666        // Peek at the identifier to decide which path to take.
1667        let var = self.ident("expected variable to DELETE")?;
1668        // Try edge var first.
1669        match self.resolve_edge_var(&var, patterns) {
1670            Ok(edge_del) => {
1671                // At least the first target is an edge var; parse the rest as
1672                // edge vars too.
1673                let mut targets = vec![edge_del];
1674                while self.eat(&Tok::Comma) {
1675                    let v = self.ident("expected variable to DELETE")?;
1676                    targets.push(self.resolve_edge_var(&v, patterns)?);
1677                }
1678                Ok(DeleteTargetResult::Edges(targets))
1679            }
1680            Err(_) => {
1681                // Not an edge var; try as node var.
1682                if self.is_node_var(&var, patterns) {
1683                    let mut node_vars = vec![var];
1684                    while self.eat(&Tok::Comma) {
1685                        let v = self.ident("expected variable to DELETE")?;
1686                        if !self.is_node_var(&v, patterns) {
1687                            return Err(format!(
1688                                "DELETE `{v}`: variable is not bound as a node in any MATCH pattern"
1689                            ));
1690                        }
1691                        node_vars.push(v);
1692                    }
1693                    Ok(DeleteTargetResult::Nodes(node_vars))
1694                } else {
1695                    Err(format!(
1696                        "DELETE `{var}`: variable is not bound as a relationship or node \
1697                         in any MATCH pattern"
1698                    ))
1699                }
1700            }
1701        }
1702    }
1703}
1704
1705/// Used internally by `delete_targets_or_node` to signal whether the targets
1706/// resolved to edge variables or node variables.
1707enum DeleteTargetResult {
1708    Edges(Vec<EdgeDelete>),
1709    Nodes(Vec<String>),
1710}
1711
1712#[cfg(test)]
1713mod tests {
1714    use super::parse;
1715    use crate::cypher::ast::{
1716        AggFunc, Expr, HopRange, LimitSkip, NodePat, Operand, OrderItem, OrderTarget, Pattern,
1717        Query, RelDir, RelPat, RetItem, RetVal,
1718    };
1719    use crate::cypher::{lex, Tok};
1720    use crate::filter::CmpOp;
1721    use core_storage::Value;
1722
1723    fn parse_src(src: &str) -> Result<Query, String> {
1724        parse(&lex(src)?)
1725    }
1726
1727    fn prop(var: &str, field: &str) -> Operand {
1728        Operand::Prop {
1729            var: var.into(),
1730            field: field.into(),
1731        }
1732    }
1733
1734    fn cmp(lhs: Operand, op: CmpOp, rhs: Operand) -> Expr {
1735        Expr::Cmp { lhs, op, rhs }
1736    }
1737
1738    fn node(var: Option<&str>, label: Option<&str>, props: Vec<(String, Operand)>) -> NodePat {
1739        NodePat {
1740            var: var.map(str::to_string),
1741            label: label.map(str::to_string),
1742            props,
1743        }
1744    }
1745
1746    #[test]
1747    fn full_feature_query_exact_ast() {
1748        let src = "\
1749MATCH (a:Person {name: $n, age: 30})-[r:KNOWS]->(b)-[u:TEAM]-(c)<-[s:LIKES]-(d) \
1750WHERE NOT a.age < 18 AND b.name = 'x' OR c.score >= 2.5 \
1751RETURN a, r.since AS since, b.name \
1752ORDER BY since DESC, b.name ASC \
1753SKIP 1 LIMIT 5";
1754        let got = parse_src(src).expect("full-feature query must parse");
1755        let expected = Query {
1756            matches: vec![Pattern {
1757                start: node(
1758                    Some("a"),
1759                    Some("Person"),
1760                    vec![
1761                        ("name".into(), Operand::Param("n".into())),
1762                        ("age".into(), Operand::Lit(Value::Int(30))),
1763                    ],
1764                ),
1765                chain: vec![
1766                    (
1767                        RelPat {
1768                            var: Some("r".into()),
1769                            etypes: vec!["KNOWS".into()],
1770                            dir: RelDir::Right,
1771                            hops: None,
1772                        },
1773                        node(Some("b"), None, vec![]),
1774                    ),
1775                    (
1776                        RelPat {
1777                            var: Some("u".into()),
1778                            etypes: vec!["TEAM".into()],
1779                            dir: RelDir::Undirected,
1780                            hops: None,
1781                        },
1782                        node(Some("c"), None, vec![]),
1783                    ),
1784                    (
1785                        RelPat {
1786                            var: Some("s".into()),
1787                            etypes: vec!["LIKES".into()],
1788                            dir: RelDir::Left,
1789                            hops: None,
1790                        },
1791                        node(Some("d"), None, vec![]),
1792                    ),
1793                ],
1794                shortest: false,
1795            }],
1796            optional_clauses: vec![],
1797            unwinds: vec![],
1798            post_unwind_where: None,
1799            where_expr: Some(Expr::Or(
1800                Box::new(Expr::And(
1801                    Box::new(Expr::Not(Box::new(cmp(
1802                        prop("a", "age"),
1803                        CmpOp::Lt,
1804                        Operand::Lit(Value::Int(18)),
1805                    )))),
1806                    Box::new(cmp(
1807                        prop("b", "name"),
1808                        CmpOp::Eq,
1809                        Operand::Lit(Value::Str("x".into())),
1810                    )),
1811                )),
1812                Box::new(cmp(
1813                    prop("c", "score"),
1814                    CmpOp::Ge,
1815                    Operand::Lit(Value::Float(2.5)),
1816                )),
1817            )),
1818            stages: vec![],
1819            returns: vec![
1820                RetItem {
1821                    value: RetVal::Var("a".into()),
1822                    alias: None,
1823                },
1824                RetItem {
1825                    value: RetVal::Prop {
1826                        var: "r".into(),
1827                        field: "since".into(),
1828                    },
1829                    alias: Some("since".into()),
1830                },
1831                RetItem {
1832                    value: RetVal::Prop {
1833                        var: "b".into(),
1834                        field: "name".into(),
1835                    },
1836                    alias: None,
1837                },
1838            ],
1839            order_by: vec![
1840                OrderItem {
1841                    target: OrderTarget::Alias("since".into()),
1842                    descending: true,
1843                },
1844                OrderItem {
1845                    target: OrderTarget::Prop {
1846                        var: "b".into(),
1847                        field: "name".into(),
1848                    },
1849                    descending: false,
1850                },
1851            ],
1852            distinct: false,
1853            skip: Some(LimitSkip::Exact(1)),
1854            limit: Some(LimitSkip::Exact(5)),
1855        };
1856        assert_eq!(got, expected);
1857    }
1858
1859    #[test]
1860    fn rel_direction_right() {
1861        let q = parse_src("MATCH (a)-[r:T]->(b) RETURN a").unwrap();
1862        assert_eq!(q.matches[0].chain[0].0.dir, RelDir::Right);
1863        assert_eq!(q.matches[0].chain[0].0.var.as_deref(), Some("r"));
1864        assert_eq!(q.matches[0].chain[0].0.etypes, vec!["T".to_string()]);
1865    }
1866
1867    #[test]
1868    fn rel_direction_left() {
1869        let q = parse_src("MATCH (a)<-[r:T]-(b) RETURN a").unwrap();
1870        assert_eq!(q.matches[0].chain[0].0.dir, RelDir::Left);
1871    }
1872
1873    #[test]
1874    fn rel_direction_undirected() {
1875        let q = parse_src("MATCH (a)-[r:T]-(b) RETURN a").unwrap();
1876        assert_eq!(q.matches[0].chain[0].0.dir, RelDir::Undirected);
1877    }
1878
1879    #[test]
1880    fn node_props_map_with_param() {
1881        let q = parse_src("MATCH (t:Talent {id: $tid, n: 1, s: 'x'}) RETURN t").unwrap();
1882        assert_eq!(
1883            q.matches[0].start.props,
1884            vec![
1885                ("id".into(), Operand::Param("tid".into())),
1886                ("n".into(), Operand::Lit(Value::Int(1))),
1887                ("s".into(), Operand::Lit(Value::Str("x".into()))),
1888            ]
1889        );
1890        assert_eq!(q.matches[0].start.var.as_deref(), Some("t"));
1891        assert_eq!(q.matches[0].start.label.as_deref(), Some("Talent"));
1892    }
1893
1894    #[test]
1895    fn operator_precedence_or_and_not() {
1896        let q = parse_src("MATCH (a) WHERE a.x = 1 OR b.y = 2 AND NOT c.z = 3 RETURN a").unwrap();
1897        let expected = Expr::Or(
1898            Box::new(cmp(prop("a", "x"), CmpOp::Eq, Operand::Lit(Value::Int(1)))),
1899            Box::new(Expr::And(
1900                Box::new(cmp(prop("b", "y"), CmpOp::Eq, Operand::Lit(Value::Int(2)))),
1901                Box::new(Expr::Not(Box::new(cmp(
1902                    prop("c", "z"),
1903                    CmpOp::Eq,
1904                    Operand::Lit(Value::Int(3)),
1905                )))),
1906            )),
1907        );
1908        assert_eq!(q.where_expr, Some(expected));
1909    }
1910
1911    #[test]
1912    fn unary_minus_folds_numeric_literals() {
1913        let q = parse_src("MATCH (a) WHERE a.x > -5 AND a.y < -1.5 RETURN a").unwrap();
1914        let expected = Expr::And(
1915            Box::new(cmp(prop("a", "x"), CmpOp::Gt, Operand::Lit(Value::Int(-5)))),
1916            Box::new(cmp(
1917                prop("a", "y"),
1918                CmpOp::Lt,
1919                Operand::Lit(Value::Float(-1.5)),
1920            )),
1921        );
1922        assert_eq!(q.where_expr, Some(expected));
1923    }
1924
1925    fn assert_parse_err(src: &str) {
1926        let result = std::panic::catch_unwind(|| parse_src(src));
1927        assert!(result.is_ok(), "parse({src:?}) panicked");
1928        let err = result
1929            .unwrap()
1930            .expect_err(&format!("parse({src:?}) must be Err"));
1931        // Parse errors say "token"; lex errors say "position". Either is a valid reject.
1932        assert!(
1933            err.contains("token") || err.contains("position"),
1934            "error must include token or lex position, got: {err}"
1935        );
1936    }
1937
1938    #[test]
1939    fn malformed_match_alone_is_err() {
1940        assert_parse_err("MATCH");
1941    }
1942
1943    #[test]
1944    fn malformed_missing_return_is_err() {
1945        assert_parse_err("MATCH (n)");
1946    }
1947
1948    #[test]
1949    fn malformed_rel_colon_without_type_is_err() {
1950        assert_parse_err("MATCH (a)-[x:]->(b) RETURN a");
1951    }
1952
1953    #[test]
1954    fn malformed_dangling_comma_in_return_is_err() {
1955        assert_parse_err("MATCH (n) RETURN n,");
1956    }
1957
1958    #[test]
1959    fn malformed_unclosed_paren_is_err() {
1960        assert_parse_err("MATCH (n RETURN n");
1961        assert_parse_err("MATCH (n) WHERE (a.x = 1 RETURN n");
1962    }
1963
1964    #[test]
1965    fn malformed_order_by_before_return_is_err() {
1966        assert_parse_err("MATCH (n) ORDER BY n RETURN n");
1967    }
1968
1969    #[test]
1970    fn malformed_garbage_after_limit_is_err() {
1971        assert_parse_err("MATCH (n) RETURN n LIMIT 1 extra");
1972    }
1973
1974    #[test]
1975    fn dogfood_query_exact_ast() {
1976        let src = "\
1977MATCH (t:Talent {id: $tid}) \
1978MATCH (c:Company)-[i:INDUSTRY_ALIGNMENT]->(t) \
1979MATCH (c)-[s:SPECIALTY_MATCH]->(t) \
1980WHERE i.score >= 0.5 AND s.score >= 0.5 \
1981RETURN c, i.score AS industry, s.score AS specialty \
1982ORDER BY industry DESC, specialty DESC \
1983LIMIT 10";
1984        let got = parse_src(src).expect("dogfood query must parse");
1985        let expected = Query {
1986            matches: vec![
1987                Pattern {
1988                    start: node(
1989                        Some("t"),
1990                        Some("Talent"),
1991                        vec![("id".into(), Operand::Param("tid".into()))],
1992                    ),
1993                    chain: vec![],
1994                    shortest: false,
1995                },
1996                Pattern {
1997                    start: node(Some("c"), Some("Company"), vec![]),
1998                    chain: vec![(
1999                        RelPat {
2000                            var: Some("i".into()),
2001                            etypes: vec!["INDUSTRY_ALIGNMENT".into()],
2002                            dir: RelDir::Right,
2003                            hops: None,
2004                        },
2005                        node(Some("t"), None, vec![]),
2006                    )],
2007                    shortest: false,
2008                },
2009                Pattern {
2010                    start: node(Some("c"), None, vec![]),
2011                    chain: vec![(
2012                        RelPat {
2013                            var: Some("s".into()),
2014                            etypes: vec!["SPECIALTY_MATCH".into()],
2015                            dir: RelDir::Right,
2016                            hops: None,
2017                        },
2018                        node(Some("t"), None, vec![]),
2019                    )],
2020                    shortest: false,
2021                },
2022            ],
2023            optional_clauses: vec![],
2024            unwinds: vec![],
2025            post_unwind_where: None,
2026            where_expr: Some(Expr::And(
2027                Box::new(cmp(
2028                    prop("i", "score"),
2029                    CmpOp::Ge,
2030                    Operand::Lit(Value::Float(0.5)),
2031                )),
2032                Box::new(cmp(
2033                    prop("s", "score"),
2034                    CmpOp::Ge,
2035                    Operand::Lit(Value::Float(0.5)),
2036                )),
2037            )),
2038            stages: vec![],
2039            returns: vec![
2040                RetItem {
2041                    value: RetVal::Var("c".into()),
2042                    alias: None,
2043                },
2044                RetItem {
2045                    value: RetVal::Prop {
2046                        var: "i".into(),
2047                        field: "score".into(),
2048                    },
2049                    alias: Some("industry".into()),
2050                },
2051                RetItem {
2052                    value: RetVal::Prop {
2053                        var: "s".into(),
2054                        field: "score".into(),
2055                    },
2056                    alias: Some("specialty".into()),
2057                },
2058            ],
2059            order_by: vec![
2060                OrderItem {
2061                    target: OrderTarget::Alias("industry".into()),
2062                    descending: true,
2063                },
2064                OrderItem {
2065                    target: OrderTarget::Alias("specialty".into()),
2066                    descending: true,
2067                },
2068            ],
2069            distinct: false,
2070            skip: None,
2071            limit: Some(LimitSkip::Exact(10)),
2072        };
2073        assert_eq!(got, expected);
2074    }
2075
2076    #[test]
2077    fn unary_minus_in_props_and_dash_elsewhere_is_err() {
2078        let q = parse_src("MATCH (a {x: -5, y: -1.5}) RETURN a").unwrap();
2079        assert_eq!(
2080            q.matches[0].start.props,
2081            vec![
2082                ("x".into(), Operand::Lit(Value::Int(-5))),
2083                ("y".into(), Operand::Lit(Value::Float(-1.5))),
2084            ]
2085        );
2086        // `1 - 2` is now valid arithmetic — no longer a parse error.
2087        let q2 = parse_src("MATCH (a) WHERE a.x = 1 - 2 RETURN a").unwrap();
2088        assert!(q2.where_expr.is_some());
2089        // Unary minus on non-literal remains an error.
2090        assert_parse_err("MATCH (a) WHERE a.x > -b.y RETURN a");
2091        assert_parse_err("MATCH (a) RETURN a SKIP -1");
2092    }
2093
2094    // ── IS NULL / IS NOT NULL ──────────────────────────────────────────────────
2095
2096    #[test]
2097    fn is_null_parses_on_prop() {
2098        let q = parse_src("MATCH (a) WHERE a.x IS NULL RETURN a").unwrap();
2099        assert_eq!(q.where_expr, Some(Expr::IsNull(prop("a", "x"))),);
2100    }
2101
2102    #[test]
2103    fn is_not_null_parses_on_prop() {
2104        let q = parse_src("MATCH (a) WHERE a.x IS NOT NULL RETURN a").unwrap();
2105        assert_eq!(q.where_expr, Some(Expr::IsNotNull(prop("a", "x"))),);
2106    }
2107
2108    #[test]
2109    fn is_null_on_var() {
2110        let q =
2111            parse_src("MATCH (a) OPTIONAL MATCH (a)-[:T]->(b) WITH a, b WHERE b IS NULL RETURN a")
2112                .unwrap();
2113        // The IS NULL filter lives on the first WITH stage's where_expr.
2114        let stage = &q.stages[0];
2115        assert_eq!(
2116            stage.where_expr,
2117            Some(Expr::IsNull(Operand::Var("b".into()))),
2118        );
2119    }
2120
2121    #[test]
2122    fn is_null_case_insensitive() {
2123        let q = parse_src("MATCH (a) WHERE a.x is null RETURN a").unwrap();
2124        assert_eq!(q.where_expr, Some(Expr::IsNull(prop("a", "x"))));
2125        let q2 = parse_src("MATCH (a) WHERE a.x IS NOT NULL RETURN a").unwrap();
2126        assert_eq!(q2.where_expr, Some(Expr::IsNotNull(prop("a", "x"))));
2127    }
2128
2129    #[test]
2130    fn is_null_combined_with_and() {
2131        let q = parse_src("MATCH (a) WHERE a.x IS NULL AND a.y > 5 RETURN a").unwrap();
2132        assert!(matches!(q.where_expr, Some(Expr::And(_, _))));
2133    }
2134
2135    // ── Arithmetic expression parsing ──────────────────────────────────────────
2136
2137    #[test]
2138    fn arith_add_in_where() {
2139        use crate::cypher::ast::ArithOp;
2140        let q = parse_src("MATCH (n) WHERE n.age + 1 > 5 RETURN n").unwrap();
2141        let expected_lhs = Operand::BinArith {
2142            op: ArithOp::Add,
2143            left: Box::new(prop("n", "age")),
2144            right: Box::new(Operand::Lit(Value::Int(1))),
2145        };
2146        assert_eq!(
2147            q.where_expr,
2148            Some(Expr::Cmp {
2149                lhs: expected_lhs,
2150                op: CmpOp::Gt,
2151                rhs: Operand::Lit(Value::Int(5)),
2152            })
2153        );
2154    }
2155
2156    #[test]
2157    fn arith_precedence_mul_over_add() {
2158        use crate::cypher::ast::ArithOp;
2159        // 1 + 2 * 3  should parse as  1 + (2 * 3)
2160        let q = parse_src("MATCH (n) WHERE n.x = 1 + 2 * 3 RETURN n").unwrap();
2161        let expected_rhs = Operand::BinArith {
2162            op: ArithOp::Add,
2163            left: Box::new(Operand::Lit(Value::Int(1))),
2164            right: Box::new(Operand::BinArith {
2165                op: ArithOp::Mul,
2166                left: Box::new(Operand::Lit(Value::Int(2))),
2167                right: Box::new(Operand::Lit(Value::Int(3))),
2168            }),
2169        };
2170        assert_eq!(
2171            q.where_expr,
2172            Some(Expr::Cmp {
2173                lhs: prop("n", "x"),
2174                op: CmpOp::Eq,
2175                rhs: expected_rhs,
2176            })
2177        );
2178    }
2179
2180    #[test]
2181    fn arith_parens_override_precedence() {
2182        use crate::cypher::ast::ArithOp;
2183        // In RETURN position: (1+2)*3 should parse as (1+2)*3
2184        let q = parse_src("MATCH (n) RETURN (1 + 2) * 3 AS r").unwrap();
2185        let expected = RetVal::ScalarExpr(Operand::BinArith {
2186            op: ArithOp::Mul,
2187            left: Box::new(Operand::BinArith {
2188                op: ArithOp::Add,
2189                left: Box::new(Operand::Lit(Value::Int(1))),
2190                right: Box::new(Operand::Lit(Value::Int(2))),
2191            }),
2192            right: Box::new(Operand::Lit(Value::Int(3))),
2193        });
2194        assert_eq!(q.returns[0].value, expected);
2195        assert_eq!(q.returns[0].alias, Some("r".into()));
2196    }
2197
2198    #[test]
2199    fn arith_scalar_expr_in_return() {
2200        use crate::cypher::ast::ArithOp;
2201        let q = parse_src("MATCH (n) RETURN n.age + 1 AS adjusted").unwrap();
2202        let expected = RetVal::ScalarExpr(Operand::BinArith {
2203            op: ArithOp::Add,
2204            left: Box::new(prop("n", "age")),
2205            right: Box::new(Operand::Lit(Value::Int(1))),
2206        });
2207        assert_eq!(q.returns[0].value, expected);
2208        assert_eq!(q.returns[0].alias, Some("adjusted".into()));
2209    }
2210
2211    #[test]
2212    fn arith_div_in_where() {
2213        use crate::cypher::ast::ArithOp;
2214        let q = parse_src("MATCH (n) WHERE n.x / 2 > 3 RETURN n").unwrap();
2215        assert!(matches!(
2216            q.where_expr,
2217            Some(Expr::Cmp {
2218                lhs: Operand::BinArith {
2219                    op: ArithOp::Div,
2220                    ..
2221                },
2222                ..
2223            })
2224        ));
2225    }
2226
2227    // ── CREATE...RETURN and MERGE...RETURN parser tests ────────────────────────
2228
2229    #[test]
2230    fn create_return_parses_node_var() {
2231        use super::parse_write;
2232        use crate::cypher::ast::{RetVal, WriteStatement};
2233
2234        let toks = crate::cypher::lex("CREATE (n:Thing {id: 'x'}) RETURN n").unwrap();
2235        let stmt = parse_write(&toks).unwrap();
2236        match stmt {
2237            WriteStatement::Create(s) => {
2238                assert_eq!(s.nodes.len(), 1);
2239                let returns = s.returns.expect("expected RETURN clause");
2240                assert_eq!(returns.len(), 1);
2241                assert_eq!(returns[0].value, RetVal::Var("n".into()));
2242            }
2243            _ => panic!("expected Create"),
2244        }
2245    }
2246
2247    #[test]
2248    fn create_return_prop_with_alias() {
2249        use super::parse_write;
2250        use crate::cypher::ast::{RetVal, WriteStatement};
2251
2252        let toks = crate::cypher::lex("CREATE (n:Thing {id: 'x'}) RETURN n.id AS node_id").unwrap();
2253        let stmt = parse_write(&toks).unwrap();
2254        match stmt {
2255            WriteStatement::Create(s) => {
2256                let returns = s.returns.expect("RETURN required");
2257                assert_eq!(
2258                    returns[0].value,
2259                    RetVal::Prop {
2260                        var: "n".into(),
2261                        field: "id".into()
2262                    }
2263                );
2264                assert_eq!(returns[0].alias, Some("node_id".into()));
2265            }
2266            _ => panic!("expected Create"),
2267        }
2268    }
2269
2270    #[test]
2271    fn merge_return_parses_node_var() {
2272        use super::parse_write;
2273        use crate::cypher::ast::{RetVal, WriteStatement};
2274
2275        let toks = crate::cypher::lex("MERGE (n:Thing {id: 'x'}) RETURN n").unwrap();
2276        let stmt = parse_write(&toks).unwrap();
2277        match stmt {
2278            WriteStatement::Merge(s) => {
2279                assert_eq!(s.var, Some("n".into()));
2280                let returns = s.returns.expect("RETURN required");
2281                assert_eq!(returns[0].value, RetVal::Var("n".into()));
2282            }
2283            _ => panic!("expected Merge"),
2284        }
2285    }
2286
2287    #[test]
2288    fn is_write_tokens_still_true_for_create_return() {
2289        use super::is_write_tokens;
2290        use crate::cypher::lex;
2291
2292        let toks = lex("CREATE (n:T {id: 'x'}) RETURN n").unwrap();
2293        assert!(
2294            is_write_tokens(&toks),
2295            "CREATE...RETURN must still be classified as write"
2296        );
2297    }
2298
2299    #[test]
2300    fn where_in_list_and_param_parses() {
2301        let q = parse_src("MATCH (n) WHERE n.city IN ['Austin', $c] RETURN n").unwrap();
2302        match q.where_expr {
2303            Some(Expr::In { expr, list }) => {
2304                assert_eq!(
2305                    expr,
2306                    Operand::Prop {
2307                        var: "n".into(),
2308                        field: "city".into()
2309                    }
2310                );
2311                assert_eq!(list.len(), 2);
2312                assert_eq!(list[0], Operand::Lit(Value::Str("Austin".into())));
2313                assert_eq!(list[1], Operand::Param("c".into()));
2314            }
2315            other => panic!("expected Expr::In, got {other:?}"),
2316        }
2317        let q2 = parse_src("MATCH (n) WHERE n.city IN $cities RETURN n").unwrap();
2318        match q2.where_expr {
2319            Some(Expr::In { list, .. }) => {
2320                assert_eq!(list, vec![Operand::Param("cities".into())]);
2321            }
2322            other => panic!("expected Expr::In, got {other:?}"),
2323        }
2324    }
2325
2326    #[test]
2327    fn return_distinct_parses() {
2328        let q = parse_src("MATCH (n) RETURN DISTINCT n.city").unwrap();
2329        assert!(q.distinct);
2330        assert_eq!(q.returns.len(), 1);
2331    }
2332
2333    #[test]
2334    fn union_query_parses_into_parts() {
2335        use super::parse_read;
2336        let u = parse_read(&lex("MATCH (n) RETURN n UNION ALL MATCH (m) RETURN m").unwrap())
2337            .expect("UNION parses");
2338        assert_eq!(u.parts.len(), 2);
2339        assert_eq!(u.all_flags, vec![true]);
2340        // A single query yields one part, no boundaries.
2341        let single = parse_read(&lex("MATCH (n) RETURN n").unwrap()).unwrap();
2342        assert_eq!(single.parts.len(), 1);
2343        assert!(single.all_flags.is_empty());
2344    }
2345
2346    #[test]
2347    fn case_when_expression_parses() {
2348        let q = parse_src("MATCH (n) RETURN CASE WHEN n.x = 1 THEN 2 ELSE 3 END AS c")
2349            .expect("CASE parses");
2350        assert!(matches!(
2351            q.returns[0].value,
2352            RetVal::ScalarExpr(Operand::Case { .. })
2353        ));
2354    }
2355
2356    #[test]
2357    fn collect_is_a_supported_aggregate() {
2358        let q = parse_src("MATCH (n) RETURN collect(n.name) AS names").expect("collect parses");
2359        assert!(matches!(
2360            q.returns[0].value,
2361            RetVal::Agg {
2362                func: AggFunc::Collect,
2363                ..
2364            }
2365        ));
2366    }
2367
2368    #[test]
2369    fn match_set_return_parses() {
2370        use super::parse_write;
2371        use crate::cypher::ast::{RetVal, WriteStatement};
2372
2373        let toks = crate::cypher::lex("MATCH (n {id:'a'}) SET n.x = 2 RETURN n.x").unwrap();
2374        let stmt = parse_write(&toks).unwrap();
2375        match stmt {
2376            WriteStatement::MatchSet(s) => {
2377                let returns = s.returns.expect("RETURN required");
2378                assert_eq!(
2379                    returns[0].value,
2380                    RetVal::Prop {
2381                        var: "n".into(),
2382                        field: "x".into()
2383                    }
2384                );
2385            }
2386            other => panic!("expected MatchSet, got {other:?}"),
2387        }
2388    }
2389
2390    #[test]
2391    fn merge_on_create_and_on_match_parse() {
2392        use super::parse_write;
2393        use crate::cypher::ast::WriteStatement;
2394
2395        let toks = crate::cypher::lex(
2396            "MERGE (n:L {id:'new'}) ON CREATE SET n.born = 1 ON MATCH SET n.hit = 1 RETURN n",
2397        )
2398        .unwrap();
2399        let stmt = parse_write(&toks).unwrap();
2400        match stmt {
2401            WriteStatement::Merge(s) => {
2402                assert_eq!(s.on_create.len(), 1);
2403                assert_eq!(s.on_create[0].field, "born");
2404                assert_eq!(s.on_match.len(), 1);
2405                assert_eq!(s.on_match[0].field, "hit");
2406                assert!(s.returns.is_some());
2407            }
2408            other => panic!("expected Merge, got {other:?}"),
2409        }
2410    }
2411
2412    #[test]
2413    fn paren_grouping_and_and_left_assoc() {
2414        let q = parse_src("MATCH (a) WHERE (a.x = 1 OR a.y = 2) AND a.z = 3 RETURN a").unwrap();
2415        let expected = Expr::And(
2416            Box::new(Expr::Or(
2417                Box::new(cmp(prop("a", "x"), CmpOp::Eq, Operand::Lit(Value::Int(1)))),
2418                Box::new(cmp(prop("a", "y"), CmpOp::Eq, Operand::Lit(Value::Int(2)))),
2419            )),
2420            Box::new(cmp(prop("a", "z"), CmpOp::Eq, Operand::Lit(Value::Int(3)))),
2421        );
2422        assert_eq!(q.where_expr, Some(expected));
2423
2424        let q = parse_src("MATCH (a) WHERE a.x = 1 AND a.y = 2 AND a.z = 3 RETURN a").unwrap();
2425        let expected = Expr::And(
2426            Box::new(Expr::And(
2427                Box::new(cmp(prop("a", "x"), CmpOp::Eq, Operand::Lit(Value::Int(1)))),
2428                Box::new(cmp(prop("a", "y"), CmpOp::Eq, Operand::Lit(Value::Int(2)))),
2429            )),
2430            Box::new(cmp(prop("a", "z"), CmpOp::Eq, Operand::Lit(Value::Int(3)))),
2431        );
2432        assert_eq!(q.where_expr, Some(expected));
2433    }
2434
2435    #[test]
2436    fn order_by_bare_ident_is_var_when_not_an_alias() {
2437        let q = parse_src("MATCH (a) RETURN a, b.name ORDER BY a, b.name").unwrap();
2438        assert_eq!(
2439            q.order_by,
2440            vec![
2441                OrderItem {
2442                    target: OrderTarget::Var("a".into()),
2443                    descending: false,
2444                },
2445                OrderItem {
2446                    target: OrderTarget::Prop {
2447                        var: "b".into(),
2448                        field: "name".into(),
2449                    },
2450                    descending: false,
2451                },
2452            ]
2453        );
2454    }
2455
2456    #[test]
2457    fn parse_never_panics_on_token_sequences() {
2458        let sequences: Vec<Vec<Tok>> = vec![
2459            vec![],
2460            vec![Tok::Match],
2461            vec![Tok::Return],
2462            vec![Tok::Dash, Tok::Dash, Tok::Dash],
2463            vec![Tok::Lt, Tok::Gt, Tok::Eq],
2464            vec![Tok::LParen, Tok::RParen, Tok::RParen],
2465            vec![Tok::Int(1), Tok::Float(2.0), Tok::Str("x".into())],
2466            vec![Tok::Where, Tok::Not, Tok::And, Tok::Or],
2467            vec![Tok::Order, Tok::By, Tok::Asc, Tok::Desc],
2468            vec![Tok::Skip, Tok::Limit, Tok::As],
2469            vec![Tok::Ident("n".into()), Tok::Dot, Tok::Ident("x".into())],
2470            vec![Tok::Param("p".into()), Tok::Colon, Tok::Comma],
2471            vec![Tok::LBracket, Tok::RBracket, Tok::LBrace, Tok::RBrace],
2472            lex("MATCH (a)-[x:]->(b) RETURN a ORDER BY a LIMIT 1 extra").unwrap(),
2473            // Aggregate tokens: COUNT(*), SUM/AVG/MIN/MAX in various positions.
2474            vec![
2475                Tok::Ident("COUNT".into()),
2476                Tok::LParen,
2477                Tok::Star,
2478                Tok::RParen,
2479            ],
2480            vec![
2481                Tok::Ident("sum".into()),
2482                Tok::LParen,
2483                Tok::Ident("n".into()),
2484                Tok::Dot,
2485                Tok::Ident("x".into()),
2486                Tok::RParen,
2487            ],
2488            vec![Tok::Star],
2489            vec![Tok::Star, Tok::LParen, Tok::RParen, Tok::Star],
2490            vec![
2491                Tok::Ident("avg".into()),
2492                Tok::LParen,
2493                Tok::Star,
2494                Tok::RParen,
2495            ],
2496            vec![Tok::Ident("min".into()), Tok::LParen, Tok::RParen],
2497            vec![
2498                Tok::Ident("max".into()),
2499                Tok::LParen,
2500                Tok::Star,
2501                Tok::RParen,
2502            ],
2503        ];
2504        for toks in sequences {
2505            let result = std::panic::catch_unwind(|| parse(&toks));
2506            assert!(result.is_ok(), "parse panicked on token sequence {toks:?}");
2507            let parsed = result.unwrap();
2508            if let Err(err) = parsed {
2509                assert!(
2510                    err.contains("token"),
2511                    "error must include token position, got: {err}"
2512                );
2513            }
2514        }
2515    }
2516
2517    #[test]
2518    fn aggregate_functions_parse_to_agg_retval() {
2519        use crate::cypher::ast::{AggArg, AggFunc, RetVal};
2520
2521        // COUNT(*) → AggFunc::Count, AggArg::Star
2522        let q = parse_src("MATCH (n) RETURN COUNT(*)").unwrap();
2523        assert_eq!(q.returns.len(), 1);
2524        assert_eq!(
2525            q.returns[0].value,
2526            RetVal::Agg {
2527                func: AggFunc::Count,
2528                arg: AggArg::Star,
2529            }
2530        );
2531        assert_eq!(q.returns[0].alias, None);
2532
2533        // COUNT(n) → AggFunc::Count, AggArg::Var
2534        let q = parse_src("MATCH (n) RETURN COUNT(n)").unwrap();
2535        assert_eq!(
2536            q.returns[0].value,
2537            RetVal::Agg {
2538                func: AggFunc::Count,
2539                arg: AggArg::Var("n".into()),
2540            }
2541        );
2542
2543        // SUM(n.age) → AggFunc::Sum, AggArg::Prop
2544        let q = parse_src("MATCH (n) RETURN SUM(n.age) AS total").unwrap();
2545        assert_eq!(
2546            q.returns[0].value,
2547            RetVal::Agg {
2548                func: AggFunc::Sum,
2549                arg: AggArg::Prop {
2550                    var: "n".into(),
2551                    field: "age".into()
2552                },
2553            }
2554        );
2555        assert_eq!(q.returns[0].alias, Some("total".into()));
2556
2557        // AVG, MIN, MAX case-insensitive
2558        let q = parse_src("MATCH (n) RETURN avg(n.score)").unwrap();
2559        assert!(matches!(
2560            q.returns[0].value,
2561            RetVal::Agg {
2562                func: AggFunc::Avg,
2563                ..
2564            }
2565        ));
2566        let q = parse_src("MATCH (n) RETURN Min(n.x)").unwrap();
2567        assert!(matches!(
2568            q.returns[0].value,
2569            RetVal::Agg {
2570                func: AggFunc::Min,
2571                ..
2572            }
2573        ));
2574        let q = parse_src("MATCH (n) RETURN MAX(n.x)").unwrap();
2575        assert!(matches!(
2576            q.returns[0].value,
2577            RetVal::Agg {
2578                func: AggFunc::Max,
2579                ..
2580            }
2581        ));
2582    }
2583
2584    #[test]
2585    fn nested_parens_beyond_limit_is_err_not_panic() {
2586        let mut src = String::from("MATCH (a) WHERE ");
2587        for _ in 0..80 {
2588            src.push('(');
2589        }
2590        src.push_str("a.x = 1");
2591        for _ in 0..80 {
2592            src.push(')');
2593        }
2594        src.push_str(" RETURN a");
2595        assert_parse_err(&src);
2596    }
2597
2598    // ── Variable-length path parser tests ─────────────────────────────────────
2599
2600    fn hop_range_of(src: &str) -> HopRange {
2601        let q = parse_src(src).expect(src);
2602        let (rel, _) = &q.matches[0].chain[0];
2603        rel.hops.expect("expected hop range")
2604    }
2605
2606    fn assert_hop_err(src: &str, needle: &str) {
2607        let result = std::panic::catch_unwind(|| parse_src(src));
2608        assert!(result.is_ok(), "parse panicked on {src:?}");
2609        let err = result
2610            .unwrap()
2611            .expect_err(&format!("parse({src:?}) must Err"));
2612        assert!(
2613            err.contains(needle),
2614            "error must contain {needle:?}, got: {err}"
2615        );
2616    }
2617
2618    #[test]
2619    fn var_length_bare_star_is_one_to_ten() {
2620        let r = hop_range_of("MATCH (a)-[r:T*]->(b) RETURN a");
2621        assert_eq!(r, HopRange { min: 1, max: 10 });
2622    }
2623
2624    #[test]
2625    fn var_length_exact_n_hops() {
2626        let r = hop_range_of("MATCH (a)-[r:T*3]->(b) RETURN a");
2627        assert_eq!(r, HopRange { min: 3, max: 3 });
2628    }
2629
2630    #[test]
2631    fn var_length_min_max_range() {
2632        let r = hop_range_of("MATCH (a)-[r:T*2..5]->(b) RETURN a");
2633        assert_eq!(r, HopRange { min: 2, max: 5 });
2634    }
2635
2636    #[test]
2637    fn var_length_dotdot_max() {
2638        let r = hop_range_of("MATCH (a)-[r:T*..4]->(b) RETURN a");
2639        assert_eq!(r, HopRange { min: 1, max: 4 });
2640    }
2641
2642    #[test]
2643    fn var_length_cap_at_ten_is_ok() {
2644        let r = hop_range_of("MATCH (a)-[r:T*10]->(b) RETURN a");
2645        assert_eq!(r, HopRange { min: 10, max: 10 });
2646        let r2 = hop_range_of("MATCH (a)-[r:T*1..10]->(b) RETURN a");
2647        assert_eq!(r2, HopRange { min: 1, max: 10 });
2648    }
2649
2650    #[test]
2651    fn var_length_cap_exceeded_is_err() {
2652        assert_hop_err(
2653            "MATCH (a)-[r:T*11]->(b) RETURN a",
2654            "variable-length paths are capped at 10 hops",
2655        );
2656        assert_hop_err(
2657            "MATCH (a)-[r:T*1..11]->(b) RETURN a",
2658            "variable-length paths are capped at 10 hops",
2659        );
2660    }
2661
2662    #[test]
2663    fn var_length_unbounded_min_dot_dot_is_err() {
2664        assert_hop_err(
2665            "MATCH (a)-[r:T*2..]->(b) RETURN a",
2666            "variable-length paths are capped at 10 hops",
2667        );
2668    }
2669
2670    #[test]
2671    fn var_length_shortest_path_parses() {
2672        let q =
2673            parse_src("MATCH (a:N) MATCH (b:N) MATCH shortestPath((a)-[r:T*..5]->(b)) RETURN a")
2674                .expect("shortestPath must parse");
2675        assert!(q.matches[2].shortest, "third match must be shortest=true");
2676        let (rel, _) = &q.matches[2].chain[0];
2677        assert_eq!(rel.hops, Some(HopRange { min: 1, max: 5 }));
2678        assert_eq!(rel.etypes, vec!["T".to_string()]);
2679    }
2680
2681    #[test]
2682    fn var_length_no_type_is_ok() {
2683        // Bare `*` with no type filter
2684        let r = hop_range_of("MATCH (a)-[r*1..3]->(b) RETURN a");
2685        assert_eq!(r, HopRange { min: 1, max: 3 });
2686    }
2687
2688    #[test]
2689    fn var_length_rel_appears_in_chain() {
2690        let q = parse_src("MATCH (a)-[r:T*2..4]->(b) RETURN a").unwrap();
2691        let (rel, dest) = &q.matches[0].chain[0];
2692        assert_eq!(rel.var.as_deref(), Some("r"));
2693        assert_eq!(rel.etypes, vec!["T".to_string()]);
2694        assert_eq!(rel.dir, RelDir::Right);
2695        assert_eq!(rel.hops, Some(HopRange { min: 2, max: 4 }));
2696        assert_eq!(dest.var.as_deref(), Some("b"));
2697    }
2698
2699    #[test]
2700    fn var_length_zero_hop_minimum_is_err() {
2701        // `*0` — exact form with min=0
2702        assert_hop_err(
2703            "MATCH (a)-[r:T*0]->(b) RETURN a",
2704            "zero-length variable-length paths are not supported",
2705        );
2706        // `*0..3` — range form with min=0
2707        assert_hop_err(
2708            "MATCH (a)-[r:T*0..3]->(b) RETURN a",
2709            "zero-length variable-length paths are not supported",
2710        );
2711    }
2712
2713    #[test]
2714    fn create_accepts_list_literal_property() {
2715        use super::parse_write;
2716        use crate::cypher::ast::WriteStatement;
2717        let src = "CREATE (n:Person {id: 'p1', tags: ['a', 'b']})";
2718        let stmt = parse_write(&lex(src).unwrap())
2719            .expect("CREATE with a list-literal property must parse");
2720        let WriteStatement::Create(c) = stmt else {
2721            panic!("expected a Create statement");
2722        };
2723        let tags = &c.nodes[0]
2724            .props
2725            .iter()
2726            .find(|(k, _)| k == "tags")
2727            .expect("tags property present")
2728            .1;
2729        assert_eq!(
2730            *tags,
2731            Value::List(vec![Value::Str("a".into()), Value::Str("b".into())])
2732        );
2733    }
2734
2735    #[test]
2736    fn create_accepts_empty_and_nested_list_literals() {
2737        use super::parse_write;
2738        use crate::cypher::ast::WriteStatement;
2739        let src = "CREATE (n:L {id: 'p1', empty: [], nested: [[1, 2], [3]]})";
2740        let stmt = parse_write(&lex(src).unwrap()).expect("empty and nested lists must parse");
2741        let WriteStatement::Create(c) = stmt else {
2742            panic!("expected a Create statement");
2743        };
2744        let get = |k: &str| {
2745            c.nodes[0]
2746                .props
2747                .iter()
2748                .find(|(name, _)| name == k)
2749                .expect("property present")
2750                .1
2751                .clone()
2752        };
2753        assert_eq!(get("empty"), Value::List(vec![]));
2754        assert_eq!(
2755            get("nested"),
2756            Value::List(vec![
2757                Value::List(vec![Value::Int(1), Value::Int(2)]),
2758                Value::List(vec![Value::Int(3)]),
2759            ])
2760        );
2761    }
2762
2763    #[test]
2764    fn set_accepts_list_literal_rhs() {
2765        use super::parse_write;
2766        use crate::cypher::ast::{Operand, WriteStatement};
2767        let src = "MATCH (n:Person {id: 'p1'}) SET n.tags = ['x', 'y']";
2768        let stmt = parse_write(&lex(src).unwrap()).expect("SET with a list-literal RHS must parse");
2769        let WriteStatement::MatchSet(m) = stmt else {
2770            panic!("expected a MatchSet statement");
2771        };
2772        let set = &m.sets[0];
2773        assert_eq!(set.field, "tags");
2774        assert_eq!(
2775            set.value,
2776            Operand::Lit(Value::List(vec![
2777                Value::Str("x".into()),
2778                Value::Str("y".into())
2779            ]))
2780        );
2781    }
2782}