Skip to main content

marsdb_query/
antlr_visitor.rs

1// `AstBuilder`/`AstNode` internals stay unused-by-external-code from
2// rustc's perspective even though `parse_antlr` (this file's real public
3// entry point, re-exported as `lib.rs`'s `parse`/`parse_many`) exercises
4// them at runtime -- the visitor trait's `visit_X` overrides are only
5// ever called through dynamic dispatch (`accept()`), which rustc's
6// dead-code analysis can't see through.
7#![allow(dead_code)]
8
9//! ANTLR-based AST builder -- replaced the old pest-tree-walk
10//! (`parser.rs`/`cypher.pest`, deleted at cutover) as this
11//! crate's real Cypher parser. `parse_antlr`/`parse_antlr_many` are
12//! re-exported by `lib.rs` as `parse`/`parse_many`.
13//!
14//! Implements the generated `CypherParserVisitorCompat` trait rather than
15//! manually walking context accessors: ANTLR's own `accept()`/`visit()`
16//! double-dispatch already routes to the right `visit_X` method for
17//! whichever grammar alternative is actually present, so alternation
18//! (`literal : boolLit | numLit | NULL_W | stringLit | charLit | listLit
19//! | mapLit`) doesn't need a hand-written `if let Some(x) = ctx.boolLit()
20//! ... else if ...` chain -- only `visit_literal` needs a one-line manual
21//! check, for the bare `NULL_W` terminal alternative specifically (a
22//! terminal has no grammar-rule `visit_X` hook of its own to override).
23//!
24//! `Return` (via [`AstNode`]) is one shared enum across the whole
25//! visitor -- required by `ParseTreeVisitorCompat`, which supports
26//! exactly one `Return` type for the entire tree walk, not a per-rule
27//! type. Grows a variant per AST node kind as later increments need it.
28
29use crate::ast::{
30    is_aggregate_name, ArithOp, CallClause, CallYield, CompareOp, Expr, Literal, MergeClause,
31    NodePattern, Pattern, PropAccess, QuantifierKind, QueryClause, QueryPart, RelDirection,
32    RelPattern, RemoveItem, ReturnExpr, ReturnItem, ReturnTail, SetItem, SortDir, Statement, Tail,
33    UnwindClause, UnwindSource, WithClause, WithExpr,
34};
35use crate::error::QueryError;
36use crate::generated::cypherparser::{
37    AddSubExpressionContext, AndExpressionContext, AndExpressionContextAttrs, AtomContext,
38    AtomContextAttrs, AtomicExpressionContext, AtomicExpressionContextAll,
39    AtomicExpressionContextAttrs, BoolLitContext, BoolLitContextAttrs, CaseExpressionContext,
40    CharLitContext, CharLitContextAttrs, ComparisonExpressionContext,
41    ComparisonExpressionContextAttrs, ComparisonSignsContextAll, ComparisonSignsContextAttrs,
42    CountAllContext, CreateIndexStContext, CreateIndexStContextAttrs, CreateStContext,
43    CreateStContextAttrs, DeleteStContext, DeleteStContextAttrs, ExplainStContext,
44    ExplainStContextAttrs, ExpressionChainContextAttrs, ExpressionContext, ExpressionContextAttrs,
45    FilterExpressionContext, FilterExpressionContextAttrs, FilterWithContext,
46    FilterWithContextAttrs, FunctionInvocationContext, FunctionInvocationContextAttrs,
47    InExpressionContextAttrs, InvocationNameContextAll, InvocationNameContextAttrs,
48    LhsContextAttrs, LimitStContextAttrs, ListComprehensionContext, ListComprehensionContextAttrs,
49    ListExpressionContextAll, ListExpressionContextAttrs, ListLitContext, ListLitContextAttrs,
50    LiteralContext, LiteralContextAttrs, MapLitContext, MapLitContextAttrs, MapPairContextAttrs,
51    MatchStContext, MatchStContextAttrs, MergeActionContextAll, MergeActionContextAttrs,
52    MergeStContext, MergeStContextAttrs, MultDivExpressionContext, MultiPartQContext,
53    MultiPartQContextAttrs, NameContextAll, NameContextAttrs, NodeLabelsContextAttrs,
54    NodePatternContext, NodePatternContextAttrs, NotExpressionContext, NotExpressionContextAttrs,
55    NullExpressionContextAttrs, NumLitContext, NumLitContextAll, NumLitContextAttrs,
56    OrderItemContextAttrs, OrderStContext, OrderStContextAttrs, ParameterContext,
57    ParameterContextAttrs, ParenExpressionChainContextAll, ParenExpressionChainContextAttrs,
58    ParenthesizedExpressionContext, ParenthesizedExpressionContextAttrs,
59    PatternComprehensionContext, PatternComprehensionContextAttrs, PatternContextAttrs,
60    PatternElemChainContextAttrs, PatternElemContext, PatternElemContextAttrs,
61    PatternPartContextAttrs, PatternWhereContextAttrs, PowerExpressionContext,
62    PowerExpressionContextAttrs, ProjectionBodyContext, ProjectionBodyContextAttrs,
63    ProjectionItemContextAttrs, ProjectionItemsContextAttrs, PropertiesContextAll,
64    PropertiesContextAttrs, PropertyExpressionContext, PropertyExpressionContextAttrs,
65    PropertyOrLabelExpressionContext, PropertyOrLabelExpressionContextAttrs, QueryCallStContextAll,
66    QueryCallStContextAttrs, ReadingStatementContextAll, ReadingStatementContextAttrs,
67    RegularQueryContext, RegularQueryContextAttrs, RelationDetailContext,
68    RelationDetailContextAttrs, RelationshipPatternContext, RelationshipPatternContextAttrs,
69    RelationshipTypesContextAttrs, RelationshipsChainPatternContext,
70    RelationshipsChainPatternContextAttrs, RemoveItemContextAll, RemoveItemContextAttrs,
71    RemoveStContext, RemoveStContextAttrs, ReturnStContext, ReturnStContextAttrs,
72    SetItemContextAll, SetItemContextAttrs, SetStContext, SetStContextAttrs,
73    ShortestPathWrapperContextAttrs, SinglePartQContext, SinglePartQContextAttrs,
74    SkipStContextAttrs, StandaloneCallContext, StandaloneCallContextAttrs,
75    StringExpPrefixContextAll, StringExpPrefixContextAttrs, StringExpressionContextAll,
76    StringExpressionContextAttrs, StringListNullExpressionContext,
77    StringListNullExpressionContextAttrs, StringLitContext, StringLitContextAttrs,
78    SubqueryExistContext, SubqueryExistContextAttrs, SymbolContextAll, SymbolContextAttrs,
79    UnaryAddSubExpressionContext, UnaryAddSubExpressionContextAttrs, UnionStContextAttrs,
80    UnwindStContext, UnwindStContextAttrs, UpdatingStatementContextAll,
81    UpdatingStatementContextAttrs, WhereContextAttrs, WithStContext, WithStContextAttrs,
82    XorExpressionContext, XorExpressionContextAttrs, YieldItemContextAttrs, YieldItemsContextAll,
83    YieldItemsContextAttrs,
84};
85use crate::generated::cypherparservisitor::CypherParserVisitorCompat;
86use crate::parse_helpers::{
87    group_into_linear_patterns, parse_int_literal, parse_rel_range, unescape_string,
88    validate_named_path_pattern, validate_shortest_path_pattern,
89};
90use antlr4rust::parser_rule_context::ParserRuleContext;
91use antlr4rust::token::Token;
92use antlr4rust::tree::{ParseTree, ParseTreeVisitorCompat, Tree};
93use std::rc::Rc;
94
95#[derive(Debug, Default)]
96pub(crate) enum AstNode {
97    #[default]
98    None,
99    Literal(Literal),
100    NodePattern(NodePattern),
101    RelPattern(RelPattern),
102    Pattern(Pattern),
103    QueryParts(Vec<QueryPart>),
104    ReturnExpr(ReturnExpr),
105    ReturnClause(ParsedReturnClause),
106    WithClause(WithClause),
107    UnwindClause(UnwindClause),
108    SetItems(Vec<SetItem>),
109    DeleteItems(ParsedDelete),
110    RemoveItems(Vec<RemoveItem>),
111    CreatePatterns(Vec<Pattern>),
112    MergeClause(MergeClause),
113    Statement(Statement),
114    Err(QueryError),
115}
116
117#[derive(Debug)]
118pub(crate) struct ParsedDelete {
119    pub items: Vec<ReturnExpr>,
120    pub detach: bool,
121}
122
123/// `returnSt`'s/`withSt`'s shared `projectionBody` bundles the item list,
124/// `DISTINCT`, `ORDER BY`, `SKIP`, and `LIMIT` together, but `Tail`
125/// (items + distinct) and `order_by`/`skip`/`limit` live at different
126/// levels of `ast::Statement::Match` (the latter three are statement-wide,
127/// not per-`Tail`) -- this carries all four out of the visitor together
128/// so the caller building `Statement::Match` can split them apart.
129#[derive(Debug)]
130pub(crate) struct ParsedReturnClause {
131    pub tail: Tail,
132    pub order_by: Option<Vec<(ReturnExpr, SortDir)>>,
133    pub skip: Option<ReturnExpr>,
134    pub limit: Option<ReturnExpr>,
135}
136
137macro_rules! ast_node_into {
138    ($name:ident, $variant:ident, $ty:ty) => {
139        fn $name(self) -> Result<$ty, QueryError> {
140            match self {
141                AstNode::$variant(v) => Ok(v),
142                AstNode::Err(e) => Err(e),
143                other => unreachable!("expected AstNode::{}, got {other:?}", stringify!($variant)),
144            }
145        }
146    };
147}
148
149impl AstNode {
150    ast_node_into!(into_literal, Literal, Literal);
151    ast_node_into!(into_node_pattern, NodePattern, NodePattern);
152    ast_node_into!(into_rel_pattern, RelPattern, RelPattern);
153    ast_node_into!(into_pattern, Pattern, Pattern);
154    ast_node_into!(into_query_parts, QueryParts, Vec<QueryPart>);
155    ast_node_into!(into_return_expr, ReturnExpr, ReturnExpr);
156
157    /// `ast::Literal` has no List/Map variant -- `listLit`/`mapLit` build
158    /// `ReturnExpr::ListLit`/`MapLit` directly instead (see
159    /// `visit_listLit`/`visit_mapLit`), so a `literal` context (reached
160    /// via `atom`, which can't tell in advance which of its 7 alternatives
161    /// it'll get) may resolve to either an `AstNode::Literal` (bool/num/
162    /// string/char/null) or an `AstNode::ReturnExpr` (list/map). This
163    /// accepts either, wrapping a bare `Literal` in `ReturnExpr::Lit`.
164    fn into_return_expr_lenient(self) -> Result<ReturnExpr, QueryError> {
165        match self {
166            AstNode::Literal(l) => Ok(ReturnExpr::Lit(l)),
167            AstNode::ReturnExpr(e) => Ok(e),
168            AstNode::Err(e) => Err(e),
169            other => {
170                unreachable!("expected AstNode::Literal or AstNode::ReturnExpr, got {other:?}")
171            }
172        }
173    }
174    ast_node_into!(into_return_clause, ReturnClause, ParsedReturnClause);
175    ast_node_into!(into_with_clause, WithClause, WithClause);
176    ast_node_into!(into_unwind_clause, UnwindClause, UnwindClause);
177    ast_node_into!(into_set_items, SetItems, Vec<SetItem>);
178    ast_node_into!(into_delete_items, DeleteItems, ParsedDelete);
179    ast_node_into!(into_remove_items, RemoveItems, Vec<RemoveItem>);
180    ast_node_into!(into_create_patterns, CreatePatterns, Vec<Pattern>);
181    ast_node_into!(into_merge_clause, MergeClause, MergeClause);
182    ast_node_into!(into_statement, Statement, Statement);
183}
184
185pub(crate) struct AstBuilder {
186    result: AstNode,
187}
188
189impl AstBuilder {
190    pub(crate) fn new() -> Self {
191        AstBuilder {
192            result: AstNode::default(),
193        }
194    }
195}
196
197impl<'input> ParseTreeVisitorCompat<'input> for AstBuilder {
198    type Node = crate::generated::cypherparser::CypherParserContextType;
199    type Return = AstNode;
200
201    fn temp_result(&mut self) -> &mut Self::Return {
202        &mut self.result
203    }
204}
205
206impl<'input> CypherParserVisitorCompat<'input> for AstBuilder {
207    fn visit_literal(&mut self, ctx: &LiteralContext<'input>) -> Self::Return {
208        // The only alternative that's a bare terminal, not a sub-rule --
209        // no `visit_X` grammar-rule hook exists to override for it, so it
210        // needs the one manual check `visit_children`'s default dispatch
211        // can't cover on its own.
212        if ctx.NULL_W().is_some() {
213            return AstNode::Literal(Literal::Null);
214        }
215        self.visit_children(ctx)
216    }
217
218    fn visit_boolLit(&mut self, ctx: &BoolLitContext<'input>) -> Self::Return {
219        AstNode::Literal(Literal::Bool(ctx.TRUE().is_some()))
220    }
221
222    /// The lexer's `DIGIT` token covers hex/octal/decimal integers *and*
223    /// floats in one token (`DIGIT : HexDigits | OctalDigits | Digits |
224    /// FLOAT;`), unlike pest's grammar which split `int_literal`/
225    /// `float_literal` into separate rules -- so int-vs-float is decided
226    /// from the raw text here instead of from which sub-rule matched.
227    /// Hex/octal integers can't contain `.`/exponent/`f`/`d` at all (the
228    /// lexer wouldn't have matched `DIGIT` as those alternatives if they
229    /// did), so checking for those unconditionally is safe and doesn't
230    /// misfire on e.g. `0xE` (a hex digit `E`, not a float exponent).
231    fn visit_numLit(&mut self, ctx: &NumLitContext<'input>) -> Self::Return {
232        let text = ctx
233            .DIGIT()
234            .expect("numLit context always has a DIGIT token")
235            .get_text();
236        match parse_num_lit_text(&text) {
237            Ok(lit) => AstNode::Literal(lit),
238            Err(e) => AstNode::Err(e),
239        }
240    }
241
242    fn visit_stringLit(&mut self, ctx: &StringLitContext<'input>) -> Self::Return {
243        let text = ctx
244            .STRING_LITERAL()
245            .expect("stringLit context always has a STRING_LITERAL token")
246            .get_text();
247        match unescape_string(&text[1..text.len() - 1]) {
248            Ok(s) => AstNode::Literal(Literal::String(s)),
249            Err(e) => AstNode::Err(e),
250        }
251    }
252
253    fn visit_charLit(&mut self, ctx: &CharLitContext<'input>) -> Self::Return {
254        let text = ctx
255            .CHAR_LITERAL()
256            .expect("charLit context always has a CHAR_LITERAL token")
257            .get_text();
258        match unescape_string(&text[1..text.len() - 1]) {
259            Ok(s) => AstNode::Literal(Literal::String(s)),
260            Err(e) => AstNode::Err(e),
261        }
262    }
263
264    fn visit_nodePattern(&mut self, ctx: &NodePatternContext<'input>) -> Self::Return {
265        match self.build_node_pattern(ctx) {
266            Ok(n) => AstNode::NodePattern(n),
267            Err(e) => AstNode::Err(e),
268        }
269    }
270
271    fn visit_relationDetail(&mut self, ctx: &RelationDetailContext<'input>) -> Self::Return {
272        match self.build_rel_detail(ctx) {
273            Ok(r) => AstNode::RelPattern(r),
274            Err(e) => AstNode::Err(e),
275        }
276    }
277
278    fn visit_relationshipPattern(
279        &mut self,
280        ctx: &RelationshipPatternContext<'input>,
281    ) -> Self::Return {
282        match self.build_relationship_pattern(ctx) {
283            Ok(r) => AstNode::RelPattern(r),
284            Err(e) => AstNode::Err(e),
285        }
286    }
287
288    fn visit_patternElem(&mut self, ctx: &PatternElemContext<'input>) -> Self::Return {
289        match self.build_pattern_elem(ctx) {
290            Ok(p) => AstNode::Pattern(p),
291            Err(e) => AstNode::Err(e),
292        }
293    }
294
295    fn visit_matchSt(&mut self, ctx: &MatchStContext<'input>) -> Self::Return {
296        match self.build_match_st(ctx) {
297            Ok(parts) => AstNode::QueryParts(parts),
298            Err(e) => AstNode::Err(e),
299        }
300    }
301
302    fn visit_expression(&mut self, ctx: &ExpressionContext<'input>) -> Self::Return {
303        let mut operands = ctx.xorExpression_all().into_iter();
304        let mut lhs = match self
305            .visit(
306                &*operands
307                    .next()
308                    .expect("expression has at least one xorExpression"),
309            )
310            .into_return_expr()
311        {
312            Ok(e) => e,
313            Err(e) => return AstNode::Err(e),
314        };
315        for rhs_ctx in operands {
316            let rhs = match self.visit(&*rhs_ctx).into_return_expr() {
317                Ok(e) => e,
318                Err(e) => return AstNode::Err(e),
319            };
320            lhs = ReturnExpr::Or(Box::new(lhs), Box::new(rhs));
321        }
322        AstNode::ReturnExpr(lhs)
323    }
324
325    fn visit_xorExpression(&mut self, ctx: &XorExpressionContext<'input>) -> Self::Return {
326        let mut operands = ctx.andExpression_all().into_iter();
327        let mut lhs = match self
328            .visit(
329                &*operands
330                    .next()
331                    .expect("xorExpression has at least one andExpression"),
332            )
333            .into_return_expr()
334        {
335            Ok(e) => e,
336            Err(e) => return AstNode::Err(e),
337        };
338        for rhs_ctx in operands {
339            let rhs = match self.visit(&*rhs_ctx).into_return_expr() {
340                Ok(e) => e,
341                Err(e) => return AstNode::Err(e),
342            };
343            lhs = ReturnExpr::Xor(Box::new(lhs), Box::new(rhs));
344        }
345        AstNode::ReturnExpr(lhs)
346    }
347
348    fn visit_andExpression(&mut self, ctx: &AndExpressionContext<'input>) -> Self::Return {
349        let mut operands = ctx.notExpression_all().into_iter();
350        let mut lhs = match self
351            .visit(
352                &*operands
353                    .next()
354                    .expect("andExpression has at least one notExpression"),
355            )
356            .into_return_expr()
357        {
358            Ok(e) => e,
359            Err(e) => return AstNode::Err(e),
360        };
361        for rhs_ctx in operands {
362            let rhs = match self.visit(&*rhs_ctx).into_return_expr() {
363                Ok(e) => e,
364                Err(e) => return AstNode::Err(e),
365            };
366            lhs = ReturnExpr::And(Box::new(lhs), Box::new(rhs));
367        }
368        AstNode::ReturnExpr(lhs)
369    }
370
371    fn visit_notExpression(&mut self, ctx: &NotExpressionContext<'input>) -> Self::Return {
372        let inner = ctx
373            .comparisonExpression()
374            .expect("notExpression always has a comparisonExpression");
375        match self.visit(&*inner).into_return_expr() {
376            Ok(mut expr) => {
377                for _ in ctx.NOT_all() {
378                    expr = ReturnExpr::Not(Box::new(expr));
379                }
380                AstNode::ReturnExpr(expr)
381            }
382            Err(e) => AstNode::Err(e),
383        }
384    }
385
386    fn visit_comparisonExpression(
387        &mut self,
388        ctx: &ComparisonExpressionContext<'input>,
389    ) -> Self::Return {
390        match self.build_comparison_expression(ctx) {
391            Ok(expr) => AstNode::ReturnExpr(expr),
392            Err(e) => AstNode::Err(e),
393        }
394    }
395
396    fn visit_stringListNullExpression(
397        &mut self,
398        ctx: &StringListNullExpressionContext<'input>,
399    ) -> Self::Return {
400        match self.build_string_list_null_expression(ctx) {
401            Ok(expr) => AstNode::ReturnExpr(expr),
402            Err(e) => AstNode::Err(e),
403        }
404    }
405
406    fn visit_addSubExpression(&mut self, ctx: &AddSubExpressionContext<'input>) -> Self::Return {
407        match self.build_add_sub_expression(ctx) {
408            Ok(expr) => AstNode::ReturnExpr(expr),
409            Err(e) => AstNode::Err(e),
410        }
411    }
412
413    fn visit_multDivExpression(&mut self, ctx: &MultDivExpressionContext<'input>) -> Self::Return {
414        match self.build_mult_div_expression(ctx) {
415            Ok(expr) => AstNode::ReturnExpr(expr),
416            Err(e) => AstNode::Err(e),
417        }
418    }
419
420    /// Left-associative (`4 ^ 3 ^ 2` is `(4 ^ 3) ^ 2`), same as every
421    /// other binary chain here -- matches `parser.rs`'s `parse_pow_expr`,
422    /// confirmed against the real TCK fixture (see that function's docs).
423    fn visit_powerExpression(&mut self, ctx: &PowerExpressionContext<'input>) -> Self::Return {
424        let mut operands = ctx.unaryAddSubExpression_all().into_iter();
425        let mut lhs = match self
426            .visit(
427                &*operands
428                    .next()
429                    .expect("powerExpression has at least one unaryAddSubExpression"),
430            )
431            .into_return_expr()
432        {
433            Ok(e) => e,
434            Err(e) => return AstNode::Err(e),
435        };
436        for rhs_ctx in operands {
437            let rhs = match self.visit(&*rhs_ctx).into_return_expr() {
438                Ok(e) => e,
439                Err(e) => return AstNode::Err(e),
440            };
441            lhs = ReturnExpr::Arith(Box::new(lhs), ArithOp::Pow, Box::new(rhs));
442        }
443        AstNode::ReturnExpr(lhs)
444    }
445
446    fn visit_unaryAddSubExpression(
447        &mut self,
448        ctx: &UnaryAddSubExpressionContext<'input>,
449    ) -> Self::Return {
450        match self.build_unary_add_sub_expression(ctx) {
451            Ok(expr) => AstNode::ReturnExpr(expr),
452            Err(e) => AstNode::Err(e),
453        }
454    }
455
456    fn visit_atomicExpression(&mut self, ctx: &AtomicExpressionContext<'input>) -> Self::Return {
457        match self.build_atomic_expression(ctx) {
458            Ok(expr) => AstNode::ReturnExpr(expr),
459            Err(e) => AstNode::Err(e),
460        }
461    }
462
463    fn visit_propertyOrLabelExpression(
464        &mut self,
465        ctx: &PropertyOrLabelExpressionContext<'input>,
466    ) -> Self::Return {
467        match self.build_property_or_label_expression(ctx) {
468            Ok(expr) => AstNode::ReturnExpr(expr),
469            Err(e) => AstNode::Err(e),
470        }
471    }
472
473    fn visit_propertyExpression(
474        &mut self,
475        ctx: &PropertyExpressionContext<'input>,
476    ) -> Self::Return {
477        match self.build_property_expression(ctx) {
478            Ok(expr) => AstNode::ReturnExpr(expr),
479            Err(e) => AstNode::Err(e),
480        }
481    }
482
483    fn visit_atom(&mut self, ctx: &AtomContext<'input>) -> Self::Return {
484        match self.build_atom(ctx) {
485            Ok(expr) => AstNode::ReturnExpr(expr),
486            Err(e) => AstNode::Err(e),
487        }
488    }
489
490    fn visit_parenthesizedExpression(
491        &mut self,
492        ctx: &ParenthesizedExpressionContext<'input>,
493    ) -> Self::Return {
494        let inner = ctx
495            .expression()
496            .expect("parenthesizedExpression always has an expression");
497        self.visit(&*inner)
498    }
499
500    fn visit_functionInvocation(
501        &mut self,
502        ctx: &FunctionInvocationContext<'input>,
503    ) -> Self::Return {
504        match self.build_function_invocation(ctx) {
505            Ok(expr) => AstNode::ReturnExpr(expr),
506            Err(e) => AstNode::Err(e),
507        }
508    }
509
510    fn visit_parameter(&mut self, ctx: &ParameterContext<'input>) -> Self::Return {
511        match self.build_parameter(ctx) {
512            Ok(expr) => AstNode::ReturnExpr(expr),
513            Err(e) => AstNode::Err(e),
514        }
515    }
516
517    fn visit_countAll(&mut self, _ctx: &CountAllContext<'input>) -> Self::Return {
518        AstNode::ReturnExpr(ReturnExpr::CountStar)
519    }
520
521    fn visit_returnSt(&mut self, ctx: &ReturnStContext<'input>) -> Self::Return {
522        let body_ctx = ctx
523            .projectionBody()
524            .expect("returnSt always has a projectionBody");
525        match self.build_projection_body(&body_ctx) {
526            Ok(c) => AstNode::ReturnClause(c),
527            Err(e) => AstNode::Err(e),
528        }
529    }
530
531    fn visit_withSt(&mut self, ctx: &WithStContext<'input>) -> Self::Return {
532        match self.build_with_clause(ctx) {
533            Ok(c) => AstNode::WithClause(c),
534            Err(e) => AstNode::Err(e),
535        }
536    }
537
538    fn visit_unwindSt(&mut self, ctx: &UnwindStContext<'input>) -> Self::Return {
539        match self.build_unwind_st(ctx) {
540            Ok(c) => AstNode::UnwindClause(c),
541            Err(e) => AstNode::Err(e),
542        }
543    }
544
545    fn visit_setSt(&mut self, ctx: &SetStContext<'input>) -> Self::Return {
546        match self.build_set_st(ctx) {
547            Ok(items) => AstNode::SetItems(items),
548            Err(e) => AstNode::Err(e),
549        }
550    }
551
552    fn visit_deleteSt(&mut self, ctx: &DeleteStContext<'input>) -> Self::Return {
553        match self.build_delete_st(ctx) {
554            Ok(d) => AstNode::DeleteItems(d),
555            Err(e) => AstNode::Err(e),
556        }
557    }
558
559    fn visit_removeSt(&mut self, ctx: &RemoveStContext<'input>) -> Self::Return {
560        match self.build_remove_st(ctx) {
561            Ok(items) => AstNode::RemoveItems(items),
562            Err(e) => AstNode::Err(e),
563        }
564    }
565
566    fn visit_createSt(&mut self, ctx: &CreateStContext<'input>) -> Self::Return {
567        match self.build_create_st(ctx) {
568            Ok(patterns) => AstNode::CreatePatterns(patterns),
569            Err(e) => AstNode::Err(e),
570        }
571    }
572
573    fn visit_mergeSt(&mut self, ctx: &MergeStContext<'input>) -> Self::Return {
574        match self.build_merge_st(ctx) {
575            Ok(c) => AstNode::MergeClause(c),
576            Err(e) => AstNode::Err(e),
577        }
578    }
579
580    fn visit_singlePartQ(&mut self, ctx: &SinglePartQContext<'input>) -> Self::Return {
581        match self.build_single_part_q(ctx) {
582            Ok(s) => AstNode::Statement(s),
583            Err(e) => AstNode::Err(e),
584        }
585    }
586
587    fn visit_multiPartQ(&mut self, ctx: &MultiPartQContext<'input>) -> Self::Return {
588        match self.build_multi_part_q(ctx) {
589            Ok(s) => AstNode::Statement(s),
590            Err(e) => AstNode::Err(e),
591        }
592    }
593
594    fn visit_regularQuery(&mut self, ctx: &RegularQueryContext<'input>) -> Self::Return {
595        match self.build_regular_query(ctx) {
596            Ok(s) => AstNode::Statement(s),
597            Err(e) => AstNode::Err(e),
598        }
599    }
600
601    // `query : explainSt | regularQuery | standaloneCall | createIndexSt`
602    // -- `regularQuery`/`explainSt`/`createIndexSt` need no override of
603    // their own *here* (default `visit_children` dispatch already routes
604    // to each rule's own override below); `standaloneCall` (a bare
605    // `CALL proc(...) YIELD ...` with no MATCH at all) builds its own
606    // `Statement::StandaloneCall` directly, same reasoning `visit_
607    // regularQuery` already has for delegating to a `build_*` helper.
608    fn visit_standaloneCall(&mut self, ctx: &StandaloneCallContext<'input>) -> Self::Return {
609        match self.build_standalone_call(ctx) {
610            Ok(s) => AstNode::Statement(s),
611            Err(e) => AstNode::Err(e),
612        }
613    }
614
615    fn visit_explainSt(&mut self, ctx: &ExplainStContext<'input>) -> Self::Return {
616        match self.build_explain_st(ctx) {
617            Ok(s) => AstNode::Statement(s),
618            Err(e) => AstNode::Err(e),
619        }
620    }
621
622    fn visit_createIndexSt(&mut self, ctx: &CreateIndexStContext<'input>) -> Self::Return {
623        match self.build_create_index_st(ctx) {
624            Ok(s) => AstNode::Statement(s),
625            Err(e) => AstNode::Err(e),
626        }
627    }
628
629    fn visit_listLit(&mut self, ctx: &ListLitContext<'input>) -> Self::Return {
630        let mut items = Vec::new();
631        if let Some(chain_ctx) = ctx.expressionChain() {
632            for expr_ctx in chain_ctx.expression_all() {
633                match self.visit(&*expr_ctx).into_return_expr() {
634                    Ok(e) => items.push(e),
635                    Err(e) => return AstNode::Err(e),
636                }
637            }
638        }
639        AstNode::ReturnExpr(ReturnExpr::ListLit(items))
640    }
641
642    fn visit_mapLit(&mut self, ctx: &MapLitContext<'input>) -> Self::Return {
643        let mut items = Vec::new();
644        for pair_ctx in ctx.mapPair_all() {
645            let name_ctx = pair_ctx.name().expect("mapPair always has a name");
646            let expr_ctx = pair_ctx
647                .expression()
648                .expect("mapPair always has an expression");
649            let value = match self.visit(&*expr_ctx).into_return_expr() {
650                Ok(v) => v,
651                Err(e) => return AstNode::Err(e),
652            };
653            items.push((name_text(&name_ctx), value));
654        }
655        AstNode::ReturnExpr(ReturnExpr::MapLit(items))
656    }
657}
658
659fn symbol_text(ctx: &SymbolContextAll) -> String {
660    match ctx.ESC_LITERAL() {
661        // `` `a weird name` `` -- strip the surrounding backticks.
662        Some(t) => {
663            let text = t.get_text();
664            text[1..text.len() - 1].to_string()
665        }
666        None => ctx.get_text(),
667    }
668}
669
670/// `name : symbol | reservedWord`, used for label/property/map-key names
671/// (unlike `symbol`, usable for bound-variable names too). Delegates to
672/// `symbol_text` (backtick-stripping) when the alternative taken is
673/// `symbol` -- a bare `.get_text()` here would keep the backticks
674/// themselves as part of the name (e.g. `` map.`name` `` would look up
675/// the map key `` `name` `` instead of `name`, always missing -- a real
676/// bug found via the TCK, not just deferred coverage). `reservedWord` has
677/// no escaping to strip either way.
678fn name_text(ctx: &NameContextAll) -> String {
679    match ctx.symbol() {
680        Some(s) => symbol_text(&s),
681        None => ctx.get_text(),
682    }
683}
684
685/// Shared by `visit_numLit` (unsigned) and `build_unary_add_sub_expr`'s
686/// sign-folding special case (`text` prefixed with `-`) -- see that
687/// function's docs for why a leading sign has to be handled there instead
688/// of in `DIGIT` itself.
689fn parse_num_lit_text(text: &str) -> Result<Literal, QueryError> {
690    // A hex/octal literal's own digits can end in `f`/`F`/`d`/`D` (real hex
691    // digits, e.g. `0x7FFFFFFFFFFFFFFF`) or contain `e`/`E` (also a real
692    // hex digit) -- neither is real openCypher's `<approximate number
693    // suffix>` (`F`/`D`/`f`), which per spec only ever follows a decimal
694    // literal already in scientific or common (has a `.`) notation. Found
695    // via a Phase 3 dry-run behavioral test failure
696    // (`int_literal_accepts_hex_and_octal_forms`): a hex literal ending in
697    // a suffix-shaped digit was misdetected as float and failed to parse.
698    let unsigned = text.strip_prefix('-').unwrap_or(text);
699    let is_hex_or_octal = unsigned
700        .as_bytes()
701        .get(1)
702        .is_some_and(|b| matches!(b, b'x' | b'X' | b'o' | b'O'))
703        && unsigned.starts_with('0');
704    let is_float = !is_hex_or_octal
705        && (text.contains('.')
706            || text.ends_with(['f', 'F', 'd', 'D'])
707            || text
708                .rfind(['e', 'E'])
709                .is_some_and(|i| text[..i].chars().all(|c| c.is_ascii_digit() || c == '-')));
710    if is_float {
711        let f: f64 = text
712            .parse()
713            .map_err(|_| QueryError::Syntax(format!("invalid float literal '{text}'")))?;
714        // `str::parse::<f64>()` silently returns `f64::INFINITY` for a
715        // magnitude beyond f64's representable range instead of erroring
716        // (`"1e999".parse::<f64>()` is `Ok(inf)`) -- real Cypher requires
717        // this to be a compile-time error (TCK Literals5 [27],
718        // `FloatingPointOverflow`).
719        if f.is_infinite() {
720            Err(QueryError::Syntax(format!(
721                "float literal '{text}' is too large to represent"
722            )))
723        } else {
724            Ok(Literal::Float(f))
725        }
726    } else {
727        parse_int_literal(text).map(Literal::Int)
728    }
729}
730
731fn compare_sign(ctx: &ComparisonSignsContextAll) -> CompareOp {
732    if ctx.LE().is_some() {
733        CompareOp::Le
734    } else if ctx.GE().is_some() {
735        CompareOp::Ge
736    } else if ctx.GT().is_some() {
737        CompareOp::Gt
738    } else if ctx.LT().is_some() {
739        CompareOp::Lt
740    } else if ctx.NOT_EQUAL().is_some() {
741        CompareOp::Ne
742    } else {
743        // Only ASSIGN ('=') left -- comparisonSigns' six alternatives are
744        // exhaustive.
745        CompareOp::Eq
746    }
747}
748
749fn string_exp_op(ctx: &StringExpPrefixContextAll) -> CompareOp {
750    if ctx.STARTS().is_some() {
751        CompareOp::StartsWith
752    } else if ctx.ENDS().is_some() {
753        CompareOp::EndsWith
754    } else {
755        CompareOp::Contains
756    }
757}
758
759fn invocation_name_text(ctx: &InvocationNameContextAll) -> String {
760    ctx.symbol_all()
761        .iter()
762        .map(|s| symbol_text(s))
763        .collect::<Vec<_>>()
764        .join(".")
765}
766
767/// Whether `atomicExpression` reduces to exactly a bare numeric literal --
768/// no property/label/postfix suffixes at any level between it and the
769/// `numLit` itself. Used by `build_unary_add_sub_expression` to fold a
770/// leading `-` directly into the literal (see that function's docs).
771/// `stringExpression`/`nullExpression`/`inExpression` no longer live at
772/// this level at all (moved up to `stringListNullExpression`, see its own
773/// docs) -- only `listExpression` (postfix index/slice) can still appear
774/// here, so that's the only check left.
775fn bare_num_lit<'i>(
776    ctx: &AtomicExpressionContextAll<'i>,
777) -> Option<std::rc::Rc<NumLitContextAll<'i>>> {
778    if !ctx.listExpression_all().is_empty() {
779        return None;
780    }
781    let prop_or_label = ctx.propertyOrLabelExpression()?;
782    if prop_or_label.nodeLabels().is_some() {
783        return None;
784    }
785    let prop_expr = prop_or_label.propertyExpression()?;
786    if !prop_expr.name_all().is_empty() {
787        return None;
788    }
789    prop_expr.atom()?.literal()?.numLit()
790}
791
792/// For a single-bound `list[..N]`/`list[N..]` slice, `expression_all()`
793/// alone can't say which side of `RANGE` the one present bound is on --
794/// walk the raw children between `LBRACK` and `RBRACK` to find out, same
795/// "read raw children in source order" approach `build_add_sub_expression`
796/// uses. `[`/`]`/`..` are the only fixed-text children possible here; the
797/// one remaining child is the expression itself.
798fn list_expr_bound_is_before_range(ctx: &ListExpressionContextAll) -> bool {
799    let mut seen_range = false;
800    for child in ctx.get_children() {
801        match child.get_text().as_str() {
802            "[" | "]" => continue,
803            ".." => seen_range = true,
804            _ => return !seen_range,
805        }
806    }
807    unreachable!("listExpression slice form always has exactly one expression child")
808}
809
810impl AstBuilder {
811    /// `properties : mapLit | parameter`. Only the `mapLit` alternative
812    /// has a real `NodePattern`/`RelPattern::props` representation --
813    /// `Vec<(String, ReturnExpr)>` has no "the whole map comes from one
814    /// parameter" shape, and pest doesn't support that on a pattern's
815    /// inline properties either (only `map_expr`), so rejecting it here
816    /// isn't a regression, just parity.
817    fn build_properties(
818        &mut self,
819        ctx: Option<Rc<PropertiesContextAll>>,
820    ) -> Result<Vec<(String, ReturnExpr)>, QueryError> {
821        let Some(ctx) = ctx else {
822            return Ok(Vec::new());
823        };
824        let Some(map_ctx) = ctx.mapLit() else {
825            return Err(QueryError::Syntax(
826                "a parameter can't be used as a pattern's whole properties map".into(),
827            ));
828        };
829        let expr = self.visit(&*map_ctx).into_return_expr()?;
830        let ReturnExpr::MapLit(items) = expr else {
831            unreachable!("mapLit always builds a ReturnExpr::MapLit");
832        };
833        Ok(items)
834    }
835
836    fn build_node_pattern(&mut self, ctx: &NodePatternContext) -> Result<NodePattern, QueryError> {
837        let var = ctx.symbol().map(|s| symbol_text(&s));
838        let labels = ctx
839            .nodeLabels()
840            .map(|nl| nl.name_all().iter().map(|n| name_text(n)).collect())
841            .unwrap_or_default();
842        let has_explicit_props = ctx.properties().is_some();
843        let props = self.build_properties(ctx.properties())?;
844        Ok(NodePattern {
845            var,
846            labels,
847            props,
848            has_explicit_props,
849        })
850    }
851
852    fn build_rel_detail(&mut self, ctx: &RelationDetailContext) -> Result<RelPattern, QueryError> {
853        let var = ctx.symbol().map(|s| symbol_text(&s));
854        let rel_types = ctx
855            .relationshipTypes()
856            .map(|rt| rt.name_all().iter().map(|n| name_text(n)).collect())
857            .unwrap_or_default();
858        let props = self.build_properties(ctx.properties())?;
859        let hop_range = ctx
860            .rangeLit()
861            .map(|r| parse_rel_range(&r.get_text()))
862            .transpose()?;
863        Ok(RelPattern {
864            var,
865            rel_types,
866            props,
867            // Overwritten by `build_relationship_pattern`, the only
868            // caller -- `relationDetail` itself (`[...]`) carries no
869            // directionality, that's `<`/`>` on the surrounding
870            // `relationshipPattern`.
871            direction: RelDirection::Either,
872            hop_range,
873            capture_path_segment: false,
874            rel_list_var: None,
875        })
876    }
877
878    fn build_relationship_pattern(
879        &mut self,
880        ctx: &RelationshipPatternContext,
881    ) -> Result<RelPattern, QueryError> {
882        let mut rel = match ctx.relationDetail() {
883            Some(rd) => self.visit(&*rd).into_rel_pattern()?,
884            None => RelPattern {
885                var: None,
886                rel_types: Vec::new(),
887                props: Vec::new(),
888                direction: RelDirection::Either,
889                hop_range: None,
890                capture_path_segment: false,
891                rel_list_var: None,
892            },
893        };
894        // Both LT and GT present (`<-[...]->`) is *not* "left wins" --
895        // it's the same undirected/either shape as neither being present
896        // (`-[...]-`), and CREATE/MERGE already reject `Either` outright
897        // (`RequiresDirectedRelationship`, executor.rs). Found via the
898        // TCK: the old `if LT ... else if GT ...` order silently treated
899        // `<-[:FOO]->` as plain `Left`, both letting CREATE wrongly
900        // succeed (Create2 [20]) and giving MATCH's own undirected
901        // multi-hop patterns the wrong direction entirely
902        // (Match5 [27]/Match6 [12]'s wrong row counts).
903        rel.direction = match (ctx.LT().is_some(), ctx.GT().is_some()) {
904            (true, false) => RelDirection::Left,
905            (false, true) => RelDirection::Right,
906            (true, true) | (false, false) => RelDirection::Either,
907        };
908        Ok(rel)
909    }
910
911    fn build_pattern_elem(&mut self, ctx: &PatternElemContext) -> Result<Pattern, QueryError> {
912        if ctx.LPAREN().is_some() || !ctx.qppElemChain_all().is_empty() {
913            return Err(QueryError::Syntax(
914                "quantified path patterns aren't supported yet".into(),
915            ));
916        }
917        let node_ctx = ctx
918            .nodePattern()
919            .expect("patternElem always starts with a nodePattern in the non-QPP alternative");
920        let start = self.visit(&*node_ctx).into_node_pattern()?;
921        let mut hops = Vec::new();
922        for chain in ctx.patternElemChain_all() {
923            let rel_ctx = chain
924                .relationshipPattern()
925                .expect("patternElemChain always has a relationshipPattern");
926            let node_ctx = chain
927                .nodePattern()
928                .expect("patternElemChain always has a nodePattern");
929            let rel = self.visit(&*rel_ctx).into_rel_pattern()?;
930            let node = self.visit(&*node_ctx).into_node_pattern()?;
931            hops.push((rel, node));
932        }
933        Ok(Pattern { start, hops })
934    }
935
936    /// `relationshipsChainPattern : nodePattern patternElemChain+` -- an
937    /// `atom` alternative (`(n)-->()` used directly as a boolean
938    /// expression, TCK's Pattern1/2 "Pattern predicate"), same node+chain
939    /// shape `build_pattern_elem` already builds for real match patterns,
940    /// just requiring at least one hop (no bare-node pattern predicate,
941    /// matching the grammar's own `+` here vs `patternElem`'s `*`).
942    fn build_relationships_chain_pattern(
943        &mut self,
944        ctx: &RelationshipsChainPatternContext,
945    ) -> Result<Pattern, QueryError> {
946        let node_ctx = ctx
947            .nodePattern()
948            .expect("relationshipsChainPattern always has a nodePattern");
949        let start = self.visit(&*node_ctx).into_node_pattern()?;
950        let mut hops = Vec::new();
951        for chain in ctx.patternElemChain_all() {
952            let rel_ctx = chain
953                .relationshipPattern()
954                .expect("patternElemChain always has a relationshipPattern");
955            let node_ctx = chain
956                .nodePattern()
957                .expect("patternElemChain always has a nodePattern");
958            let rel = self.visit(&*rel_ctx).into_rel_pattern()?;
959            let node = self.visit(&*node_ctx).into_node_pattern()?;
960            hops.push((rel, node));
961        }
962        Ok(Pattern { start, hops })
963    }
964
965    /// Mirrors `parser.rs`'s `parse_match_part` -- comma-separated pattern
966    /// parts splice into linear chains (shared-node merging) or split into
967    /// separate `QueryPart`s (disjoint cross join) via
968    /// `group_into_linear_patterns`, reused as-is.
969    fn build_match_st(&mut self, ctx: &MatchStContext) -> Result<Vec<QueryPart>, QueryError> {
970        let optional = ctx.OPTIONAL().is_some();
971        let pw = ctx
972            .patternWhere()
973            .expect("matchSt always has a patternWhere");
974        let where_clause = match pw.where_() {
975            Some(where_ctx) => {
976                let expr_ctx = where_ctx
977                    .expression()
978                    .expect("where always has an expression");
979                let expr = self.visit(&*expr_ctx).into_return_expr()?;
980                Some(return_expr_to_expr(expr)?)
981            }
982            None => None,
983        };
984        let pattern_ctx = pw.pattern().expect("patternWhere always has a pattern");
985
986        let mut path_var = None;
987        let mut shortest_path = false;
988        let mut patterns = Vec::new();
989        for (i, part) in pattern_ctx.patternPart_all().into_iter().enumerate() {
990            // `shortestPathWrapper` is grammar-permissive (any
991            // comma-separated position) -- restricted here to the first
992            // position only, same as `parser.rs`'s `parse_path_pattern`
993            // (real Cypher: naming/shortestPath only make sense on a
994            // single linear pattern, never a cross join).
995            let pattern = match part.shortestPathWrapper() {
996                Some(sp_ctx) => {
997                    if i != 0 {
998                        return Err(QueryError::Syntax(
999                            "shortestPath() must be the first (and only) comma-separated pattern"
1000                                .into(),
1001                        ));
1002                    }
1003                    shortest_path = true;
1004                    let elem_ctx = sp_ctx
1005                        .patternElem()
1006                        .expect("shortestPathWrapper always has a patternElem");
1007                    self.visit(&*elem_ctx).into_pattern()?
1008                }
1009                None => {
1010                    let elem_ctx = part.patternElem().expect(
1011                        "patternPart always has a patternElem when shortestPathWrapper is absent",
1012                    );
1013                    self.visit(&*elem_ctx).into_pattern()?
1014                }
1015            };
1016            patterns.push(pattern);
1017            if part.ASSIGN().is_some() {
1018                if path_var.is_some() {
1019                    return Err(QueryError::Syntax(
1020                        "at most one comma-separated pattern part can have a named-path variable"
1021                            .into(),
1022                    ));
1023                }
1024                let symbol_ctx = part
1025                    .symbol()
1026                    .expect("patternPart with ASSIGN always has a symbol");
1027                path_var = Some(symbol_text(&symbol_ctx));
1028            }
1029        }
1030
1031        let groups = group_into_linear_patterns(patterns)?;
1032        if groups.len() > 1 && (shortest_path || path_var.is_some()) {
1033            return Err(QueryError::Syntax(
1034                "a named path/shortestPath() can't span a comma-separated cross join".into(),
1035            ));
1036        }
1037        if shortest_path {
1038            validate_shortest_path_pattern(&groups[0])?;
1039        } else if path_var.is_some() {
1040            validate_named_path_pattern(&groups[0])?;
1041        }
1042
1043        // `where_clause` attaches to the *last* group only, same as
1044        // `parser.rs`'s `parse_match_part` -- a comma-separated cross join
1045        // sees every group's bindings by the time WHERE runs. `with` stays
1046        // unconditionally `None` here: this grammar's `matchSt` has no
1047        // trailing WITH of its own (that's a separate clause in the
1048        // statement's clause list, attached by whichever caller builds
1049        // that list, not here).
1050        let last = groups.len() - 1;
1051        Ok(groups
1052            .into_iter()
1053            .enumerate()
1054            .map(|(i, pattern)| QueryPart {
1055                optional,
1056                path_var: if i == 0 { path_var.clone() } else { None },
1057                shortest_path: i == 0 && shortest_path,
1058                pattern,
1059                where_clause: if i == last {
1060                    where_clause.clone()
1061                } else {
1062                    None
1063                },
1064                with: None,
1065            })
1066            .collect())
1067    }
1068
1069    /// Mirrors `parser.rs`'s `parse_compare_expr` -- a chain folds into
1070    /// nested `And`s of each *adjacent* pair (`a op0 b op1 c` -> `(a op0
1071    /// b) AND (b op1 c)`, real Cypher's own chained-comparison semantics),
1072    /// not a separate AST shape. Operand type is `stringListNullExpression`
1073    /// (not `addSubExpression` directly) since the precedence fix moved
1074    /// `IN`/`STARTS WITH`/etc up to sit between this level and arithmetic
1075    /// -- see `build_string_list_null_expression`'s docs.
1076    fn build_comparison_expression(
1077        &mut self,
1078        ctx: &ComparisonExpressionContext,
1079    ) -> Result<ReturnExpr, QueryError> {
1080        let mut operands = Vec::new();
1081        for operand_ctx in ctx.stringListNullExpression_all() {
1082            operands.push(self.visit(&*operand_ctx).into_return_expr()?);
1083        }
1084        let mut ops = Vec::new();
1085        for sign_ctx in ctx.comparisonSigns_all() {
1086            ops.push(compare_sign(&sign_ctx));
1087        }
1088        if ops.is_empty() {
1089            return Ok(operands
1090                .into_iter()
1091                .next()
1092                .expect("comparisonExpression has at least one stringListNullExpression"));
1093        }
1094        let mut pairs = operands.windows(2).zip(&ops).map(|(pair, op)| {
1095            ReturnExpr::Compare(Box::new(pair[0].clone()), *op, Box::new(pair[1].clone()))
1096        });
1097        let mut acc = pairs
1098            .next()
1099            .expect("a comparison chain has at least one pair");
1100        for next in pairs {
1101            acc = ReturnExpr::And(Box::new(acc), Box::new(next));
1102        }
1103        Ok(acc)
1104    }
1105
1106    /// `SUB_all()`/`PLUS_all()` each only return same-type tokens, losing
1107    /// which operator occupies which position among possibly-mixed `+`/`-`
1108    /// -- walking the raw children directly instead recovers real source
1109    /// order for free, and lets ANTLR's own dispatch (`self.visit` on a
1110    /// generic child) route each operand to `visit_multDivExpression`
1111    /// rather than needing the typed `multDivExpression_all()` accessor at
1112    /// all. The grammar shape (`multDivExpression ((PLUS | SUB)
1113    /// multDivExpression)*`) guarantees strict operand/operator
1114    /// alternation, so no type check is needed to tell them apart.
1115    fn build_add_sub_expression(
1116        &mut self,
1117        ctx: &AddSubExpressionContext,
1118    ) -> Result<ReturnExpr, QueryError> {
1119        let mut children = ctx.get_children();
1120        let mut lhs = self
1121            .visit(
1122                &*children
1123                    .next()
1124                    .expect("addSubExpression has at least one multDivExpression"),
1125            )
1126            .into_return_expr()?;
1127        while let Some(op_node) = children.next() {
1128            let op = match op_node.get_text().as_str() {
1129                "+" => ArithOp::Add,
1130                "-" => ArithOp::Sub,
1131                other => unreachable!("unexpected addSubExpression operator {other:?}"),
1132            };
1133            let rhs_node = children
1134                .next()
1135                .expect("addSubExpression operator has a following multDivExpression");
1136            let rhs = self.visit(&*rhs_node).into_return_expr()?;
1137            lhs = ReturnExpr::Arith(Box::new(lhs), op, Box::new(rhs));
1138        }
1139        Ok(lhs)
1140    }
1141
1142    fn build_mult_div_expression(
1143        &mut self,
1144        ctx: &MultDivExpressionContext,
1145    ) -> Result<ReturnExpr, QueryError> {
1146        let mut children = ctx.get_children();
1147        let mut lhs = self
1148            .visit(
1149                &*children
1150                    .next()
1151                    .expect("multDivExpression has at least one powerExpression"),
1152            )
1153            .into_return_expr()?;
1154        while let Some(op_node) = children.next() {
1155            let op = match op_node.get_text().as_str() {
1156                "*" => ArithOp::Mul,
1157                "/" => ArithOp::Div,
1158                "%" => ArithOp::Mod,
1159                other => unreachable!("unexpected multDivExpression operator {other:?}"),
1160            };
1161            let rhs_node = children
1162                .next()
1163                .expect("multDivExpression operator has a following powerExpression");
1164            let rhs = self.visit(&*rhs_node).into_return_expr()?;
1165            lhs = ReturnExpr::Arith(Box::new(lhs), op, Box::new(rhs));
1166        }
1167        Ok(lhs)
1168    }
1169
1170    /// The parser already has correct unary-minus handling at this
1171    /// precedence level (`(PLUS | SUB)? atomicExpression`), but for
1172    /// `i64::MIN` (`-9223372036854775808`) to round-trip, the sign has to
1173    /// fold directly into the literal's own parse rather than building
1174    /// `Neg(Lit(Int(9223372036854775808)))` -- `9223372036854775808`
1175    /// itself doesn't fit in a positive `i64` at all (only `i64::MIN`'s
1176    /// magnitude does, via `parse_int_literal`'s two's-complement special
1177    /// case, which needs the sign in its input string up front). Pest's
1178    /// grammar sidestepped this by including an optional leading `-` in
1179    /// `int_literal`/`float_literal` themselves; this grammar's `DIGIT`
1180    /// deliberately doesn't (see the binary-minus fix), so the fold has to
1181    /// happen here instead, for the one case where the operand is exactly
1182    /// a bare numeric literal with no other operators/suffixes.
1183    fn build_unary_add_sub_expression(
1184        &mut self,
1185        ctx: &UnaryAddSubExpressionContext,
1186    ) -> Result<ReturnExpr, QueryError> {
1187        let atomic_ctx = ctx
1188            .atomicExpression()
1189            .expect("unaryAddSubExpression always has an atomicExpression");
1190        if ctx.SUB().is_some() {
1191            if let Some(numlit_ctx) = bare_num_lit(&atomic_ctx) {
1192                let text = numlit_ctx
1193                    .DIGIT()
1194                    .expect("numLit context always has a DIGIT token")
1195                    .get_text();
1196                return parse_num_lit_text(&format!("-{text}")).map(ReturnExpr::Lit);
1197            }
1198            let operand = self.visit(&*atomic_ctx).into_return_expr()?;
1199            return Ok(ReturnExpr::Neg(Box::new(operand)));
1200        }
1201        // A leading `+` is always a no-op in Cypher (`+x` is just `x`).
1202        self.visit(&*atomic_ctx).into_return_expr()
1203    }
1204
1205    /// `atomicExpression : propertyOrLabelExpression (listExpression)*`
1206    /// -- only postfix index/slice suffixes live here now (`IN`/
1207    /// `stringExpression`/`nullExpression` moved up to
1208    /// `stringListNullExpression`, see its own docs); genuinely
1209    /// left-to-right chainable (`list[0][1]`, real postfix repetition per
1210    /// openCypher.bnf's `<postfix expression> ::= ... | <postfix
1211    /// expression> <postfix operator>`), so no "at most one" restriction
1212    /// is needed here at all anymore.
1213    fn build_atomic_expression(
1214        &mut self,
1215        ctx: &AtomicExpressionContext,
1216    ) -> Result<ReturnExpr, QueryError> {
1217        let base_ctx = ctx
1218            .propertyOrLabelExpression()
1219            .expect("atomicExpression always has a propertyOrLabelExpression");
1220        let mut base = self.visit(&*base_ctx).into_return_expr()?;
1221        for l in ctx.listExpression_all() {
1222            base = self.build_list_expression(&l, base)?;
1223        }
1224        Ok(base)
1225    }
1226
1227    /// `stringListNullExpression : addSubExpression (stringExpression |
1228    /// inExpression | nullExpression)?` -- fixes a real precedence bug in
1229    /// the vendored grammar (found via a Phase 3 behavioral dry-run, not
1230    /// the TCK): `IN`/`STARTS WITH`/`ENDS WITH`/`CONTAINS`/`IS NULL` used
1231    /// to attach at `atomicExpression`'s level (tighter than `+`/`-`/`*`/
1232    /// `/`/`^`), so `n.val + 0 IS NULL` parsed as `n.val + (0 IS NULL)`.
1233    /// Per openCypher.bnf's `<comparison predicate>` chain, these operate
1234    /// on a full `<arithmetic value expression>` (this file's
1235    /// `addSubExpression`), sitting above arithmetic and below `=`/`<>`/
1236    /// `<`/`>`/`<=`/`>=` (`comparisonExpression`, one level up) --
1237    /// see `grammar/README.md` for the upstream PR this was also sent to.
1238    fn build_string_list_null_expression(
1239        &mut self,
1240        ctx: &StringListNullExpressionContext,
1241    ) -> Result<ReturnExpr, QueryError> {
1242        let base_ctx = ctx
1243            .addSubExpression()
1244            .expect("stringListNullExpression always has an addSubExpression");
1245        let base = self.visit(&*base_ctx).into_return_expr()?;
1246        if let Some(s) = ctx.stringExpression() {
1247            return self.build_string_expression(&s, base);
1248        }
1249        if let Some(i) = ctx.inExpression() {
1250            let rhs_ctx = i
1251                .addSubExpression()
1252                .expect("inExpression always has an addSubExpression");
1253            let rhs = self.visit(&*rhs_ctx).into_return_expr()?;
1254            return Ok(ReturnExpr::In(Box::new(base), Box::new(rhs)));
1255        }
1256        let Some(n) = ctx.nullExpression() else {
1257            return Ok(base);
1258        };
1259        Ok(if n.NOT().is_some() {
1260            ReturnExpr::Not(Box::new(ReturnExpr::IsNull(Box::new(base))))
1261        } else {
1262            ReturnExpr::IsNull(Box::new(base))
1263        })
1264    }
1265
1266    /// Operand widened from `propertyOrLabelExpression` to
1267    /// `addSubExpression` (moved up alongside `stringListNullExpression`,
1268    /// see its own docs) -- `x STARTS WITH y + z` is now real, matching
1269    /// spec's `<advanced comparison predicand> ::= <arithmetic value
1270    /// expression>`.
1271    fn build_string_expression(
1272        &mut self,
1273        ctx: &StringExpressionContextAll,
1274        base: ReturnExpr,
1275    ) -> Result<ReturnExpr, QueryError> {
1276        let prefix_ctx = ctx
1277            .stringExpPrefix()
1278            .expect("stringExpression always has a stringExpPrefix");
1279        let op = string_exp_op(&prefix_ctx);
1280        let rhs_ctx = ctx
1281            .addSubExpression()
1282            .expect("stringExpression always has an addSubExpression");
1283        let rhs = self.visit(&*rhs_ctx).into_return_expr()?;
1284        Ok(ReturnExpr::Compare(Box::new(base), op, Box::new(rhs)))
1285    }
1286
1287    /// `listExpression` no longer has an `IN` alternative at all (moved to
1288    /// the new `inExpression` rule, built directly in
1289    /// `build_string_list_null_expression`) -- only the postfix index/
1290    /// slice forms remain.
1291    fn build_list_expression(
1292        &mut self,
1293        ctx: &ListExpressionContextAll,
1294        base: ReturnExpr,
1295    ) -> Result<ReturnExpr, QueryError> {
1296        let exprs = ctx.expression_all();
1297        if ctx.RANGE().is_some() {
1298            // `list[start..end]` -- either bound can be omitted.
1299            // `expression_all()` in source order: 0, 1, or 2 present.
1300            let (start, end) = match exprs.len() {
1301                0 => (None, None),
1302                1 => {
1303                    // One bound present -- is it before or after `RANGE`?
1304                    // Same alternating-children approach as
1305                    // `build_add_sub_expression`: walk raw children past
1306                    // `LBRACK` and see whether the expression comes before
1307                    // or after the `..` token.
1308                    let before_range = list_expr_bound_is_before_range(ctx);
1309                    let e = self.visit(&*exprs[0].clone()).into_return_expr()?;
1310                    if before_range {
1311                        (Some(Box::new(e)), None)
1312                    } else {
1313                        (None, Some(Box::new(e)))
1314                    }
1315                }
1316                2 => {
1317                    let start = self.visit(&*exprs[0].clone()).into_return_expr()?;
1318                    let end = self.visit(&*exprs[1].clone()).into_return_expr()?;
1319                    (Some(Box::new(start)), Some(Box::new(end)))
1320                }
1321                n => unreachable!("listExpression slice form has {n} expressions, expected 0-2"),
1322            };
1323            return Ok(ReturnExpr::Slice(Box::new(base), start, end));
1324        }
1325        let index_ctx = exprs
1326            .into_iter()
1327            .next()
1328            .expect("non-slice listExpression always has exactly one expression");
1329        let index = self.visit(&*index_ctx).into_return_expr()?;
1330        Ok(ReturnExpr::Index(Box::new(base), Box::new(index)))
1331    }
1332
1333    fn build_property_or_label_expression(
1334        &mut self,
1335        ctx: &PropertyOrLabelExpressionContext,
1336    ) -> Result<ReturnExpr, QueryError> {
1337        let prop_ctx = ctx
1338            .propertyExpression()
1339            .expect("propertyOrLabelExpression always has a propertyExpression");
1340        let base = self.visit(&*prop_ctx).into_return_expr()?;
1341        let Some(labels_ctx) = ctx.nodeLabels() else {
1342            return Ok(base);
1343        };
1344        let ReturnExpr::Var(var) = base else {
1345            return Err(QueryError::Syntax(
1346                "a label check (`x:Label`) only applies to a bare variable".into(),
1347            ));
1348        };
1349        let labels = labels_ctx.name_all().iter().map(|n| name_text(n)).collect();
1350        Ok(ReturnExpr::HasLabel(var, labels))
1351    }
1352
1353    /// `propertyExpression : atom (DOT name)*`. A bare atom (no `.name`
1354    /// suffix) passes through unchanged; the first suffix on a bare
1355    /// variable becomes the flat `Prop` shape (`{var, prop}`); every other
1356    /// suffix -- the first one when `atom` isn't a bare variable, and
1357    /// every suffix after the first regardless -- becomes `PropOf`
1358    /// instead, folded left-to-right (`a.b.c` -> `PropOf(Prop{a,b}, c)`),
1359    /// each evaluated by evaluating its own base first, then looking the
1360    /// property up on whatever `Value` that produced (TCK's Graph6 [4]/
1361    /// [8], Map1 [3], Merge5 [11], With2 [2]).
1362    fn build_property_expression(
1363        &mut self,
1364        ctx: &PropertyExpressionContext,
1365    ) -> Result<ReturnExpr, QueryError> {
1366        let atom_ctx = ctx.atom().expect("propertyExpression always has an atom");
1367        let base = self.visit(&*atom_ctx).into_return_expr()?;
1368        let mut names = ctx.name_all().into_iter();
1369        let Some(first) = names.next() else {
1370            return Ok(base);
1371        };
1372        // First suffix on a bare variable becomes the flat `Prop` shape
1373        // (`{var, prop}`); every suffix after that -- including this one
1374        // when `base` isn't a bare variable -- becomes `PropOf`, folded
1375        // left-to-right (`a.b.c` -> `PropOf(Prop{a,b}, c)`, TCK's With2
1376        // `[2]`, `nestedMap.name.name2`).
1377        let mut expr = match base {
1378            ReturnExpr::Var(var) => ReturnExpr::Prop(PropAccess {
1379                var,
1380                prop: name_text(&first),
1381            }),
1382            other => ReturnExpr::PropOf(Box::new(other), name_text(&first)),
1383        };
1384        for name in names {
1385            expr = ReturnExpr::PropOf(Box::new(expr), name_text(&name));
1386        }
1387        Ok(expr)
1388    }
1389
1390    fn build_atom(&mut self, ctx: &AtomContext) -> Result<ReturnExpr, QueryError> {
1391        if let Some(lit_ctx) = ctx.literal() {
1392            return self.visit(&*lit_ctx).into_return_expr_lenient();
1393        }
1394        if let Some(param_ctx) = ctx.parameter() {
1395            return self.build_parameter(&param_ctx);
1396        }
1397        if let Some(paren_ctx) = ctx.parenthesizedExpression() {
1398            return self.visit(&*paren_ctx).into_return_expr();
1399        }
1400        if let Some(func_ctx) = ctx.functionInvocation() {
1401            return self.build_function_invocation(&func_ctx);
1402        }
1403        if let Some(count_ctx) = ctx.countAll() {
1404            let _ = self.visit(&*count_ctx);
1405            return Ok(ReturnExpr::CountStar);
1406        }
1407        if let Some(sym_ctx) = ctx.symbol() {
1408            return Ok(ReturnExpr::Var(symbol_text(&sym_ctx)));
1409        }
1410        if let Some(filter_ctx) = ctx.filterWith() {
1411            return self.build_filter_with(&filter_ctx);
1412        }
1413        if let Some(lc_ctx) = ctx.listComprehension() {
1414            return self.build_list_comprehension(&lc_ctx);
1415        }
1416        if let Some(case_ctx) = ctx.caseExpression() {
1417            return self.build_case_expression(&case_ctx);
1418        }
1419        if let Some(pc_ctx) = ctx.patternComprehension() {
1420            return self.build_pattern_comprehension(&pc_ctx);
1421        }
1422        if let Some(rcp_ctx) = ctx.relationshipsChainPattern() {
1423            return Ok(ReturnExpr::PatternPredicate(
1424                self.build_relationships_chain_pattern(&rcp_ctx)?,
1425            ));
1426        }
1427        if let Some(se_ctx) = ctx.subqueryExist() {
1428            return self.build_subquery_exist(&se_ctx);
1429        }
1430        Err(QueryError::Syntax(
1431            "this expression form (path-as-expression) isn't supported by the ANTLR parser yet"
1432                .into(),
1433        ))
1434    }
1435
1436    /// `patternComprehension : LBRACK lhs? relationshipsChainPattern where?
1437    /// STICK expression RBRACK` -- `lhs` (`symbol ASSIGN`) is the optional
1438    /// named-path capture (`p = (n)-->()`), reusing
1439    /// `build_relationships_chain_pattern` for the pattern itself (same
1440    /// node+chain shape a pattern predicate already builds, just here it's
1441    /// enumerated rather than existence-checked) and the same `where?`
1442    /// production `build_match_st` uses for an ordinary `MATCH`'s own
1443    /// pattern-level `WHERE` (not `ListComp`'s post-projection
1444    /// `ReturnExpr`-shaped filter -- `patternComprehension` shares its
1445    /// grammar rule with `MATCH`, not with `listComprehension`).
1446    fn build_pattern_comprehension(
1447        &mut self,
1448        ctx: &PatternComprehensionContext,
1449    ) -> Result<ReturnExpr, QueryError> {
1450        let path_var = ctx
1451            .lhs()
1452            .and_then(|lhs| lhs.symbol())
1453            .map(|s| symbol_text(&s));
1454        let rcp_ctx = ctx
1455            .relationshipsChainPattern()
1456            .expect("patternComprehension always has a relationshipsChainPattern");
1457        let pattern = self.build_relationships_chain_pattern(&rcp_ctx)?;
1458        let where_clause = match ctx.where_() {
1459            Some(where_ctx) => {
1460                let expr_ctx = where_ctx
1461                    .expression()
1462                    .expect("where always has an expression");
1463                let expr = self.visit(&*expr_ctx).into_return_expr()?;
1464                Some(Box::new(return_expr_to_expr(expr)?))
1465            }
1466            None => None,
1467        };
1468        let proj_ctx = ctx
1469            .expression()
1470            .expect("patternComprehension always has a projection expression");
1471        let projection = self.visit(&*proj_ctx).into_return_expr()?;
1472        Ok(ReturnExpr::PatternComprehension {
1473            path_var,
1474            pattern: Box::new(pattern),
1475            where_clause,
1476            projection: Box::new(projection),
1477        })
1478    }
1479
1480    /// `subqueryExist : EXISTS LBRACE (regularQuery | patternWhere)
1481    /// RBRACE` -- `patternWhere` (TCK's ExistentialSubquery1, the "simple"
1482    /// form: a pattern with an optional inline `WHERE`, same grammar rule
1483    /// `MATCH` itself uses) builds a `ReturnExpr::ExistsPattern`;
1484    /// `regularQuery` (TCK's ExistentialSubquery2/3, a full nested `MATCH
1485    /// ... RETURN ...` subquery, arbitrarily many clauses, possibly itself
1486    /// containing a nested `exists {}`) reuses `build_regular_query`
1487    /// verbatim -- the exact same builder a top-level statement goes
1488    /// through -- and wraps the result in `ReturnExpr::ExistsSubquery`.
1489    /// Real Cypher restricts `exists {}`'s body to read-only clauses;
1490    /// `semantic::validate_statement`/`validate_match_clauses` reject a
1491    /// mutating clause or non-`Statement::Match` shape at compile time
1492    /// (TCK's ExistentialSubquery2 `[3]`), not here -- this stays a
1493    /// structural build step, same division of labor as every other
1494    /// pattern this visitor builds.
1495    fn build_subquery_exist(
1496        &mut self,
1497        ctx: &SubqueryExistContext,
1498    ) -> Result<ReturnExpr, QueryError> {
1499        if let Some(rq_ctx) = ctx.regularQuery() {
1500            let stmt = self.build_regular_query(&rq_ctx)?;
1501            return Ok(ReturnExpr::ExistsSubquery(Box::new(stmt)));
1502        }
1503        let pw_ctx = ctx
1504            .patternWhere()
1505            .expect("subqueryExist always has a regularQuery or patternWhere");
1506        let pattern_ctx = pw_ctx.pattern().expect("patternWhere always has a pattern");
1507        let mut parts = pattern_ctx.patternPart_all().into_iter();
1508        let part = parts
1509            .next()
1510            .expect("pattern always has at least one patternPart");
1511        if parts.next().is_some() {
1512            return Err(QueryError::Syntax(
1513                "exists {} with more than one comma-separated pattern isn't supported yet".into(),
1514            ));
1515        }
1516        if part.ASSIGN().is_some() || part.shortestPathWrapper().is_some() {
1517            return Err(QueryError::Syntax(
1518                "exists {} doesn't support a named path or shortestPath()".into(),
1519            ));
1520        }
1521        let elem_ctx = part
1522            .patternElem()
1523            .expect("a patternPart without ASSIGN/shortestPathWrapper always has a patternElem");
1524        let pattern = self.visit(&*elem_ctx).into_pattern()?;
1525        let where_clause = match pw_ctx.where_() {
1526            Some(where_ctx) => {
1527                let expr_ctx = where_ctx
1528                    .expression()
1529                    .expect("where always has an expression");
1530                let expr = self.visit(&*expr_ctx).into_return_expr()?;
1531                Some(Box::new(return_expr_to_expr(expr)?))
1532            }
1533            None => None,
1534        };
1535        Ok(ReturnExpr::ExistsPattern {
1536            pattern: Box::new(pattern),
1537            where_clause,
1538        })
1539    }
1540
1541    /// `caseExpression : CASE expression? (WHEN expression THEN
1542    /// expression)+ (ELSE expression)? END`. No typed per-`WHEN`/`THEN`
1543    /// accessor exists (`expression_all()` flattens every branch's exprs
1544    /// together, `WHEN()`/`THEN()`/`ELSE()` only ever return the *first*
1545    /// occurrence) -- walked via raw children instead, same "read raw
1546    /// children in source order" approach `build_add_sub_expression` uses,
1547    /// tracking position via each keyword *terminal*'s own text. Matched
1548    /// case-insensitively (the lexer's `caseInsensitive = true` means
1549    /// `get_text()` returns the source's own casing, e.g. `case`/`CASE`
1550    /// both valid) -- safe against a same-named real expression, since
1551    /// CASE/WHEN/THEN/ELSE/END are all in `reservedWord`, so none can
1552    /// appear as a bare variable at this position.
1553    fn build_case_expression(
1554        &mut self,
1555        ctx: &CaseExpressionContext,
1556    ) -> Result<ReturnExpr, QueryError> {
1557        #[derive(PartialEq)]
1558        enum Pos {
1559            BeforeFirstWhen,
1560            AfterWhen,
1561            AfterThen,
1562            AfterElse,
1563        }
1564        let mut pos = Pos::BeforeFirstWhen;
1565        let mut test = None;
1566        let mut whens: Vec<(ReturnExpr, ReturnExpr)> = Vec::new();
1567        let mut pending_when: Option<ReturnExpr> = None;
1568        let mut else_ = None;
1569        for child in ctx.get_children() {
1570            match child.get_text().to_ascii_uppercase().as_str() {
1571                "CASE" | "END" => continue,
1572                "WHEN" => pos = Pos::AfterWhen,
1573                "THEN" => pos = Pos::AfterThen,
1574                "ELSE" => pos = Pos::AfterElse,
1575                _ => {
1576                    let expr = self.visit(&*child).into_return_expr()?;
1577                    match pos {
1578                        Pos::BeforeFirstWhen => test = Some(Box::new(expr)),
1579                        Pos::AfterWhen => pending_when = Some(expr),
1580                        Pos::AfterThen => {
1581                            let w = pending_when
1582                                .take()
1583                                .expect("a THEN expression always follows a WHEN expression");
1584                            whens.push((w, expr));
1585                        }
1586                        Pos::AfterElse => else_ = Some(Box::new(expr)),
1587                    }
1588                }
1589            }
1590        }
1591        Ok(ReturnExpr::Case { test, whens, else_ })
1592    }
1593
1594    /// `filterExpression : symbol IN expression where?` -- shared by
1595    /// `filterWith` (ALL/ANY/NONE/SINGLE quantifiers) and
1596    /// `listComprehension`, both of which bind one variable over a source
1597    /// list, optionally filtered.
1598    fn build_filter_expression(
1599        &mut self,
1600        ctx: &FilterExpressionContext,
1601    ) -> Result<(String, ReturnExpr, Option<Box<ReturnExpr>>), QueryError> {
1602        let var_ctx = ctx.symbol().expect("filterExpression always has a symbol");
1603        let var = symbol_text(&var_ctx);
1604        let source_ctx = ctx
1605            .expression()
1606            .expect("filterExpression always has an expression");
1607        let source = self.visit(&*source_ctx).into_return_expr()?;
1608        let where_clause = match ctx.where_() {
1609            Some(where_ctx) => {
1610                let expr_ctx = where_ctx
1611                    .expression()
1612                    .expect("where always has an expression");
1613                Some(Box::new(self.visit(&*expr_ctx).into_return_expr()?))
1614            }
1615            None => None,
1616        };
1617        Ok((var, source, where_clause))
1618    }
1619
1620    /// `filterWith : (ALL | ANY | NONE | SINGLE) LPAREN filterExpression
1621    /// RPAREN` -- `ReturnExpr::Quantifier`, always evaluates to a bool
1622    /// (`where_clause` absent means "every element's own truthiness", same
1623    /// convention `Quantifier::where_clause`'s own docs describe).
1624    fn build_filter_with(&mut self, ctx: &FilterWithContext) -> Result<ReturnExpr, QueryError> {
1625        let kind = if ctx.ALL().is_some() {
1626            QuantifierKind::All
1627        } else if ctx.ANY().is_some() {
1628            QuantifierKind::Any
1629        } else if ctx.NONE().is_some() {
1630            QuantifierKind::None
1631        } else {
1632            ctx.SINGLE()
1633                .expect("filterWith always has one of ALL/ANY/NONE/SINGLE");
1634            QuantifierKind::Single
1635        };
1636        let fe_ctx = ctx
1637            .filterExpression()
1638            .expect("filterWith always has a filterExpression");
1639        let (var, source, where_clause) = self.build_filter_expression(&fe_ctx)?;
1640        Ok(ReturnExpr::Quantifier {
1641            kind,
1642            var,
1643            source: Box::new(source),
1644            where_clause,
1645        })
1646    }
1647
1648    /// `listComprehension : LBRACK filterExpression (STICK expression)?
1649    /// RBRACK` -- `ctx.expression()` here is `listComprehension`'s own
1650    /// direct child (the `STICK`-following projection), not
1651    /// `filterExpression`'s nested one (a different context type, no
1652    /// ambiguity).
1653    fn build_list_comprehension(
1654        &mut self,
1655        ctx: &ListComprehensionContext,
1656    ) -> Result<ReturnExpr, QueryError> {
1657        let fe_ctx = ctx
1658            .filterExpression()
1659            .expect("listComprehension always has a filterExpression");
1660        let (var, source, where_clause) = self.build_filter_expression(&fe_ctx)?;
1661        let project = match ctx.expression() {
1662            Some(expr_ctx) => Some(Box::new(self.visit(&*expr_ctx).into_return_expr()?)),
1663            None => None,
1664        };
1665        Ok(ReturnExpr::ListComp {
1666            var,
1667            source: Box::new(source),
1668            where_clause,
1669            project,
1670        })
1671    }
1672
1673    fn build_function_invocation(
1674        &mut self,
1675        ctx: &FunctionInvocationContext,
1676    ) -> Result<ReturnExpr, QueryError> {
1677        let name_ctx = ctx
1678            .invocationName()
1679            .expect("functionInvocation always has an invocationName");
1680        let name = invocation_name_text(&name_ctx);
1681        let distinct = ctx.DISTINCT().is_some();
1682        let mut args = Vec::new();
1683        if let Some(chain_ctx) = ctx.expressionChain() {
1684            for arg_ctx in chain_ctx.expression_all() {
1685                args.push(self.visit(&*arg_ctx).into_return_expr()?);
1686            }
1687        }
1688        if distinct && !is_aggregate_name(&name) {
1689            return Err(QueryError::Syntax(format!(
1690                "'{name}(DISTINCT ...)' isn't valid — DISTINCT is only meaningful inside an aggregate function"
1691            )));
1692        }
1693        Ok(ReturnExpr::Call {
1694            name,
1695            args,
1696            distinct,
1697        })
1698    }
1699
1700    /// `standaloneCall : CALL invocationName parenExpressionChain? (YIELD
1701    /// (MULT | yieldItems))?` -- the top-level, no-MATCH form (TCK's
1702    /// Call1/Call2). `parenExpressionChain?`'s absence is the implicit-
1703    /// argument shape (`CALL proc`, no parens at all -- `CallClause::args:
1704    /// None`, see its own docs); `MULT` (`YIELD *`) is only reachable
1705    /// here, never from `queryCallSt`'s own grammar production below.
1706    fn build_standalone_call(
1707        &mut self,
1708        ctx: &StandaloneCallContext,
1709    ) -> Result<Statement, QueryError> {
1710        let name_ctx = ctx
1711            .invocationName()
1712            .expect("standaloneCall always has an invocationName");
1713        let name = invocation_name_text(&name_ctx);
1714        let args = match ctx.parenExpressionChain() {
1715            Some(paren_ctx) => Some(self.build_call_args(&paren_ctx)?),
1716            None => None,
1717        };
1718        let yield_items = if ctx.MULT().is_some() {
1719            Some(CallYield::Star)
1720        } else if let Some(yi_ctx) = ctx.yieldItems() {
1721            Some(self.build_yield_items(&yi_ctx)?)
1722        } else {
1723            None
1724        };
1725        Ok(Statement::StandaloneCall(Box::new(CallClause {
1726            name,
1727            args,
1728            with: None,
1729            yield_items,
1730        })))
1731    }
1732
1733    /// `queryCallSt : CALL invocationName parenExpressionChain (YIELD
1734    /// yieldItems)?` -- the in-query reading-clause form (TCK's
1735    /// Call1 `[3]`/`[4]`/etc). Parens are mandatory here (no implicit-
1736    /// argument shape mid-query, TCK's Call2 `[4]`, `@skipGrammarCheck`
1737    /// but structurally impossible to reach via this grammar rule either
1738    /// way) and there's no `YIELD *` alternative (only `standaloneCall`
1739    /// has one).
1740    fn build_query_call_st(
1741        &mut self,
1742        ctx: &QueryCallStContextAll,
1743    ) -> Result<CallClause, QueryError> {
1744        let name_ctx = ctx
1745            .invocationName()
1746            .expect("queryCallSt always has an invocationName");
1747        let name = invocation_name_text(&name_ctx);
1748        let paren_ctx = ctx
1749            .parenExpressionChain()
1750            .expect("queryCallSt always has a parenExpressionChain");
1751        let args = Some(self.build_call_args(&paren_ctx)?);
1752        let yield_items = match ctx.yieldItems() {
1753            Some(yi_ctx) => Some(self.build_yield_items(&yi_ctx)?),
1754            None => None,
1755        };
1756        Ok(CallClause {
1757            name,
1758            args,
1759            with: None,
1760            yield_items,
1761        })
1762    }
1763
1764    fn build_call_args(
1765        &mut self,
1766        ctx: &ParenExpressionChainContextAll,
1767    ) -> Result<Vec<ReturnExpr>, QueryError> {
1768        let mut args = Vec::new();
1769        if let Some(chain_ctx) = ctx.expressionChain() {
1770            for arg_ctx in chain_ctx.expression_all() {
1771                args.push(self.visit(&*arg_ctx).into_return_expr()?);
1772            }
1773        }
1774        Ok(args)
1775    }
1776
1777    /// `yieldItems : yieldItem (COMMA yieldItem)* where?`, `yieldItem :
1778    /// (symbol AS)? symbol` -- one or two `symbol`s per item: two means
1779    /// `a AS c` (the procedure's own declared output name `a`, renamed to
1780    /// `c`), one means the declared name doubles as the binding name too
1781    /// (no rename).
1782    fn build_yield_items(&mut self, ctx: &YieldItemsContextAll) -> Result<CallYield, QueryError> {
1783        let mut items = Vec::new();
1784        for item_ctx in ctx.yieldItem_all() {
1785            let symbols = item_ctx.symbol_all();
1786            let (name, alias) = match symbols.len() {
1787                1 => (symbol_text(&symbols[0]), None),
1788                2 => (symbol_text(&symbols[0]), Some(symbol_text(&symbols[1]))),
1789                other => unreachable!("yieldItem always has 1 or 2 symbols, got {other}"),
1790            };
1791            items.push((name, alias));
1792        }
1793        let where_clause = match ctx.where_() {
1794            Some(where_ctx) => {
1795                let expr_ctx = where_ctx
1796                    .expression()
1797                    .expect("where always has an expression");
1798                let expr = self.visit(&*expr_ctx).into_return_expr()?;
1799                Some(Box::new(return_expr_to_expr(expr)?))
1800            }
1801            None => None,
1802        };
1803        Ok(CallYield::Items(items, where_clause))
1804    }
1805
1806    fn build_parameter(&mut self, ctx: &ParameterContext) -> Result<ReturnExpr, QueryError> {
1807        let name = if let Some(sym_ctx) = ctx.symbol() {
1808            symbol_text(&sym_ctx)
1809        } else if let Some(num_ctx) = ctx.numLit() {
1810            num_ctx
1811                .DIGIT()
1812                .expect("numLit context always has a DIGIT token")
1813                .get_text()
1814        } else {
1815            unreachable!("parameter always has a symbol or numLit")
1816        };
1817        Ok(ReturnExpr::Lit(Literal::Param(name)))
1818    }
1819
1820    fn build_projection_body(
1821        &mut self,
1822        ctx: &ProjectionBodyContext,
1823    ) -> Result<ParsedReturnClause, QueryError> {
1824        let distinct = ctx.DISTINCT().is_some();
1825        let items_ctx = ctx
1826            .projectionItems()
1827            .expect("projectionBody always has projectionItems");
1828        let tail = if items_ctx.MULT().is_some() {
1829            // `projectionItems : (MULT | projectionItem) (COMMA
1830            // projectionItem)*` syntactically allows `RETURN *, x AS y`
1831            // (MULT first, then a COMMA'd projectionItem) -- but
1832            // `Tail::ReturnStar` has no field for extra items alongside
1833            // the star (unlike `WithClause`, which has both `star` and
1834            // `items`), so silently taking the star-only path here would
1835            // drop `x AS y` on the floor. Error instead.
1836            if !items_ctx.projectionItem_all().is_empty() {
1837                return Err(QueryError::Syntax(
1838                    "RETURN * can't be combined with additional items".into(),
1839                ));
1840            }
1841            Tail::ReturnStar(distinct)
1842        } else {
1843            let mut items = Vec::new();
1844            for item_ctx in items_ctx.projectionItem_all() {
1845                let expr_ctx = item_ctx
1846                    .expression()
1847                    .expect("projectionItem always has an expression");
1848                let expr = self.visit(&*expr_ctx).into_return_expr()?;
1849                let alias = item_ctx.symbol().map(|s| symbol_text(&s));
1850                items.push(ReturnItem { expr, alias });
1851            }
1852            Tail::Return(items, distinct)
1853        };
1854
1855        let (order_by, skip, limit) = self.build_order_skip_limit(ctx)?;
1856
1857        Ok(ParsedReturnClause {
1858            tail,
1859            order_by,
1860            skip,
1861            limit,
1862        })
1863    }
1864
1865    /// Shared by `build_projection_body` (RETURN) and `build_with_clause`
1866    /// (WITH) -- both grammar rules bundle `orderSt`/`skipSt`/`limitSt`
1867    /// into the same `projectionBody`.
1868    #[allow(clippy::type_complexity)]
1869    fn build_order_skip_limit(
1870        &mut self,
1871        ctx: &ProjectionBodyContext,
1872    ) -> Result<
1873        (
1874            Option<Vec<(ReturnExpr, SortDir)>>,
1875            Option<ReturnExpr>,
1876            Option<ReturnExpr>,
1877        ),
1878        QueryError,
1879    > {
1880        let order_by = match ctx.orderSt() {
1881            Some(order_ctx) => Some(self.build_order_by(&order_ctx)?),
1882            None => None,
1883        };
1884        let skip = match ctx.skipSt() {
1885            Some(skip_ctx) => {
1886                let expr_ctx = skip_ctx
1887                    .expression()
1888                    .expect("skipSt always has an expression");
1889                Some(self.visit(&*expr_ctx).into_return_expr()?)
1890            }
1891            None => None,
1892        };
1893        let limit = match ctx.limitSt() {
1894            Some(limit_ctx) => {
1895                let expr_ctx = limit_ctx
1896                    .expression()
1897                    .expect("limitSt always has an expression");
1898                Some(self.visit(&*expr_ctx).into_return_expr()?)
1899            }
1900            None => None,
1901        };
1902        Ok((order_by, skip, limit))
1903    }
1904
1905    fn build_order_by(
1906        &mut self,
1907        ctx: &OrderStContext,
1908    ) -> Result<Vec<(ReturnExpr, SortDir)>, QueryError> {
1909        let mut items = Vec::new();
1910        for item_ctx in ctx.orderItem_all() {
1911            let expr_ctx = item_ctx
1912                .expression()
1913                .expect("orderItem always has an expression");
1914            let expr = self.visit(&*expr_ctx).into_return_expr()?;
1915            let dir = if item_ctx.DESC().is_some() || item_ctx.DESCENDING().is_some() {
1916                SortDir::Desc
1917            } else {
1918                SortDir::Asc
1919            };
1920            items.push((expr, dir));
1921        }
1922        Ok(items)
1923    }
1924
1925    fn build_with_clause(&mut self, ctx: &WithStContext) -> Result<WithClause, QueryError> {
1926        let body_ctx = ctx
1927            .projectionBody()
1928            .expect("withSt always has a projectionBody");
1929        let distinct = body_ctx.DISTINCT().is_some();
1930        let items_ctx = body_ctx
1931            .projectionItems()
1932            .expect("projectionBody always has projectionItems");
1933        let star = items_ctx.MULT().is_some();
1934        let mut items = Vec::new();
1935        for item_ctx in items_ctx.projectionItem_all() {
1936            let expr_ctx = item_ctx
1937                .expression()
1938                .expect("projectionItem always has an expression");
1939            let expr = self.visit(&*expr_ctx).into_return_expr()?;
1940            let alias = item_ctx.symbol().map(|s| symbol_text(&s));
1941            items.push(ReturnItem { expr, alias });
1942        }
1943        let (order_by, skip, limit) = self.build_order_skip_limit(&body_ctx)?;
1944        let where_clause = match ctx.where_() {
1945            Some(where_ctx) => {
1946                let expr_ctx = where_ctx
1947                    .expression()
1948                    .expect("where always has an expression");
1949                let expr = self.visit(&*expr_ctx).into_return_expr()?;
1950                Some(return_expr_to_with_expr(expr))
1951            }
1952            None => None,
1953        };
1954        Ok(WithClause {
1955            items,
1956            star,
1957            distinct,
1958            where_clause,
1959            order_by,
1960            skip,
1961            limit,
1962        })
1963    }
1964
1965    /// `UnwindClause::where_clause`/`::with` are populated wherever mars's
1966    /// own AST assembly attaches a following `WHERE`/`WITH` -- neither is
1967    /// part of `unwindSt`'s own grammar (`UNWIND expression AS symbol`,
1968    /// no trailing clauses at all), unlike pest's grammar, which does let
1969    /// UNWIND carry an inline WHERE directly (a mars-specific extension
1970    /// beyond real openCypher syntax, per `UnwindClause::where_clause`'s
1971    /// own docs). Always `None` here; a real capability gap versus pest
1972    /// for this specific extension, not a deferred-for-now stub.
1973    fn build_unwind_st(&mut self, ctx: &UnwindStContext) -> Result<UnwindClause, QueryError> {
1974        let expr_ctx = ctx.expression().expect("unwindSt always has an expression");
1975        let source = UnwindSource(self.visit(&*expr_ctx).into_return_expr()?);
1976        let var_ctx = ctx.symbol().expect("unwindSt always has a symbol");
1977        Ok(UnwindClause {
1978            source,
1979            var: symbol_text(&var_ctx),
1980            where_clause: None,
1981            with: None,
1982        })
1983    }
1984
1985    fn build_set_st(&mut self, ctx: &SetStContext) -> Result<Vec<SetItem>, QueryError> {
1986        ctx.setItem_all()
1987            .into_iter()
1988            .map(|item_ctx| self.build_set_item(&item_ctx))
1989            .collect()
1990    }
1991
1992    fn build_set_item(&mut self, ctx: &SetItemContextAll) -> Result<SetItem, QueryError> {
1993        // `setItem`'s first alternative is `propertyExpression ASSIGN
1994        // expression`, and `propertyExpression`'s own zero-`.name`-suffix
1995        // form degenerates to a bare variable -- so `n = {...}` (no dots
1996        // at all) parses through *this* alternative too, not the
1997        // `symbol ASSIGN expression` one below (which ANTLR only reaches
1998        // for `+=`, since alternative one has no ADD_ASSIGN option at
1999        // all). `build_property_expression`'s result tells them apart:
2000        // `Prop` is real `x.prop` access; `Var` is the degenerate case,
2001        // meaning `SetItem::MapAssign` (never `merge: true` here --
2002        // that's only reachable via `+=`, which can't take this branch).
2003        if let Some(prop_ctx) = ctx.propertyExpression() {
2004            let expr_ctx = ctx
2005                .expression()
2006                .expect("setItem's propertyExpression form always has an expression");
2007            return match self.build_property_expression(&prop_ctx)? {
2008                ReturnExpr::Prop(prop) => {
2009                    let value = self.visit(&*expr_ctx).into_return_expr()?;
2010                    Ok(SetItem::Prop(prop, value))
2011                }
2012                ReturnExpr::Var(var) => {
2013                    let value = self.visit(&*expr_ctx).into_return_expr()?;
2014                    Ok(SetItem::MapAssign {
2015                        var,
2016                        value,
2017                        merge: false,
2018                    })
2019                }
2020                _ => Err(QueryError::Syntax(
2021                    "expected a property access (x.prop) or variable on the left of SET's `=`"
2022                        .into(),
2023                )),
2024            };
2025        }
2026        let sym_ctx = ctx
2027            .symbol()
2028            .expect("setItem always has a propertyExpression or symbol");
2029        let var = symbol_text(&sym_ctx);
2030        if let Some(labels_ctx) = ctx.nodeLabels() {
2031            let labels = labels_ctx.name_all().iter().map(|n| name_text(n)).collect();
2032            return Ok(SetItem::Labels(var, labels));
2033        }
2034        let expr_ctx = ctx
2035            .expression()
2036            .expect("setItem's symbol-assign form always has an expression");
2037        let value = self.visit(&*expr_ctx).into_return_expr()?;
2038        Ok(SetItem::MapAssign {
2039            var,
2040            value,
2041            merge: ctx.ADD_ASSIGN().is_some(),
2042        })
2043    }
2044
2045    fn build_delete_st(&mut self, ctx: &DeleteStContext) -> Result<ParsedDelete, QueryError> {
2046        let chain_ctx = ctx
2047            .expressionChain()
2048            .expect("deleteSt always has an expressionChain");
2049        let mut items = Vec::new();
2050        for expr_ctx in chain_ctx.expression_all() {
2051            items.push(self.visit(&*expr_ctx).into_return_expr()?);
2052        }
2053        Ok(ParsedDelete {
2054            items,
2055            detach: ctx.DETACH().is_some(),
2056        })
2057    }
2058
2059    fn build_remove_st(&mut self, ctx: &RemoveStContext) -> Result<Vec<RemoveItem>, QueryError> {
2060        ctx.removeItem_all()
2061            .into_iter()
2062            .map(|item_ctx| self.build_remove_item(&item_ctx))
2063            .collect()
2064    }
2065
2066    fn build_remove_item(&mut self, ctx: &RemoveItemContextAll) -> Result<RemoveItem, QueryError> {
2067        if let Some(prop_ctx) = ctx.propertyExpression() {
2068            return Ok(RemoveItem::Prop(self.build_prop_access(&prop_ctx)?));
2069        }
2070        let sym_ctx = ctx
2071            .symbol()
2072            .expect("removeItem always has a symbol+nodeLabels or a propertyExpression");
2073        let labels_ctx = ctx
2074            .nodeLabels()
2075            .expect("removeItem's symbol form always has nodeLabels");
2076        let labels = labels_ctx.name_all().iter().map(|n| name_text(n)).collect();
2077        Ok(RemoveItem::Labels(symbol_text(&sym_ctx), labels))
2078    }
2079
2080    /// `propertyExpression`'s own grammar rule is reused by `setItem`/
2081    /// `removeItem` for their `x.prop` alternative -- `build_property_
2082    /// expression` already builds exactly `ReturnExpr::Prop` for that
2083    /// shape (or errors for anything wider, chained access etc), so this
2084    /// just unwraps the one variant these two callers can ever legally
2085    /// see here (the grammar alternative they're on doesn't admit a bare
2086    /// `symbol` or anything else propertyExpression could otherwise
2087    /// produce).
2088    fn build_prop_access(
2089        &mut self,
2090        ctx: &PropertyExpressionContext,
2091    ) -> Result<PropAccess, QueryError> {
2092        match self.build_property_expression(ctx)? {
2093            ReturnExpr::Prop(p) => Ok(p),
2094            _ => Err(QueryError::Syntax(
2095                "expected a property access (x.prop)".into(),
2096            )),
2097        }
2098    }
2099
2100    /// `Statement::Create`'s `Vec<Pattern>` has no named-path-capture slot
2101    /// at all (unlike `QueryPart::path_var`), and unlike `MATCH`, CREATE's
2102    /// comma-separated patterns are never spliced into linear chains --
2103    /// each becomes its own independent `Pattern` directly (matches
2104    /// `parser.rs`'s `parse_create_patterns`, which does the same, no
2105    /// `group_into_linear_patterns` call).
2106    fn build_create_st(&mut self, ctx: &CreateStContext) -> Result<Vec<Pattern>, QueryError> {
2107        let pattern_ctx = ctx.pattern().expect("createSt always has a pattern");
2108        pattern_ctx
2109            .patternPart_all()
2110            .into_iter()
2111            .map(|part_ctx| {
2112                if part_ctx.ASSIGN().is_some() {
2113                    return Err(QueryError::Syntax(
2114                        "named-path capture (`p = ...`) isn't supported on CREATE".into(),
2115                    ));
2116                }
2117                if part_ctx.shortestPathWrapper().is_some() {
2118                    return Err(QueryError::Syntax(
2119                        "shortestPath() isn't valid in CREATE".into(),
2120                    ));
2121                }
2122                let elem_ctx = part_ctx.patternElem().expect(
2123                    "patternPart always has a patternElem when shortestPathWrapper is absent",
2124                );
2125                self.visit(&*elem_ctx).into_pattern()
2126            })
2127            .collect()
2128    }
2129
2130    /// Mirrors `parser.rs`'s `parse_merge_clause`: `MergeClause::pattern`
2131    /// caps at one relationship hop (checked here, not the grammar, which
2132    /// permissively allows any hop count via the same `patternElem` every
2133    /// other pattern context uses), and real Cypher rejects more than one
2134    /// `ON CREATE`/`ON MATCH` on the same MERGE (also grammar-permissive,
2135    /// `mergeAction*` allows any order/count) -- same "grammar permissive,
2136    /// builder enforces the exact constraint" split used there.
2137    /// `p = ...` named-path capture (unlike `build_create_st`, which still
2138    /// rejects it) is supported here -- MERGE's own pattern is simple
2139    /// enough (at most one hop, no `shortestPath()`, no variable-length
2140    /// hop) that `executor::merge_one_row` can just reuse ordinary MATCH's
2141    /// own `name_pattern_for_path`/`assemble_path` machinery directly, no
2142    /// bespoke path-assembly logic needed.
2143    fn build_merge_st(&mut self, ctx: &MergeStContext) -> Result<MergeClause, QueryError> {
2144        let part_ctx = ctx.patternPart().expect("mergeSt always has a patternPart");
2145        let path_var = if part_ctx.ASSIGN().is_some() {
2146            let symbol_ctx = part_ctx
2147                .symbol()
2148                .expect("patternPart with ASSIGN always has a symbol");
2149            Some(symbol_text(&symbol_ctx))
2150        } else {
2151            None
2152        };
2153        if part_ctx.shortestPathWrapper().is_some() {
2154            return Err(QueryError::Syntax(
2155                "shortestPath() isn't valid in MERGE".into(),
2156            ));
2157        }
2158        let elem_ctx = part_ctx
2159            .patternElem()
2160            .expect("patternPart always has a patternElem when shortestPathWrapper is absent");
2161        let pattern = self.visit(&*elem_ctx).into_pattern()?;
2162        if pattern.hops.len() > 1 {
2163            return Err(QueryError::Syntax(
2164                "MERGE with more than one relationship hop isn't supported yet — split it into a MATCH \
2165                 for the already-known part and a MERGE for one new hop"
2166                    .into(),
2167            ));
2168        }
2169
2170        let mut on_create = Vec::new();
2171        let mut on_match = Vec::new();
2172        for action_ctx in ctx.mergeAction_all() {
2173            let set_items = self.build_merge_action(&action_ctx)?;
2174            if action_ctx.MATCH().is_some() {
2175                if !on_match.is_empty() {
2176                    return Err(QueryError::Syntax(
2177                        "MERGE can have at most one ON MATCH SET clause".into(),
2178                    ));
2179                }
2180                on_match = set_items;
2181            } else {
2182                if !on_create.is_empty() {
2183                    return Err(QueryError::Syntax(
2184                        "MERGE can have at most one ON CREATE SET clause".into(),
2185                    ));
2186                }
2187                on_create = set_items;
2188            }
2189        }
2190
2191        Ok(MergeClause {
2192            pattern,
2193            path_var,
2194            on_create,
2195            on_match,
2196            with: None,
2197        })
2198    }
2199
2200    fn build_merge_action(
2201        &mut self,
2202        ctx: &MergeActionContextAll,
2203    ) -> Result<Vec<SetItem>, QueryError> {
2204        let set_ctx = ctx.setSt().expect("mergeAction always has a setSt");
2205        self.build_set_st(&set_ctx)
2206    }
2207
2208    /// `readingStatement : matchSt | unwindSt | queryCallSt`. `matchSt` can
2209    /// expand to more than one `QueryClause::Match` (comma-separated
2210    /// disjoint patterns splice into separate `QueryPart`s -- see
2211    /// `build_match_st`'s docs), so this appends rather than returning a
2212    /// single clause. `queryCallSt` (`CALL proc(...) YIELD ...` used as a
2213    /// reading clause) builds a `QueryClause::Call` -- unlike
2214    /// `standaloneCall`'s own grammar rule, this one's `parenExpressionChain`
2215    /// is mandatory (no implicit-argument form in-query) and its `YIELD`
2216    /// has no `*` alternative (only `yieldItems`), see `CallClause`'s own
2217    /// docs.
2218    fn append_reading_statement(
2219        &mut self,
2220        ctx: &ReadingStatementContextAll,
2221        clauses: &mut Vec<QueryClause>,
2222    ) -> Result<(), QueryError> {
2223        if let Some(match_ctx) = ctx.matchSt() {
2224            let parts = self.visit(&*match_ctx).into_query_parts()?;
2225            clauses.extend(parts.into_iter().map(QueryClause::Match));
2226            return Ok(());
2227        }
2228        if let Some(unwind_ctx) = ctx.unwindSt() {
2229            let clause = self.visit(&*unwind_ctx).into_unwind_clause()?;
2230            clauses.push(QueryClause::Unwind(clause));
2231            return Ok(());
2232        }
2233        let call_ctx = ctx
2234            .queryCallSt()
2235            .expect("readingStatement is matchSt | unwindSt | queryCallSt");
2236        let call = self.build_query_call_st(&call_ctx)?;
2237        clauses.push(QueryClause::Call(call));
2238        Ok(())
2239    }
2240
2241    /// `updatingStatement : createSt | mergeSt | deleteSt | setSt |
2242    /// removeSt`, used where it's just another clause in the sequence (not
2243    /// the statement's final tail -- see `build_mutating_tail` for that
2244    /// position instead).
2245    fn build_updating_statement_as_clause(
2246        &mut self,
2247        ctx: &UpdatingStatementContextAll,
2248    ) -> Result<QueryClause, QueryError> {
2249        if let Some(create_ctx) = ctx.createSt() {
2250            return Ok(QueryClause::Create(
2251                self.visit(&*create_ctx).into_create_patterns()?,
2252            ));
2253        }
2254        if let Some(merge_ctx) = ctx.mergeSt() {
2255            return Ok(QueryClause::Merge(
2256                self.visit(&*merge_ctx).into_merge_clause()?,
2257            ));
2258        }
2259        if let Some(delete_ctx) = ctx.deleteSt() {
2260            let d = self.visit(&*delete_ctx).into_delete_items()?;
2261            return Ok(QueryClause::Delete {
2262                items: d.items,
2263                detach: d.detach,
2264            });
2265        }
2266        if let Some(set_ctx) = ctx.setSt() {
2267            return Ok(QueryClause::Set(self.visit(&*set_ctx).into_set_items()?));
2268        }
2269        let remove_ctx = ctx
2270            .removeSt()
2271            .expect("updatingStatement always has one of its 5 alternatives");
2272        Ok(QueryClause::Remove(
2273            self.visit(&*remove_ctx).into_remove_items()?,
2274        ))
2275    }
2276
2277    /// The statement's final mutating clause (`createSt`/`deleteSt`/
2278    /// `setSt`/`removeSt` -- never `mergeSt`, which has no `Tail` variant
2279    /// at all and always becomes a `QueryClause::Merge` entry even when
2280    /// it's last, per `Statement::Match`'s own "missing tail is only valid
2281    /// with a MERGE clause" rule) folds into a `Tail::X(_, Option
2282    /// <ReturnTail>)`, consuming an optional trailing `returnSt` as a
2283    /// narrower `ReturnTail` (items + distinct only, matching pest's
2284    /// `ReturnTail`, which has no other fields either). `RETURN *` isn't
2285    /// supported in this position (`ReturnTail` has no star-resolution
2286    /// site -- mirrors `parser.rs`'s `parse_mutating_tail`, same
2287    /// real restriction there too, confirmed via the TCK). ORDER BY/SKIP/
2288    /// LIMIT, though, are NOT restricted here (an earlier version of this
2289    /// function wrongly rejected them, found via a full TCK parse-parity
2290    /// run -- `MATCH (n) DELETE n RETURN 42 LIMIT 0` is real, TCK-tested
2291    /// Cypher) -- returned to the caller instead, which places them on the
2292    /// *statement's* own `order_by`/`skip`/`limit` fields, same as pest:
2293    /// its `mutating_tail` rule has no order/skip/limit slot of its own at
2294    /// all, they're siblings of `tail_clause` at `match_stmt`'s own level
2295    /// (`clause* ~ tail_clause? ~ order_by_clause? ~ skip_clause? ~
2296    /// limit_clause?`), applying regardless of which `Tail` variant is
2297    /// active. This grammar just nests them inside `returnSt`'s own
2298    /// `projectionBody` structurally instead of keeping them as separate
2299    /// statement-level siblings -- same semantics, different grammar shape.
2300    #[allow(clippy::type_complexity)]
2301    fn build_mutating_tail(
2302        &mut self,
2303        ctx: &UpdatingStatementContextAll,
2304        return_ctx: Option<&ReturnStContext>,
2305    ) -> Result<
2306        (
2307            Tail,
2308            Option<Vec<(ReturnExpr, SortDir)>>,
2309            Option<ReturnExpr>,
2310            Option<ReturnExpr>,
2311        ),
2312        QueryError,
2313    > {
2314        let mut order_by = None;
2315        let mut skip = None;
2316        let mut limit = None;
2317        let ret = match return_ctx {
2318            Some(return_ctx) => {
2319                let c = self.visit(return_ctx).into_return_clause()?;
2320                order_by = c.order_by;
2321                skip = c.skip;
2322                limit = c.limit;
2323                let Tail::Return(items, distinct) = c.tail else {
2324                    return Err(QueryError::Syntax(
2325                        "RETURN * isn't supported as a mutating clause's own trailing RETURN"
2326                            .into(),
2327                    ));
2328                };
2329                Some(ReturnTail { items, distinct })
2330            }
2331            None => None,
2332        };
2333        let tail = if let Some(create_ctx) = ctx.createSt() {
2334            Tail::Create(self.visit(&*create_ctx).into_create_patterns()?, ret)
2335        } else if let Some(delete_ctx) = ctx.deleteSt() {
2336            let d = self.visit(&*delete_ctx).into_delete_items()?;
2337            if d.detach {
2338                Tail::DetachDelete(d.items, ret)
2339            } else {
2340                Tail::Delete(d.items, ret)
2341            }
2342        } else if let Some(set_ctx) = ctx.setSt() {
2343            Tail::Set(self.visit(&*set_ctx).into_set_items()?, ret)
2344        } else {
2345            let remove_ctx = ctx
2346                .removeSt()
2347                .expect("build_mutating_tail's caller already excluded mergeSt");
2348            Tail::Remove(self.visit(&*remove_ctx).into_remove_items()?, ret)
2349        };
2350        Ok((tail, order_by, skip, limit))
2351    }
2352
2353    /// `singlePartQ : readingStatement* (returnSt | updatingStatement+
2354    /// returnSt?)`. No WITH chaining at this level at all (that's
2355    /// `multiPartQ`'s job, not yet wired up -- see this file's module
2356    /// doc). Mirrors `parser.rs`'s `parse_match_stmt` for the no-WITH
2357    /// case: leading reading statements become `QueryClause`s; either a
2358    /// bare `returnSt` becomes the statement's `Tail::Return`/`ReturnStar`
2359    /// (with ORDER BY/SKIP/LIMIT at the statement level, where they
2360    /// belong for this form), or the *last* updating statement becomes the
2361    /// tail (see `build_mutating_tail`) with every earlier one just
2362    /// another `QueryClause`, unless that last one is `mergeSt` (never a
2363    /// tail -- see that function's docs), in which case a trailing
2364    /// `returnSt`, if present, becomes the statement's own `Tail::Return`
2365    /// instead.
2366    fn build_single_part_q(&mut self, ctx: &SinglePartQContext) -> Result<Statement, QueryError> {
2367        let mut clauses = Vec::new();
2368        for rs_ctx in ctx.readingStatement_all() {
2369            self.append_reading_statement(&rs_ctx, &mut clauses)?;
2370        }
2371
2372        let updating = ctx.updatingStatement_all();
2373        let return_ctx = ctx.returnSt();
2374
2375        // Bare `CREATE (...)` with nothing else at all (no leading MATCH/
2376        // UNWIND, no trailing RETURN, no other updating clause) -- mirrors
2377        // pest's `create_stmt_only` (`create_stmt ~ !(return_clause |
2378        // chainable_clause_follows)`), producing a real `Statement::Create`
2379        // directly instead of wrapping in `Statement::Match` with a
2380        // `Tail::Create`. Found via a Phase 3 dry-run behavioral test
2381        // failure (`explain_never_mutates_even_a_write_statement`):
2382        // `explain.rs`'s "no query plan" output depends on this exact
2383        // shape distinction, not just equivalent semantics.
2384        if clauses.is_empty() && return_ctx.is_none() && updating.len() == 1 {
2385            if let Some(create_ctx) = updating[0].createSt() {
2386                let patterns = self.visit(&*create_ctx).into_create_patterns()?;
2387                return Ok(Statement::Create(patterns));
2388            }
2389        }
2390
2391        let mut tail = None;
2392        let mut order_by = None;
2393        let mut skip = None;
2394        let mut limit = None;
2395        let mut consumed_return = false;
2396
2397        if let Some((last, earlier)) = updating.split_last() {
2398            for us_ctx in earlier {
2399                clauses.push(self.build_updating_statement_as_clause(us_ctx)?);
2400            }
2401            if last.mergeSt().is_some() {
2402                clauses.push(self.build_updating_statement_as_clause(last)?);
2403            } else {
2404                let (t, ob, sk, lim) = self.build_mutating_tail(last, return_ctx.as_deref())?;
2405                tail = Some(t);
2406                order_by = ob;
2407                skip = sk;
2408                limit = lim;
2409                consumed_return = return_ctx.is_some();
2410            }
2411        }
2412
2413        if !consumed_return {
2414            if let Some(return_ctx) = return_ctx {
2415                let c = self.visit(&*return_ctx).into_return_clause()?;
2416                tail = Some(c.tail);
2417                order_by = c.order_by;
2418                skip = c.skip;
2419                limit = c.limit;
2420            }
2421        }
2422
2423        if tail.is_none() && !clauses.iter().any(|c| matches!(c, QueryClause::Merge(_))) {
2424            return Err(QueryError::Syntax(
2425                "a query needs a RETURN/DELETE/SET tail, unless it has a MERGE clause with nothing after it".into(),
2426            ));
2427        }
2428
2429        Ok(Statement::Match {
2430            clauses,
2431            tail,
2432            order_by,
2433            skip: skip.map(Box::new),
2434            limit: limit.map(Box::new),
2435        })
2436    }
2437
2438    /// `multiPartQ : readingStatement* ((readingStatement | updatingStatement)*
2439    /// withSt)+ singlePartQ` -- one or more WITH boundaries, each preceded by
2440    /// zero or more reading/updating statements, followed by a final
2441    /// `singlePartQ` (itself another `readingStatement*` run plus the
2442    /// statement's real tail). The grammar's typed accessors
2443    /// (`readingStatement_all`/`updatingStatement_all`/`withSt_all`) each
2444    /// flatten across every group, losing which items came before which
2445    /// `withSt` -- recovered by sorting all three by source position
2446    /// (`start().get_token_index()`) instead of walking raw children (which
2447    /// would need runtime downcasting to tell a `readingStatement` from an
2448    /// `updatingStatement` from a `withSt`).
2449    ///
2450    /// A `withSt` attaches to the immediately preceding MATCH/UNWIND/MERGE
2451    /// clause's own `with` field (only the *last* one, for a comma
2452    /// cross-join `matchSt`) -- same as `parser.rs`'s `parse_match_part`/
2453    /// `parse_merge_clause`/`parse_unwind_clause`. If nothing attachable
2454    /// immediately precedes it (statement-leading, or right after a
2455    /// SET/DELETE/REMOVE/CREATE -- none of which have a `with` field on
2456    /// their `QueryClause` variant -- or right after another `withSt`), it
2457    /// becomes its own standalone `QueryClause::With` entry, mirroring
2458    /// pest's `clause = { ... | with_clause | ... }` alternative.
2459    fn build_multi_part_q(&mut self, ctx: &MultiPartQContext) -> Result<Statement, QueryError> {
2460        enum Item<'i> {
2461            Reading(Rc<ReadingStatementContextAll<'i>>),
2462            Updating(Rc<UpdatingStatementContextAll<'i>>),
2463            With(Rc<WithStContext<'i>>),
2464        }
2465        let mut items: Vec<(isize, Item)> = Vec::new();
2466        for rs in ctx.readingStatement_all() {
2467            let idx = rs.start().get_token_index();
2468            items.push((idx, Item::Reading(rs)));
2469        }
2470        for us in ctx.updatingStatement_all() {
2471            let idx = us.start().get_token_index();
2472            items.push((idx, Item::Updating(us)));
2473        }
2474        for w in ctx.withSt_all() {
2475            let idx = w.start().get_token_index();
2476            items.push((idx, Item::With(w)));
2477        }
2478        items.sort_by_key(|(idx, _)| *idx);
2479
2480        let mut clauses: Vec<QueryClause> = Vec::new();
2481        let mut attach_target: Option<usize> = None;
2482        for (_, item) in items {
2483            match item {
2484                Item::Reading(rs) => {
2485                    self.append_reading_statement(&rs, &mut clauses)?;
2486                    attach_target = Some(clauses.len() - 1);
2487                }
2488                Item::Updating(us) => {
2489                    let clause = self.build_updating_statement_as_clause(&us)?;
2490                    let can_attach = matches!(clause, QueryClause::Merge(_));
2491                    clauses.push(clause);
2492                    attach_target = can_attach.then_some(clauses.len() - 1);
2493                }
2494                Item::With(w) => {
2495                    let with = self.visit(&*w).into_with_clause()?;
2496                    match attach_target.take() {
2497                        Some(i) => match &mut clauses[i] {
2498                            QueryClause::Match(part) => part.with = Some(with),
2499                            QueryClause::Unwind(u) => u.with = Some(with),
2500                            QueryClause::Merge(m) => m.with = Some(with),
2501                            QueryClause::Call(call) => call.with = Some(with),
2502                            _ => unreachable!(
2503                                "attach_target is only ever set right after pushing a Match/Unwind/Merge/Call clause"
2504                            ),
2505                        },
2506                        None => clauses.push(QueryClause::With(with)),
2507                    }
2508                }
2509            }
2510        }
2511
2512        let sp_ctx = ctx
2513            .singlePartQ()
2514            .expect("multiPartQ always ends in a singlePartQ");
2515        // `build_single_part_q` can also return a bare `Statement::Create`
2516        // directly (its own "CREATE with nothing else at all" special
2517        // case, mirroring pest's `create_stmt_only`) -- but nested inside
2518        // a `multiPartQ` (past at least one `WITH` boundary already),
2519        // that's still just this statement's final `Tail::Create`, same
2520        // as an ordinary trailing `CREATE` would be. Only a genuinely
2521        // top-level, whole-statement bare CREATE gets the dedicated
2522        // `Statement::Create` shape (`explain.rs`'s "no query plan" case).
2523        let (tail_clauses, tail, order_by, skip, limit) =
2524            match self.build_single_part_q(&sp_ctx)? {
2525                Statement::Match {
2526                    clauses,
2527                    tail,
2528                    order_by,
2529                    skip,
2530                    limit,
2531                } => (clauses, tail, order_by, skip, limit),
2532                Statement::Create(patterns) => {
2533                    (Vec::new(), Some(Tail::Create(patterns, None)), None, None, None)
2534                }
2535                other => unreachable!(
2536                    "build_single_part_q only ever returns Statement::Match or Statement::Create, got {other:?}"
2537                ),
2538            };
2539        clauses.extend(tail_clauses);
2540        Ok(Statement::Match {
2541            clauses,
2542            tail,
2543            order_by,
2544            skip,
2545            limit,
2546        })
2547    }
2548
2549    /// `explainSt : EXPLAIN (createIndexSt | regularQuery)` -- mars-specific
2550    /// grammar extension (this file's own local addition, not from
2551    /// upstream `antlr/grammars-v4/cypher`; see `grammar/README.md`), no
2552    /// real openCypher equivalent. Mirrors `parser.rs`'s `parse_explain_stmt`.
2553    fn build_explain_st(&mut self, ctx: &ExplainStContext) -> Result<Statement, QueryError> {
2554        let inner = match ctx.createIndexSt() {
2555            Some(ci_ctx) => self.build_create_index_st(&ci_ctx)?,
2556            None => {
2557                let rq_ctx = ctx
2558                    .regularQuery()
2559                    .expect("explainSt always has a createIndexSt or regularQuery");
2560                self.visit(&*rq_ctx).into_statement()?
2561            }
2562        };
2563        Ok(Statement::Explain(Box::new(inner)))
2564    }
2565
2566    /// `createIndexSt : CREATE INDEX ON COLON name LPAREN name RPAREN
2567    /// UNIQUE?` -- same mars-specific-extension caveat as `build_explain_st`
2568    /// above. Mirrors `parser.rs`'s `parse_create_index_stmt`; `name_all()`
2569    /// returns the label then the property name in source order (the only
2570    /// two `name` children this rule ever has).
2571    fn build_create_index_st(
2572        &mut self,
2573        ctx: &CreateIndexStContext,
2574    ) -> Result<Statement, QueryError> {
2575        let names = ctx.name_all();
2576        let label = name_text(
2577            names
2578                .first()
2579                .expect("createIndexSt always has a label name"),
2580        );
2581        let prop = name_text(
2582            names
2583                .get(1)
2584                .expect("createIndexSt always has a property name"),
2585        );
2586        Ok(Statement::CreateIndex {
2587            label,
2588            prop,
2589            unique: ctx.UNIQUE().is_some(),
2590        })
2591    }
2592
2593    /// `regularQuery : singleQuery unionSt*`. No `unionSt` at all just
2594    /// passes the single `Statement` straight through -- `singleQuery`
2595    /// itself (`singlePartQ | multiPartQ`) needs no override, default
2596    /// dispatch already routes to whichever of those two produced the
2597    /// `Statement`. Otherwise mirrors `parser.rs`'s `parse_union_stmt`:
2598    /// every `unionSt`'s `ALL` presence must agree (real Cypher rejects
2599    /// mixing bare `UNION` and `UNION ALL` in one statement), checked here
2600    /// rather than in the grammar since it's only knowable once every
2601    /// occurrence is in hand.
2602    fn build_regular_query(&mut self, ctx: &RegularQueryContext) -> Result<Statement, QueryError> {
2603        let sq_ctx = ctx
2604            .singleQuery()
2605            .expect("regularQuery always has a singleQuery");
2606        let first = self.visit(&*sq_ctx).into_statement()?;
2607        let unions = ctx.unionSt_all();
2608        if unions.is_empty() {
2609            return Ok(first);
2610        }
2611        let mut parts = vec![first];
2612        let mut all: Option<bool> = None;
2613        for u_ctx in unions {
2614            let this_all = u_ctx.ALL().is_some();
2615            match all {
2616                None => all = Some(this_all),
2617                Some(prev) if prev != this_all => {
2618                    return Err(QueryError::Syntax(
2619                        "can't mix UNION and UNION ALL in the same statement".into(),
2620                    ));
2621                }
2622                Some(_) => {}
2623            }
2624            let part_sq = u_ctx
2625                .singleQuery()
2626                .expect("unionSt always has a singleQuery");
2627            parts.push(self.visit(&*part_sq).into_statement()?);
2628        }
2629        Ok(Statement::Union {
2630            parts,
2631            all: all.unwrap_or(false),
2632        })
2633    }
2634}
2635
2636/// The real implementation behind `lib.rs`'s public `parse` -- the
2637/// pest-based `parser.rs`/`cypher.pest` this replaced are gone (see
2638/// `grammar/README.md`).
2639pub fn parse_antlr(input: &str) -> Result<Statement, QueryError> {
2640    use crate::generated::cypherlexer::CypherLexer;
2641    use crate::generated::cypherparser::{CypherParser, ScriptContextAttrs};
2642    use antlr4rust::common_token_stream::CommonTokenStream;
2643    use antlr4rust::error_listener::ErrorListener;
2644    use antlr4rust::recognizer::Recognizer;
2645    use antlr4rust::token_factory::TokenFactory;
2646    use antlr4rust::InputStream;
2647    use antlr4rust::Parser as _;
2648    use std::cell::RefCell;
2649
2650    struct CollectErrors(Rc<RefCell<Vec<String>>>);
2651    impl<'a, T: Recognizer<'a>> ErrorListener<'a, T> for CollectErrors {
2652        fn syntax_error(
2653            &self,
2654            _recognizer: &T,
2655            _offending_symbol: Option<&<T::TF as TokenFactory<'a>>::Inner>,
2656            line: isize,
2657            column: isize,
2658            msg: &str,
2659            _e: Option<&antlr4rust::errors::ANTLRError>,
2660        ) {
2661            self.0
2662                .borrow_mut()
2663                .push(format!("line {line}:{column} {msg}"));
2664        }
2665    }
2666
2667    let errors = Rc::new(RefCell::new(Vec::new()));
2668    let stream = InputStream::new(input);
2669    let mut lexer = CypherLexer::new(stream);
2670    lexer.remove_error_listeners();
2671    lexer.add_error_listener(Box::new(CollectErrors(errors.clone())));
2672    let tokens = CommonTokenStream::new(lexer);
2673    let mut parser = CypherParser::new(tokens);
2674    parser.remove_error_listeners();
2675    parser.add_error_listener(Box::new(CollectErrors(errors.clone())));
2676    let ctx = parser
2677        .script()
2678        .map_err(|e| QueryError::Syntax(e.to_string()))?;
2679    if let Some(msg) = errors.borrow().first() {
2680        return Err(QueryError::Syntax(format!("syntax error: {msg}")));
2681    }
2682    // `script : query SEMI? EOF` -- visiting the whole tree would run
2683    // straight into the default `aggregate_results`' unconditional
2684    // "last child wins" rule (not "last *non-default*", despite this
2685    // file's other alternation rules getting away with relying on that
2686    // distinction -- see this function's own docs): the trailing `EOF`
2687    // terminal has no `visit_X` hook of its own, so it'd overwrite
2688    // `query`'s real result with `AstNode::None`. Visiting `query`
2689    // directly sidesteps it -- `script`'s own job (rejecting trailing
2690    // garbage after a valid query) is already done by the `parser.script()`
2691    // call above succeeding.
2692    let query_ctx = ctx.query().expect("script always has a query");
2693    AstBuilder::new().visit(&*query_ctx).into_statement()
2694}
2695
2696/// The real implementation behind `lib.rs`'s public `parse_many` --
2697/// parses a `;`-separated batch of one or more statements (`"CREATE (a);
2698/// CREATE (b); MATCH (n) RETURN n"`). Splits the input into individual
2699/// statements itself (`split_statements`, respecting Cypher's quoting
2700/// rules) and parses each one independently via `parse_antlr`, rather
2701/// than parsing the whole batch as one shared ANTLR tree the way the
2702/// grammar's own `queries : query (SEMI query)* EOF` rule (a
2703/// mars-specific extension, see `grammar/README.md`) would: building one
2704/// tree for a large batch means every statement's tree is alive in
2705/// memory simultaneously until the last one is converted to a
2706/// lightweight `Statement` and the whole tree can finally drop.
2707/// Confirmed via `/usr/bin/time -l`: a real 29MB/9,771-statement import
2708/// script peaked at 13GB RSS in the parse step alone (before any
2709/// execution) parsed the old way. Splitting first means only the
2710/// *largest single statement's* tree is ever alive at once.
2711///
2712/// Also strips a single genuinely-trailing `;` first, same as before --
2713/// `script : query SEMI? EOF` (what `parse_antlr` uses per statement)
2714/// already tolerates one, but stripping it here first keeps
2715/// `split_statements` from ever seeing a trailing empty segment.
2716pub fn parse_antlr_many(input: &str) -> Result<Vec<Statement>, QueryError> {
2717    let trimmed = input.trim_end();
2718    let trimmed = trimmed.strip_suffix(';').unwrap_or(trimmed);
2719    split_statements(trimmed)
2720        .into_iter()
2721        .map(parse_antlr)
2722        .collect()
2723}
2724
2725/// Splits `;`-separated statement text into individual statement slices
2726/// without building any parse tree -- a `;` inside a single-quoted
2727/// (`'...'`), double-quoted (`"..."`), or backtick-quoted (`` `...` ``)
2728/// region is never treated as a separator, matching exactly what the
2729/// lexer's own `CHAR_LITERAL`/`STRING_LITERAL`/`ESC_LITERAL` rules
2730/// consider part of the literal (see `grammar/CypherLexer.g4`).
2731/// Backtick-quoted identifiers have no escape sequences in this grammar
2732/// (`ESC_LITERAL : '`' .*? '`'`) -- a backslash there is just a literal
2733/// character, not an escape introducer, unlike inside the other two.
2734/// Doesn't validate escape sequences itself (that's `parse_antlr`'s job
2735/// once each slice is actually parsed) -- only tracks "am I currently
2736/// inside a quoted region" well enough to find the real separators.
2737pub fn split_statements(input: &str) -> Vec<&str> {
2738    let bytes = input.as_bytes();
2739    let mut starts = vec![0usize];
2740    let mut semicolons = Vec::new();
2741    let mut quote: Option<u8> = None;
2742    let mut i = 0;
2743    while i < bytes.len() {
2744        let b = bytes[i];
2745        match quote {
2746            Some(q) => {
2747                if b == b'\\' && q != b'`' {
2748                    i += 1; // skip the escaped character too
2749                } else if b == q {
2750                    quote = None;
2751                }
2752            }
2753            None => match b {
2754                b'\'' | b'"' | b'`' => quote = Some(b),
2755                b';' => {
2756                    semicolons.push(i);
2757                    starts.push(i + 1);
2758                }
2759                _ => {}
2760            },
2761        }
2762        i += 1;
2763    }
2764    starts
2765        .iter()
2766        .enumerate()
2767        .map(|(idx, &start)| {
2768            let end = semicolons.get(idx).copied().unwrap_or(bytes.len());
2769            &input[start..end]
2770        })
2771        .collect()
2772}
2773
2774/// `where`'s grammar reuses the same `expression` rule as everywhere else
2775/// (unlike pest, which has a separate, narrower `with_expr` grammar chain
2776/// building `WithExpr` directly) -- so a full `ReturnExpr` has to be built
2777/// first and then folded down into `WithExpr` here. Only the variants with
2778/// an exact `WithExpr` counterpart (`And`/`Or`/`Not`/`Compare`/`IsNull`)
2779/// unwrap recursively; everything else (including `Xor`, which `WithExpr`
2780/// has no variant for at all) becomes `Bare` -- `WithExpr::Bare`'s own
2781/// docs already cover "any boolean-valued expression used directly as a
2782/// predicate", which this falls under regardless of its exact shape.
2783fn return_expr_to_with_expr(expr: ReturnExpr) -> WithExpr {
2784    match expr {
2785        ReturnExpr::And(l, r) => WithExpr::And(
2786            Box::new(return_expr_to_with_expr(*l)),
2787            Box::new(return_expr_to_with_expr(*r)),
2788        ),
2789        ReturnExpr::Or(l, r) => WithExpr::Or(
2790            Box::new(return_expr_to_with_expr(*l)),
2791            Box::new(return_expr_to_with_expr(*r)),
2792        ),
2793        ReturnExpr::Not(inner) => WithExpr::Not(Box::new(return_expr_to_with_expr(*inner))),
2794        ReturnExpr::Compare(l, op, r) => WithExpr::Compare(*l, op, *r),
2795        ReturnExpr::IsNull(inner) => WithExpr::IsNull(*inner),
2796        other => WithExpr::Bare(other),
2797    }
2798}
2799
2800/// `matchSt`'s `where`, like `withSt`'s, reuses the same generic
2801/// `expression` rule as everywhere else (unlike pest, which has dedicated
2802/// narrower grammar rules -- `comparison`/`general_comparison`/
2803/// `label_predicate`/`var_compare` -- picking the right `Expr` variant
2804/// directly at parse time). So the same fold-down-after-the-fact approach
2805/// as `return_expr_to_with_expr` applies here too, just against `Expr`'s
2806/// wider shape: a `Compare` between two bare `Prop`s becomes `PropCompare`,
2807/// a `Prop` compared to a `Lit` keeps the planner-fusable `Compare` variant
2808/// pest's `comparison` rule reserves for exactly that shape, two bare
2809/// `Var`s becomes identity comparison (`VarEq`/`Not(VarEq)`, matching
2810/// pest's `var_compare`'s restriction to `=`/`<>` — anything else is a real
2811/// error, not a silent `GeneralCompare` fallback, since no ordering exists
2812/// between two nodes/relationships), anything else falls back to
2813/// `GeneralCompare`. Similarly `IsNull` on a bare `Prop` keeps the narrow
2814/// variant, anything else becomes `GeneralIsNull`. `HasLabel` folds
2815/// multiple labels into a `HasLabel` `And` chain exactly like pest's
2816/// `parse_label_predicate`. Everything else becomes `GeneralBare`.
2817fn return_expr_to_expr(expr: ReturnExpr) -> Result<Expr, QueryError> {
2818    Ok(match expr {
2819        ReturnExpr::And(l, r) => Expr::And(
2820            Box::new(return_expr_to_expr(*l)?),
2821            Box::new(return_expr_to_expr(*r)?),
2822        ),
2823        ReturnExpr::Or(l, r) => Expr::Or(
2824            Box::new(return_expr_to_expr(*l)?),
2825            Box::new(return_expr_to_expr(*r)?),
2826        ),
2827        ReturnExpr::Not(inner) => Expr::Not(Box::new(return_expr_to_expr(*inner)?)),
2828        ReturnExpr::Compare(l, op, r) => match (*l, *r) {
2829            (ReturnExpr::Prop(pa), ReturnExpr::Lit(lit)) => Expr::Compare(pa, op, lit),
2830            (ReturnExpr::Prop(pa1), ReturnExpr::Prop(pa2)) => Expr::PropCompare(pa1, op, pa2),
2831            (ReturnExpr::Var(a), ReturnExpr::Var(b)) => match op {
2832                CompareOp::Eq => Expr::VarEq(a, b),
2833                CompareOp::Ne => Expr::Not(Box::new(Expr::VarEq(a, b))),
2834                _ => {
2835                    return Err(QueryError::Syntax(format!(
2836                        "{a} {op:?} {b}: only = and <> are meaningful for comparing two \
2837                         nodes/relationships by identity (no ordering exists between them)"
2838                    )))
2839                }
2840            },
2841            (l, r) => Expr::GeneralCompare(l, op, r),
2842        },
2843        ReturnExpr::IsNull(inner) => match *inner {
2844            ReturnExpr::Prop(pa) => Expr::IsNull(pa),
2845            other => Expr::GeneralIsNull(other),
2846        },
2847        ReturnExpr::HasLabel(var, labels) => {
2848            let mut labels = labels.into_iter();
2849            let first = labels
2850                .next()
2851                .expect("HasLabel always carries at least one label");
2852            labels.fold(Expr::HasLabel(var.clone(), first), |acc, label| {
2853                Expr::And(Box::new(acc), Box::new(Expr::HasLabel(var.clone(), label)))
2854            })
2855        }
2856        ReturnExpr::PatternPredicate(pattern) => Expr::Pattern(pattern),
2857        ReturnExpr::ExistsPattern {
2858            pattern,
2859            where_clause,
2860        } => Expr::Exists {
2861            pattern,
2862            where_clause,
2863        },
2864        ReturnExpr::ExistsSubquery(stmt) => Expr::ExistsSubquery(stmt),
2865        other => Expr::GeneralBare(other),
2866    })
2867}
2868
2869#[cfg(test)]
2870mod tests {
2871    use super::*;
2872    use crate::generated::cypherlexer::CypherLexer;
2873    use crate::generated::cypherparser::CypherParser;
2874    use antlr4rust::common_token_stream::CommonTokenStream;
2875    use antlr4rust::InputStream;
2876
2877    fn parse_literal_expr(input: &str) -> Result<Literal, QueryError> {
2878        let stream = InputStream::new(input);
2879        let lexer = CypherLexer::new(stream);
2880        let tokens = CommonTokenStream::new(lexer);
2881        let mut parser = CypherParser::new(tokens);
2882        let ctx = parser
2883            .literal()
2884            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `literal`: {e:?}"));
2885        AstBuilder::new().visit(&*ctx).into_literal()
2886    }
2887
2888    fn parse_pattern(input: &str) -> Result<Pattern, QueryError> {
2889        let stream = InputStream::new(input);
2890        let lexer = CypherLexer::new(stream);
2891        let tokens = CommonTokenStream::new(lexer);
2892        let mut parser = CypherParser::new(tokens);
2893        let ctx = parser
2894            .patternElem()
2895            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `patternElem`: {e:?}"));
2896        AstBuilder::new().visit(&*ctx).into_pattern()
2897    }
2898
2899    fn parse_match(input: &str) -> Result<Vec<QueryPart>, QueryError> {
2900        let stream = InputStream::new(input);
2901        let lexer = CypherLexer::new(stream);
2902        let tokens = CommonTokenStream::new(lexer);
2903        let mut parser = CypherParser::new(tokens);
2904        let ctx = parser
2905            .matchSt()
2906            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `matchSt`: {e:?}"));
2907        AstBuilder::new().visit(&*ctx).into_query_parts()
2908    }
2909
2910    fn parse_expr(input: &str) -> Result<ReturnExpr, QueryError> {
2911        let stream = InputStream::new(input);
2912        let lexer = CypherLexer::new(stream);
2913        let tokens = CommonTokenStream::new(lexer);
2914        let mut parser = CypherParser::new(tokens);
2915        let ctx = parser
2916            .expression()
2917            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `expression`: {e:?}"));
2918        AstBuilder::new().visit(&*ctx).into_return_expr()
2919    }
2920
2921    fn parse_return(input: &str) -> Result<ParsedReturnClause, QueryError> {
2922        let stream = InputStream::new(input);
2923        let lexer = CypherLexer::new(stream);
2924        let tokens = CommonTokenStream::new(lexer);
2925        let mut parser = CypherParser::new(tokens);
2926        let ctx = parser
2927            .returnSt()
2928            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `returnSt`: {e:?}"));
2929        AstBuilder::new().visit(&*ctx).into_return_clause()
2930    }
2931
2932    fn parse_with(input: &str) -> Result<WithClause, QueryError> {
2933        let stream = InputStream::new(input);
2934        let lexer = CypherLexer::new(stream);
2935        let tokens = CommonTokenStream::new(lexer);
2936        let mut parser = CypherParser::new(tokens);
2937        let ctx = parser
2938            .withSt()
2939            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `withSt`: {e:?}"));
2940        AstBuilder::new().visit(&*ctx).into_with_clause()
2941    }
2942
2943    fn parse_unwind(input: &str) -> Result<UnwindClause, QueryError> {
2944        let stream = InputStream::new(input);
2945        let lexer = CypherLexer::new(stream);
2946        let tokens = CommonTokenStream::new(lexer);
2947        let mut parser = CypherParser::new(tokens);
2948        let ctx = parser
2949            .unwindSt()
2950            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `unwindSt`: {e:?}"));
2951        AstBuilder::new().visit(&*ctx).into_unwind_clause()
2952    }
2953
2954    fn parse_set(input: &str) -> Result<Vec<SetItem>, QueryError> {
2955        let stream = InputStream::new(input);
2956        let lexer = CypherLexer::new(stream);
2957        let tokens = CommonTokenStream::new(lexer);
2958        let mut parser = CypherParser::new(tokens);
2959        let ctx = parser
2960            .setSt()
2961            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `setSt`: {e:?}"));
2962        AstBuilder::new().visit(&*ctx).into_set_items()
2963    }
2964
2965    fn parse_delete(input: &str) -> Result<ParsedDelete, QueryError> {
2966        let stream = InputStream::new(input);
2967        let lexer = CypherLexer::new(stream);
2968        let tokens = CommonTokenStream::new(lexer);
2969        let mut parser = CypherParser::new(tokens);
2970        let ctx = parser
2971            .deleteSt()
2972            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `deleteSt`: {e:?}"));
2973        AstBuilder::new().visit(&*ctx).into_delete_items()
2974    }
2975
2976    fn parse_remove(input: &str) -> Result<Vec<RemoveItem>, QueryError> {
2977        let stream = InputStream::new(input);
2978        let lexer = CypherLexer::new(stream);
2979        let tokens = CommonTokenStream::new(lexer);
2980        let mut parser = CypherParser::new(tokens);
2981        let ctx = parser
2982            .removeSt()
2983            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `removeSt`: {e:?}"));
2984        AstBuilder::new().visit(&*ctx).into_remove_items()
2985    }
2986
2987    fn parse_create(input: &str) -> Result<Vec<Pattern>, QueryError> {
2988        let stream = InputStream::new(input);
2989        let lexer = CypherLexer::new(stream);
2990        let tokens = CommonTokenStream::new(lexer);
2991        let mut parser = CypherParser::new(tokens);
2992        let ctx = parser
2993            .createSt()
2994            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `createSt`: {e:?}"));
2995        AstBuilder::new().visit(&*ctx).into_create_patterns()
2996    }
2997
2998    fn parse_merge(input: &str) -> Result<MergeClause, QueryError> {
2999        let stream = InputStream::new(input);
3000        let lexer = CypherLexer::new(stream);
3001        let tokens = CommonTokenStream::new(lexer);
3002        let mut parser = CypherParser::new(tokens);
3003        let ctx = parser
3004            .mergeSt()
3005            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `mergeSt`: {e:?}"));
3006        AstBuilder::new().visit(&*ctx).into_merge_clause()
3007    }
3008
3009    fn parse_statement(input: &str) -> Result<Statement, QueryError> {
3010        let stream = InputStream::new(input);
3011        let lexer = CypherLexer::new(stream);
3012        let tokens = CommonTokenStream::new(lexer);
3013        let mut parser = CypherParser::new(tokens);
3014        let ctx = parser
3015            .singlePartQ()
3016            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `singlePartQ`: {e:?}"));
3017        AstBuilder::new().visit(&*ctx).into_statement()
3018    }
3019
3020    fn parse_multi_part_statement(input: &str) -> Result<Statement, QueryError> {
3021        let stream = InputStream::new(input);
3022        let lexer = CypherLexer::new(stream);
3023        let tokens = CommonTokenStream::new(lexer);
3024        let mut parser = CypherParser::new(tokens);
3025        let ctx = parser
3026            .multiPartQ()
3027            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `multiPartQ`: {e:?}"));
3028        AstBuilder::new().visit(&*ctx).into_statement()
3029    }
3030
3031    #[test]
3032    fn bool_literals() {
3033        assert_eq!(parse_literal_expr("true").unwrap(), Literal::Bool(true));
3034        assert_eq!(parse_literal_expr("FALSE").unwrap(), Literal::Bool(false));
3035    }
3036
3037    #[test]
3038    fn null_literal() {
3039        assert_eq!(parse_literal_expr("null").unwrap(), Literal::Null);
3040    }
3041
3042    #[test]
3043    fn decimal_int() {
3044        assert_eq!(parse_literal_expr("42").unwrap(), Literal::Int(42));
3045        assert_eq!(parse_literal_expr("007").unwrap(), Literal::Int(7));
3046    }
3047
3048    #[test]
3049    fn hex_and_octal_int() {
3050        assert_eq!(parse_literal_expr("0x1A").unwrap(), Literal::Int(26));
3051        assert_eq!(parse_literal_expr("0o17").unwrap(), Literal::Int(15));
3052    }
3053
3054    // `i64::MIN`'s two's-complement edge case (`-9223372036854775808`) is
3055    // exercised once sign-folding lands at the `unaryAddSubExpression`
3056    // level (see this file's module doc) -- unlike pest's `int_literal`,
3057    // which included an optional leading `-` in the literal token itself,
3058    // this grammar's `literal`/`numLit` never carries a sign at all; `-`
3059    // is strictly `unaryAddSubExpression`'s prefix operator, one level up.
3060    // `parse_int_literal` (reused from `parser.rs`) already handles the
3061    // two's-complement case correctly given a leading `-` in its input --
3062    // that part's covered; only the fold-sign-into-literal-vs-build-a-Neg-
3063    // node decision at the expression level remains.
3064
3065    #[test]
3066    fn float_literals() {
3067        assert_eq!(parse_literal_expr("2.5").unwrap(), Literal::Float(2.5));
3068        assert_eq!(parse_literal_expr("1e10").unwrap(), Literal::Float(1e10));
3069        assert_eq!(parse_literal_expr(".5").unwrap(), Literal::Float(0.5));
3070    }
3071
3072    #[test]
3073    fn float_overflow_errors() {
3074        assert!(parse_literal_expr("1e999").is_err());
3075    }
3076
3077    #[test]
3078    fn string_and_char_literals() {
3079        assert_eq!(
3080            parse_literal_expr("\"hello\"").unwrap(),
3081            Literal::String("hello".to_string())
3082        );
3083        assert_eq!(
3084            parse_literal_expr("'a string with spaces and a hyphen-in-it'").unwrap(),
3085            Literal::String("a string with spaces and a hyphen-in-it".to_string())
3086        );
3087    }
3088
3089    #[test]
3090    fn string_escapes() {
3091        assert_eq!(
3092            parse_literal_expr(r#"'line1\nline2'"#).unwrap(),
3093            Literal::String("line1\nline2".to_string())
3094        );
3095        assert_eq!(
3096            parse_literal_expr(r#"'é'"#).unwrap(),
3097            Literal::String("é".to_string())
3098        );
3099    }
3100
3101    #[test]
3102    fn single_node() {
3103        let p = parse_pattern("(a:Person)").unwrap();
3104        assert_eq!(p.start.var.as_deref(), Some("a"));
3105        assert_eq!(p.start.labels, vec!["Person".to_string()]);
3106        assert!(p.hops.is_empty());
3107    }
3108
3109    #[test]
3110    fn anonymous_node() {
3111        let p = parse_pattern("()").unwrap();
3112        assert_eq!(p.start.var, None);
3113        assert!(p.start.labels.is_empty());
3114    }
3115
3116    #[test]
3117    fn multiple_labels() {
3118        let p = parse_pattern("(a:Person:Employee)").unwrap();
3119        assert_eq!(
3120            p.start.labels,
3121            vec!["Person".to_string(), "Employee".to_string()]
3122        );
3123    }
3124
3125    #[test]
3126    fn escaped_identifier() {
3127        let p = parse_pattern("(`weird name`)").unwrap();
3128        assert_eq!(p.start.var.as_deref(), Some("weird name"));
3129    }
3130
3131    #[test]
3132    fn directions() {
3133        assert_eq!(
3134            parse_pattern("(a)-->(b)").unwrap().hops[0].0.direction,
3135            RelDirection::Right
3136        );
3137        assert_eq!(
3138            parse_pattern("(a)<--(b)").unwrap().hops[0].0.direction,
3139            RelDirection::Left
3140        );
3141        assert_eq!(
3142            parse_pattern("(a)--(b)").unwrap().hops[0].0.direction,
3143            RelDirection::Either
3144        );
3145        // Both arrowheads (`<-...->`) is the same undirected/either shape
3146        // as neither -- regression found via the TCK (Match6 [12]/
3147        // Create2 [20]): used to silently resolve to Left,
3148        // checking LT before GT and never noticing GT was also present.
3149        assert_eq!(
3150            parse_pattern("(a)<-->(b)").unwrap().hops[0].0.direction,
3151            RelDirection::Either
3152        );
3153    }
3154
3155    #[test]
3156    fn rel_type_and_var() {
3157        let p = parse_pattern("(a)-[r:KNOWS]->(b)").unwrap();
3158        let (rel, node) = &p.hops[0];
3159        assert_eq!(rel.var.as_deref(), Some("r"));
3160        assert_eq!(rel.rel_types, vec!["KNOWS".to_string()]);
3161        assert_eq!(node.var.as_deref(), Some("b"));
3162        assert_eq!(rel.hop_range, None);
3163    }
3164
3165    #[test]
3166    fn multiple_rel_types() {
3167        let p = parse_pattern("(a)-[:KNOWS|LIKES]->(b)").unwrap();
3168        assert_eq!(
3169            p.hops[0].0.rel_types,
3170            vec!["KNOWS".to_string(), "LIKES".to_string()]
3171        );
3172    }
3173
3174    #[test]
3175    fn var_length_bounds() {
3176        // Exercises the DIGIT/ID lexer fixes end to end -- `*0`/`*2` used
3177        // to hard-fail before those were fixed upstream.
3178        assert_eq!(
3179            parse_pattern("(a)-[*0]->(b)").unwrap().hops[0].0.hop_range,
3180            Some((0, Some(0)))
3181        );
3182        assert_eq!(
3183            parse_pattern("(a)-[*2]->(b)").unwrap().hops[0].0.hop_range,
3184            Some((2, Some(2)))
3185        );
3186        assert_eq!(
3187            parse_pattern("(a)-[*1..3]->(b)").unwrap().hops[0]
3188                .0
3189                .hop_range,
3190            Some((1, Some(3)))
3191        );
3192        assert_eq!(
3193            parse_pattern("(a)-[*]->(b)").unwrap().hops[0].0.hop_range,
3194            Some((1, None))
3195        );
3196    }
3197
3198    #[test]
3199    fn multi_hop_chain() {
3200        let p = parse_pattern("(a)-[:KNOWS]->(b)<-[:LIKES]-(c)").unwrap();
3201        assert_eq!(p.hops.len(), 2);
3202        assert_eq!(p.hops[0].0.direction, RelDirection::Right);
3203        assert_eq!(p.hops[1].0.direction, RelDirection::Left);
3204    }
3205
3206    #[test]
3207    fn node_pattern_properties() {
3208        let pattern = parse_pattern("(a {name: 'x', age: 1 + 1})").unwrap();
3209        assert_eq!(
3210            pattern.start.props,
3211            vec![
3212                (
3213                    "name".to_string(),
3214                    ReturnExpr::Lit(Literal::String("x".to_string()))
3215                ),
3216                (
3217                    "age".to_string(),
3218                    ReturnExpr::Arith(
3219                        Box::new(ReturnExpr::Lit(Literal::Int(1))),
3220                        ArithOp::Add,
3221                        Box::new(ReturnExpr::Lit(Literal::Int(1))),
3222                    )
3223                ),
3224            ]
3225        );
3226    }
3227
3228    #[test]
3229    fn rel_pattern_properties() {
3230        let pattern = parse_pattern("(a)-[:T {weight: 5}]->(b)").unwrap();
3231        assert_eq!(
3232            pattern.hops[0].0.props,
3233            vec![("weight".to_string(), ReturnExpr::Lit(Literal::Int(5)))]
3234        );
3235    }
3236
3237    #[test]
3238    fn pattern_properties_parameter_not_supported() {
3239        assert!(parse_pattern("(a $props)").is_err());
3240    }
3241
3242    #[test]
3243    fn simple_match() {
3244        let parts = parse_match("MATCH (a:Person)-[:KNOWS]->(b)").unwrap();
3245        assert_eq!(parts.len(), 1);
3246        assert!(!parts[0].optional);
3247        assert_eq!(parts[0].path_var, None);
3248        assert_eq!(parts[0].pattern.start.var.as_deref(), Some("a"));
3249        assert_eq!(parts[0].pattern.hops.len(), 1);
3250    }
3251
3252    #[test]
3253    fn optional_match() {
3254        let parts = parse_match("OPTIONAL MATCH (a)").unwrap();
3255        assert!(parts[0].optional);
3256    }
3257
3258    #[test]
3259    fn named_path() {
3260        let parts = parse_match("MATCH p = (a)-->(b)").unwrap();
3261        assert_eq!(parts.len(), 1);
3262        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3263    }
3264
3265    #[test]
3266    fn comma_pattern_shared_node_merges_into_one_linear_chain() {
3267        // `(a)-->(b), (b)-->(c)` shares `b` -- one QueryPart, three-node
3268        // chain, not two disjoint ones. Exercises group_into_linear_patterns.
3269        let parts = parse_match("MATCH (a)-->(b), (b)-->(c)").unwrap();
3270        assert_eq!(parts.len(), 1);
3271        assert_eq!(parts[0].pattern.hops.len(), 2);
3272    }
3273
3274    #[test]
3275    fn comma_pattern_disjoint_becomes_multiple_query_parts() {
3276        let parts = parse_match("MATCH (a), (b)").unwrap();
3277        assert_eq!(parts.len(), 2);
3278    }
3279
3280    #[test]
3281    fn named_path_over_disjoint_cross_join_errors() {
3282        assert!(parse_match("MATCH p = (a), (b)").is_err());
3283    }
3284
3285    #[test]
3286    fn shortest_path() {
3287        let parts = parse_match("MATCH shortestPath((a)-[*1..3]->(b))").unwrap();
3288        assert_eq!(parts.len(), 1);
3289        assert!(parts[0].shortest_path);
3290        assert_eq!(parts[0].pattern.hops.len(), 1);
3291    }
3292
3293    #[test]
3294    fn shortest_path_with_named_path_capture() {
3295        let parts = parse_match("MATCH p = shortestPath((a)-[*1..3]->(b))").unwrap();
3296        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3297        assert!(parts[0].shortest_path);
3298    }
3299
3300    #[test]
3301    fn shortest_path_requires_variable_length_hop() {
3302        assert!(parse_match("MATCH shortestPath((a)-->(b))").is_err());
3303    }
3304
3305    #[test]
3306    fn shortest_path_not_first_in_cross_join_errors() {
3307        assert!(parse_match("MATCH (c), shortestPath((a)-[*1..3]->(b))").is_err());
3308    }
3309
3310    #[test]
3311    fn shortest_path_over_disjoint_cross_join_errors() {
3312        assert!(parse_match("MATCH shortestPath((a)-[*1..3]->(b)), (c)").is_err());
3313    }
3314
3315    #[test]
3316    fn shortest_path_not_valid_in_create() {
3317        assert!(parse_statement("CREATE shortestPath((a)-[*1..3]->(b))").is_err());
3318    }
3319
3320    #[test]
3321    fn shortest_path_not_valid_in_merge() {
3322        assert!(parse_merge("MERGE shortestPath((a)-[*1..3]->(b))").is_err());
3323    }
3324
3325    #[test]
3326    fn named_path_over_a_single_variable_length_hop_is_supported() {
3327        // TCK's Quantifier1-4 [8]/[9] -- a single variable-length hop is
3328        // fine; only *mixing* one with another hop stays rejected (see
3329        // the next test).
3330        let parts = parse_match("MATCH p = (a)-[*1..3]->(b)").unwrap();
3331        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3332    }
3333
3334    #[test]
3335    fn named_path_over_variable_length_mixed_with_another_hop_is_supported() {
3336        // Was rejected until the `LogicalPlan::VarExpand` edge-isomorphism
3337        // gap was fixed -- see `validate_named_path_pattern`'s docs.
3338        let parts = parse_match("MATCH p = (a)-[*1..3]->(b)-->(c)").unwrap();
3339        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3340    }
3341
3342    #[test]
3343    fn match_where() {
3344        let parts = parse_match("MATCH (a) WHERE a.x = 1").unwrap();
3345        assert_eq!(parts.len(), 1);
3346        assert!(matches!(
3347            parts[0].where_clause,
3348            Some(Expr::Compare(
3349                PropAccess { .. },
3350                CompareOp::Eq,
3351                Literal::Int(1),
3352            ))
3353        ));
3354    }
3355
3356    #[test]
3357    fn match_where_var_eq() {
3358        let parts = parse_match("MATCH (a), (b) WHERE a = b").unwrap();
3359        assert!(matches!(parts[1].where_clause, Some(Expr::VarEq(_, _))));
3360    }
3361
3362    #[test]
3363    fn match_where_label_predicate() {
3364        let parts = parse_match("MATCH (a) WHERE a:A:B").unwrap();
3365        assert!(matches!(parts[0].where_clause, Some(Expr::And(_, _))));
3366    }
3367
3368    #[test]
3369    fn match_where_pattern_predicate() {
3370        let parts = parse_match("MATCH (n) WHERE (n)-[]->() RETURN n")
3371            .unwrap_or_else(|e| panic!("expected pattern predicate to parse, got {e:?}"));
3372        let Some(Expr::Pattern(pattern)) = &parts[0].where_clause else {
3373            panic!("expected Expr::Pattern");
3374        };
3375        assert_eq!(pattern.hops.len(), 1);
3376    }
3377
3378    #[test]
3379    fn match_where_pattern_predicate_combined_with_and() {
3380        let parts = parse_match("MATCH (n) WHERE (n)-->() AND n.x = 1").unwrap();
3381        let Some(Expr::And(l, r)) = &parts[0].where_clause else {
3382            panic!("expected Expr::And");
3383        };
3384        assert!(matches!(**l, Expr::Pattern(_)));
3385        assert!(matches!(**r, Expr::Compare(..)));
3386    }
3387
3388    #[test]
3389    fn pattern_predicate_outside_where_still_parses() {
3390        // Grammatically legal anywhere an expression is (real Cypher
3391        // restricts it to WHERE) -- parses fine as a ReturnExpr;
3392        // semantic::infer_expr is what rejects it outside a WHERE-folded
3393        // position, at compile time (see that function's own docs).
3394        let expr = parse_expr("(n)-->()").unwrap();
3395        assert!(matches!(expr, ReturnExpr::PatternPredicate(_)));
3396    }
3397
3398    #[test]
3399    fn match_where_on_last_group_of_cross_join() {
3400        let parts = parse_match("MATCH (a), (b) WHERE b.x = 1").unwrap();
3401        assert_eq!(parts.len(), 2);
3402        assert!(parts[0].where_clause.is_none());
3403        assert!(parts[1].where_clause.is_some());
3404    }
3405
3406    #[test]
3407    fn arithmetic_precedence() {
3408        // 1 + 2 * 3 = 7, not 9 -- * binds tighter than +.
3409        assert_eq!(
3410            parse_expr("1 + 2 * 3").unwrap(),
3411            ReturnExpr::Arith(
3412                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3413                ArithOp::Add,
3414                Box::new(ReturnExpr::Arith(
3415                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3416                    ArithOp::Mul,
3417                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3418                )),
3419            )
3420        );
3421    }
3422
3423    #[test]
3424    fn arithmetic_left_associative() {
3425        // 10 - 2 - 3 = (10 - 2) - 3 = 5, not 10 - (2 - 3) = 11.
3426        assert_eq!(
3427            parse_expr("10 - 2 - 3").unwrap(),
3428            ReturnExpr::Arith(
3429                Box::new(ReturnExpr::Arith(
3430                    Box::new(ReturnExpr::Lit(Literal::Int(10))),
3431                    ArithOp::Sub,
3432                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3433                )),
3434                ArithOp::Sub,
3435                Box::new(ReturnExpr::Lit(Literal::Int(3))),
3436            )
3437        );
3438    }
3439
3440    #[test]
3441    fn power_left_associative() {
3442        assert_eq!(
3443            parse_expr("4 ^ 3 ^ 2").unwrap(),
3444            ReturnExpr::Arith(
3445                Box::new(ReturnExpr::Arith(
3446                    Box::new(ReturnExpr::Lit(Literal::Int(4))),
3447                    ArithOp::Pow,
3448                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3449                )),
3450                ArithOp::Pow,
3451                Box::new(ReturnExpr::Lit(Literal::Int(2))),
3452            )
3453        );
3454    }
3455
3456    #[test]
3457    fn binary_minus_no_whitespace() {
3458        // Exercises the DIGIT-sign-removal grammar fix end to end: `5-1`
3459        // used to tokenize as two adjacent DIGIT tokens with no operator.
3460        assert_eq!(
3461            parse_expr("5-1").unwrap(),
3462            ReturnExpr::Arith(
3463                Box::new(ReturnExpr::Lit(Literal::Int(5))),
3464                ArithOp::Sub,
3465                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3466            )
3467        );
3468    }
3469
3470    #[test]
3471    fn unary_minus_on_variable() {
3472        assert_eq!(
3473            parse_expr("-x").unwrap(),
3474            ReturnExpr::Neg(Box::new(ReturnExpr::Var("x".to_string())))
3475        );
3476    }
3477
3478    #[test]
3479    fn unary_minus_folds_into_literal() {
3480        assert_eq!(parse_expr("-5").unwrap(), ReturnExpr::Lit(Literal::Int(-5)));
3481        assert_eq!(
3482            parse_expr("-5.5").unwrap(),
3483            ReturnExpr::Lit(Literal::Float(-5.5))
3484        );
3485    }
3486
3487    #[test]
3488    fn unary_minus_int_min_two_complement_edge_case() {
3489        // 9223372036854775808 (2^63) doesn't fit in a positive i64 at all
3490        // -- only i64::MIN's magnitude does. Folding the sign directly
3491        // into the literal (rather than building Neg(Lit(Int(...)))) is
3492        // what makes this representable.
3493        assert_eq!(
3494            parse_expr("-9223372036854775808").unwrap(),
3495            ReturnExpr::Lit(Literal::Int(i64::MIN))
3496        );
3497    }
3498
3499    #[test]
3500    fn comparison_chain_folds_into_nested_and() {
3501        // 1 < x < 3 -> (1 < x) AND (x < 3), real Cypher's chained-
3502        // comparison semantics, not a separate AST shape.
3503        assert_eq!(
3504            parse_expr("1 < x < 3").unwrap(),
3505            ReturnExpr::And(
3506                Box::new(ReturnExpr::Compare(
3507                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3508                    CompareOp::Lt,
3509                    Box::new(ReturnExpr::Var("x".to_string())),
3510                )),
3511                Box::new(ReturnExpr::Compare(
3512                    Box::new(ReturnExpr::Var("x".to_string())),
3513                    CompareOp::Lt,
3514                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3515                )),
3516            )
3517        );
3518    }
3519
3520    #[test]
3521    fn boolean_operators() {
3522        assert_eq!(
3523            parse_expr("true AND false").unwrap(),
3524            ReturnExpr::And(
3525                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3526                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3527            )
3528        );
3529        assert_eq!(
3530            parse_expr("true OR false").unwrap(),
3531            ReturnExpr::Or(
3532                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3533                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3534            )
3535        );
3536        assert_eq!(
3537            parse_expr("true XOR false").unwrap(),
3538            ReturnExpr::Xor(
3539                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3540                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3541            )
3542        );
3543    }
3544
3545    #[test]
3546    fn double_negation() {
3547        // Exercises the notExpression NOT* grammar fix end to end.
3548        assert_eq!(
3549            parse_expr("NOT NOT true").unwrap(),
3550            ReturnExpr::Not(Box::new(ReturnExpr::Not(Box::new(ReturnExpr::Lit(
3551                Literal::Bool(true)
3552            )))))
3553        );
3554    }
3555
3556    #[test]
3557    fn is_null() {
3558        assert_eq!(
3559            parse_expr("x IS NULL").unwrap(),
3560            ReturnExpr::IsNull(Box::new(ReturnExpr::Var("x".to_string())))
3561        );
3562        assert_eq!(
3563            parse_expr("x IS NOT NULL").unwrap(),
3564            ReturnExpr::Not(Box::new(ReturnExpr::IsNull(Box::new(ReturnExpr::Var(
3565                "x".to_string()
3566            )))))
3567        );
3568    }
3569
3570    #[test]
3571    fn in_operator() {
3572        assert_eq!(
3573            parse_expr("x IN y").unwrap(),
3574            ReturnExpr::In(
3575                Box::new(ReturnExpr::Var("x".to_string())),
3576                Box::new(ReturnExpr::Var("y".to_string())),
3577            )
3578        );
3579    }
3580
3581    #[test]
3582    fn is_null_binds_looser_than_arithmetic() {
3583        // Precedence bug found via a Phase 3 behavioral dry-run: `IS
3584        // NULL`/`IN`/`STARTS WITH` etc must bind above `+`/`-`/`*`/`/`/`^`
3585        // (openCypher.bnf's <comparison predicate> chain), so `x + 0 IS
3586        // NULL` is `(x + 0) IS NULL`, not `x + (0 IS NULL)`.
3587        assert_eq!(
3588            parse_expr("x + 0 IS NULL").unwrap(),
3589            ReturnExpr::IsNull(Box::new(ReturnExpr::Arith(
3590                Box::new(ReturnExpr::Var("x".to_string())),
3591                ArithOp::Add,
3592                Box::new(ReturnExpr::Lit(Literal::Int(0))),
3593            )))
3594        );
3595    }
3596
3597    #[test]
3598    fn in_binds_looser_than_arithmetic_and_operand_can_be_sliced() {
3599        assert_eq!(
3600            parse_expr("3 IN [1, 2, 3][0..2]").unwrap(),
3601            ReturnExpr::In(
3602                Box::new(ReturnExpr::Lit(Literal::Int(3))),
3603                Box::new(ReturnExpr::Slice(
3604                    Box::new(ReturnExpr::ListLit(vec![
3605                        ReturnExpr::Lit(Literal::Int(1)),
3606                        ReturnExpr::Lit(Literal::Int(2)),
3607                        ReturnExpr::Lit(Literal::Int(3)),
3608                    ])),
3609                    Some(Box::new(ReturnExpr::Lit(Literal::Int(0)))),
3610                    Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))),
3611                ))
3612            )
3613        );
3614    }
3615
3616    #[test]
3617    fn starts_with_operand_can_be_an_arithmetic_expression() {
3618        assert_eq!(
3619            parse_expr("x STARTS WITH y + z").unwrap(),
3620            ReturnExpr::Compare(
3621                Box::new(ReturnExpr::Var("x".to_string())),
3622                CompareOp::StartsWith,
3623                Box::new(ReturnExpr::Arith(
3624                    Box::new(ReturnExpr::Var("y".to_string())),
3625                    ArithOp::Add,
3626                    Box::new(ReturnExpr::Var("z".to_string())),
3627                )),
3628            )
3629        );
3630    }
3631
3632    #[test]
3633    fn chained_index_postfix_still_works() {
3634        assert_eq!(
3635            parse_expr("[[1, 2], [3, 4]][0][1]").unwrap(),
3636            ReturnExpr::Index(
3637                Box::new(ReturnExpr::Index(
3638                    Box::new(ReturnExpr::ListLit(vec![
3639                        ReturnExpr::ListLit(vec![
3640                            ReturnExpr::Lit(Literal::Int(1)),
3641                            ReturnExpr::Lit(Literal::Int(2)),
3642                        ]),
3643                        ReturnExpr::ListLit(vec![
3644                            ReturnExpr::Lit(Literal::Int(3)),
3645                            ReturnExpr::Lit(Literal::Int(4)),
3646                        ]),
3647                    ])),
3648                    Box::new(ReturnExpr::Lit(Literal::Int(0))),
3649                )),
3650                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3651            )
3652        );
3653    }
3654
3655    #[test]
3656    fn case_searched_form() {
3657        assert_eq!(
3658            parse_expr("CASE WHEN x > 1 THEN 'big' WHEN x > 0 THEN 'small' ELSE 'none' END")
3659                .unwrap(),
3660            ReturnExpr::Case {
3661                test: None,
3662                whens: vec![
3663                    (
3664                        ReturnExpr::Compare(
3665                            Box::new(ReturnExpr::Var("x".to_string())),
3666                            CompareOp::Gt,
3667                            Box::new(ReturnExpr::Lit(Literal::Int(1))),
3668                        ),
3669                        ReturnExpr::Lit(Literal::String("big".to_string())),
3670                    ),
3671                    (
3672                        ReturnExpr::Compare(
3673                            Box::new(ReturnExpr::Var("x".to_string())),
3674                            CompareOp::Gt,
3675                            Box::new(ReturnExpr::Lit(Literal::Int(0))),
3676                        ),
3677                        ReturnExpr::Lit(Literal::String("small".to_string())),
3678                    ),
3679                ],
3680                else_: Some(Box::new(ReturnExpr::Lit(Literal::String(
3681                    "none".to_string()
3682                )))),
3683            }
3684        );
3685    }
3686
3687    #[test]
3688    fn case_simple_form_with_test_no_else() {
3689        assert_eq!(
3690            parse_expr("CASE x WHEN 1 THEN 'one' WHEN 2 THEN 'two' END").unwrap(),
3691            ReturnExpr::Case {
3692                test: Some(Box::new(ReturnExpr::Var("x".to_string()))),
3693                whens: vec![
3694                    (
3695                        ReturnExpr::Lit(Literal::Int(1)),
3696                        ReturnExpr::Lit(Literal::String("one".to_string())),
3697                    ),
3698                    (
3699                        ReturnExpr::Lit(Literal::Int(2)),
3700                        ReturnExpr::Lit(Literal::String("two".to_string())),
3701                    ),
3702                ],
3703                else_: None,
3704            }
3705        );
3706    }
3707
3708    #[test]
3709    fn quantifier_none() {
3710        assert_eq!(
3711            parse_expr("none(x IN [1,2] WHERE x > 1)").unwrap(),
3712            ReturnExpr::Quantifier {
3713                kind: QuantifierKind::None,
3714                var: "x".to_string(),
3715                source: Box::new(ReturnExpr::ListLit(vec![
3716                    ReturnExpr::Lit(Literal::Int(1)),
3717                    ReturnExpr::Lit(Literal::Int(2)),
3718                ])),
3719                where_clause: Some(Box::new(ReturnExpr::Compare(
3720                    Box::new(ReturnExpr::Var("x".to_string())),
3721                    CompareOp::Gt,
3722                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3723                ))),
3724            }
3725        );
3726    }
3727
3728    #[test]
3729    fn quantifier_all_any_single_no_where() {
3730        assert!(matches!(
3731            parse_expr("all(x IN [1]) ").unwrap(),
3732            ReturnExpr::Quantifier {
3733                kind: QuantifierKind::All,
3734                where_clause: None,
3735                ..
3736            }
3737        ));
3738        assert!(matches!(
3739            parse_expr("any(x IN [1])").unwrap(),
3740            ReturnExpr::Quantifier {
3741                kind: QuantifierKind::Any,
3742                ..
3743            }
3744        ));
3745        assert!(matches!(
3746            parse_expr("single(x IN [1])").unwrap(),
3747            ReturnExpr::Quantifier {
3748                kind: QuantifierKind::Single,
3749                ..
3750            }
3751        ));
3752    }
3753
3754    #[test]
3755    fn list_comprehension_with_projection() {
3756        assert_eq!(
3757            parse_expr("[x IN [1,2] WHERE x > 1 | x * 2]").unwrap(),
3758            ReturnExpr::ListComp {
3759                var: "x".to_string(),
3760                source: Box::new(ReturnExpr::ListLit(vec![
3761                    ReturnExpr::Lit(Literal::Int(1)),
3762                    ReturnExpr::Lit(Literal::Int(2)),
3763                ])),
3764                where_clause: Some(Box::new(ReturnExpr::Compare(
3765                    Box::new(ReturnExpr::Var("x".to_string())),
3766                    CompareOp::Gt,
3767                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3768                ))),
3769                project: Some(Box::new(ReturnExpr::Arith(
3770                    Box::new(ReturnExpr::Var("x".to_string())),
3771                    ArithOp::Mul,
3772                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3773                ))),
3774            }
3775        );
3776    }
3777
3778    #[test]
3779    fn list_comprehension_with_where_no_project() {
3780        assert_eq!(
3781            parse_expr("[x IN [1,2] WHERE x > 1]").unwrap(),
3782            ReturnExpr::ListComp {
3783                var: "x".to_string(),
3784                source: Box::new(ReturnExpr::ListLit(vec![
3785                    ReturnExpr::Lit(Literal::Int(1)),
3786                    ReturnExpr::Lit(Literal::Int(2)),
3787                ])),
3788                where_clause: Some(Box::new(ReturnExpr::Compare(
3789                    Box::new(ReturnExpr::Var("x".to_string())),
3790                    CompareOp::Gt,
3791                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3792                ))),
3793                project: None,
3794            }
3795        );
3796    }
3797
3798    #[test]
3799    fn list_comprehension_bare_identity_no_where_no_project() {
3800        // `[x IN list]` (neither WHERE nor `| project`) is genuinely
3801        // ambiguous with a one-element `listLit` containing the boolean
3802        // `x IN list` membership test -- `atom`'s alternatives are
3803        // ordered so `listComprehension` wins (real, spec-valid Cypher on
3804        // its own per openCypher.bnf's `<list comprehension>`, whose
3805        // filter/projection half is optional; found wrong via a Phase 3
3806        // behavioral dry-run, not the TCK).
3807        assert_eq!(
3808            parse_expr("[x IN [1, 2, 3]]").unwrap(),
3809            ReturnExpr::ListComp {
3810                var: "x".to_string(),
3811                source: Box::new(ReturnExpr::ListLit(vec![
3812                    ReturnExpr::Lit(Literal::Int(1)),
3813                    ReturnExpr::Lit(Literal::Int(2)),
3814                    ReturnExpr::Lit(Literal::Int(3)),
3815                ])),
3816                where_clause: None,
3817                project: None,
3818            }
3819        );
3820    }
3821
3822    #[test]
3823    fn string_predicates() {
3824        assert_eq!(
3825            parse_expr("x STARTS WITH y").unwrap(),
3826            ReturnExpr::Compare(
3827                Box::new(ReturnExpr::Var("x".to_string())),
3828                CompareOp::StartsWith,
3829                Box::new(ReturnExpr::Var("y".to_string())),
3830            )
3831        );
3832        assert_eq!(
3833            parse_expr("x ENDS WITH y").unwrap(),
3834            ReturnExpr::Compare(
3835                Box::new(ReturnExpr::Var("x".to_string())),
3836                CompareOp::EndsWith,
3837                Box::new(ReturnExpr::Var("y".to_string())),
3838            )
3839        );
3840        assert_eq!(
3841            parse_expr("x CONTAINS y").unwrap(),
3842            ReturnExpr::Compare(
3843                Box::new(ReturnExpr::Var("x".to_string())),
3844                CompareOp::Contains,
3845                Box::new(ReturnExpr::Var("y".to_string())),
3846            )
3847        );
3848    }
3849
3850    #[test]
3851    fn index_and_slice() {
3852        assert_eq!(
3853            parse_expr("list[0]").unwrap(),
3854            ReturnExpr::Index(
3855                Box::new(ReturnExpr::Var("list".to_string())),
3856                Box::new(ReturnExpr::Lit(Literal::Int(0))),
3857            )
3858        );
3859        assert_eq!(
3860            parse_expr("list[1..3]").unwrap(),
3861            ReturnExpr::Slice(
3862                Box::new(ReturnExpr::Var("list".to_string())),
3863                Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))),
3864                Some(Box::new(ReturnExpr::Lit(Literal::Int(3)))),
3865            )
3866        );
3867        assert_eq!(
3868            parse_expr("list[..3]").unwrap(),
3869            ReturnExpr::Slice(
3870                Box::new(ReturnExpr::Var("list".to_string())),
3871                None,
3872                Some(Box::new(ReturnExpr::Lit(Literal::Int(3)))),
3873            )
3874        );
3875        assert_eq!(
3876            parse_expr("list[1..]").unwrap(),
3877            ReturnExpr::Slice(
3878                Box::new(ReturnExpr::Var("list".to_string())),
3879                Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))),
3880                None,
3881            )
3882        );
3883    }
3884
3885    #[test]
3886    fn property_access() {
3887        assert_eq!(
3888            parse_expr("n.name").unwrap(),
3889            ReturnExpr::Prop(PropAccess {
3890                var: "n".to_string(),
3891                prop: "name".to_string(),
3892            })
3893        );
3894    }
3895
3896    #[test]
3897    fn property_access_with_backtick_escaped_name() {
3898        // Regression (found via the TCK, Map1 [5]): `.get_text()` on the
3899        // `name` context kept the surrounding backticks as part of the
3900        // property name (`` `name` `` instead of `name`), so this always
3901        // looked up the wrong key. `name_text` strips them, same as
3902        // `symbol_text` already does for backtick-escaped variable names.
3903        assert_eq!(
3904            parse_expr("n.`weird name`").unwrap(),
3905            ReturnExpr::Prop(PropAccess {
3906                var: "n".to_string(),
3907                prop: "weird name".to_string(),
3908            })
3909        );
3910    }
3911
3912    #[test]
3913    fn property_access_on_computed_expr_becomes_prop_of() {
3914        // `<expr>.prop` where `<expr>` isn't a bare variable -- `ReturnExpr::
3915        // PropOf`, evaluated by evaluating the base first, then looking the
3916        // property up on whatever `Value` it produced (TCK's Graph6 [4]/
3917        // [8], Map1 [3], Merge5 [11]).
3918        let expr = parse_expr("duration.between(a, b).days").unwrap();
3919        let ReturnExpr::PropOf(base, prop) = expr else {
3920            panic!("expected PropOf, got {expr:?}");
3921        };
3922        assert_eq!(prop, "days");
3923        assert!(matches!(*base, ReturnExpr::Call { .. }));
3924    }
3925
3926    #[test]
3927    fn chained_property_access_folds_left_to_right() {
3928        // `a.b.c` -> `PropOf(Prop{a,b}, c)` -- TCK's With2 [2].
3929        let expr = parse_expr("a.b.c").unwrap();
3930        let ReturnExpr::PropOf(base, prop) = expr else {
3931            panic!("expected PropOf, got {expr:?}");
3932        };
3933        assert_eq!(prop, "c");
3934        assert_eq!(
3935            *base,
3936            ReturnExpr::Prop(PropAccess {
3937                var: "a".to_string(),
3938                prop: "b".to_string(),
3939            })
3940        );
3941    }
3942
3943    #[test]
3944    fn has_label() {
3945        assert_eq!(
3946            parse_expr("n:Person").unwrap(),
3947            ReturnExpr::HasLabel("n".to_string(), vec!["Person".to_string()])
3948        );
3949    }
3950
3951    #[test]
3952    fn function_call() {
3953        assert_eq!(
3954            parse_expr("size(list)").unwrap(),
3955            ReturnExpr::Call {
3956                name: "size".to_string(),
3957                args: vec![ReturnExpr::Var("list".to_string())],
3958                distinct: false,
3959            }
3960        );
3961    }
3962
3963    #[test]
3964    fn namespaced_function_call() {
3965        assert_eq!(
3966            parse_expr("duration.between(a, b)").unwrap(),
3967            ReturnExpr::Call {
3968                name: "duration.between".to_string(),
3969                args: vec![
3970                    ReturnExpr::Var("a".to_string()),
3971                    ReturnExpr::Var("b".to_string())
3972                ],
3973                distinct: false,
3974            }
3975        );
3976    }
3977
3978    #[test]
3979    fn count_star() {
3980        assert_eq!(parse_expr("count(*)").unwrap(), ReturnExpr::CountStar);
3981    }
3982
3983    #[test]
3984    fn aggregate_distinct() {
3985        assert_eq!(
3986            parse_expr("count(DISTINCT x)").unwrap(),
3987            ReturnExpr::Call {
3988                name: "count".to_string(),
3989                args: vec![ReturnExpr::Var("x".to_string())],
3990                distinct: true,
3991            }
3992        );
3993    }
3994
3995    #[test]
3996    fn distinct_on_non_aggregate_errors() {
3997        assert!(parse_expr("size(DISTINCT x)").is_err());
3998    }
3999
4000    #[test]
4001    fn distinct_on_namespaced_call_errors() {
4002        assert!(parse_expr("duration.between(DISTINCT a, b)").is_err());
4003    }
4004
4005    #[test]
4006    fn parameter_by_name() {
4007        assert_eq!(
4008            parse_expr("$name").unwrap(),
4009            ReturnExpr::Lit(Literal::Param("name".to_string()))
4010        );
4011    }
4012
4013    #[test]
4014    fn parameter_by_position() {
4015        assert_eq!(
4016            parse_expr("$0").unwrap(),
4017            ReturnExpr::Lit(Literal::Param("0".to_string()))
4018        );
4019    }
4020
4021    #[test]
4022    fn parenthesized_expression() {
4023        assert_eq!(
4024            parse_expr("(1 + 2) * 3").unwrap(),
4025            ReturnExpr::Arith(
4026                Box::new(ReturnExpr::Arith(
4027                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
4028                    ArithOp::Add,
4029                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
4030                )),
4031                ArithOp::Mul,
4032                Box::new(ReturnExpr::Lit(Literal::Int(3))),
4033            )
4034        );
4035    }
4036
4037    #[test]
4038    fn return_simple_items() {
4039        let c = parse_return("RETURN a, b.name AS name").unwrap();
4040        let Tail::Return(items, distinct) = c.tail else {
4041            panic!("expected Tail::Return");
4042        };
4043        assert!(!distinct);
4044        assert_eq!(items.len(), 2);
4045        assert_eq!(items[0].expr, ReturnExpr::Var("a".to_string()));
4046        assert_eq!(items[0].alias, None);
4047        assert_eq!(
4048            items[1].expr,
4049            ReturnExpr::Prop(PropAccess {
4050                var: "b".to_string(),
4051                prop: "name".to_string(),
4052            })
4053        );
4054        assert_eq!(items[1].alias.as_deref(), Some("name"));
4055    }
4056
4057    #[test]
4058    fn return_distinct() {
4059        let c = parse_return("RETURN DISTINCT a").unwrap();
4060        let Tail::Return(_, distinct) = c.tail else {
4061            panic!("expected Tail::Return");
4062        };
4063        assert!(distinct);
4064    }
4065
4066    #[test]
4067    fn return_star() {
4068        let c = parse_return("RETURN *").unwrap();
4069        assert!(matches!(c.tail, Tail::ReturnStar(false)));
4070    }
4071
4072    #[test]
4073    fn return_order_by_skip_limit() {
4074        let c = parse_return("RETURN a ORDER BY a DESC SKIP 5 LIMIT 10").unwrap();
4075        let order_by = c.order_by.unwrap();
4076        assert_eq!(order_by.len(), 1);
4077        assert_eq!(order_by[0].0, ReturnExpr::Var("a".to_string()));
4078        assert_eq!(order_by[0].1, SortDir::Desc);
4079        assert_eq!(c.skip, Some(ReturnExpr::Lit(Literal::Int(5))));
4080        assert_eq!(c.limit, Some(ReturnExpr::Lit(Literal::Int(10))));
4081    }
4082
4083    #[test]
4084    fn order_by_default_ascending() {
4085        let c = parse_return("RETURN a ORDER BY a").unwrap();
4086        assert_eq!(c.order_by.unwrap()[0].1, SortDir::Asc);
4087    }
4088
4089    #[test]
4090    fn limit_accepts_arbitrary_expression() {
4091        // skipSt/limitSt grammar-allow any expression -- SKIP/LIMIT no
4092        // longer restrict to a literal integer at parse time (real Cypher
4093        // permits `SKIP $n`/`LIMIT toInteger(rand()*9)`, TCK's
4094        // `ReturnSkipLimit1 [2]`/`[3]`); the non-negative-integer check
4095        // happens once at execution time instead (see
4096        // `executor::resolve_skip_limit`).
4097        let c = parse_return("RETURN a LIMIT 1 + 1").unwrap();
4098        assert!(c.limit.is_some());
4099    }
4100
4101    #[test]
4102    fn return_star_with_extra_items_errors() {
4103        // projectionItems syntactically allows `* , x` (MULT then a
4104        // COMMA'd projectionItem), but Tail::ReturnStar has no field to
4105        // carry the extra item -- must error, not silently drop it.
4106        assert!(parse_return("RETURN *, x AS y").is_err());
4107    }
4108
4109    #[test]
4110    fn with_items() {
4111        let c = parse_with("WITH a, b.name AS name").unwrap();
4112        assert!(!c.star);
4113        assert!(!c.distinct);
4114        assert_eq!(c.items.len(), 2);
4115        assert_eq!(c.items[0].expr, ReturnExpr::Var("a".to_string()));
4116        assert_eq!(c.items[1].alias.as_deref(), Some("name"));
4117    }
4118
4119    #[test]
4120    fn with_star() {
4121        let c = parse_with("WITH *").unwrap();
4122        assert!(c.star);
4123        assert!(c.items.is_empty());
4124    }
4125
4126    #[test]
4127    fn with_star_and_items() {
4128        // Unlike RETURN *, WithClause has both `star` and `items` fields
4129        // -- real Cypher's `WITH *, x AS y` is fully representable.
4130        let c = parse_with("WITH *, x AS y").unwrap();
4131        assert!(c.star);
4132        assert_eq!(c.items.len(), 1);
4133        assert_eq!(c.items[0].alias.as_deref(), Some("y"));
4134    }
4135
4136    #[test]
4137    fn with_distinct_order_skip_limit() {
4138        let c = parse_with("WITH DISTINCT a ORDER BY a SKIP 1 LIMIT 2").unwrap();
4139        assert!(c.distinct);
4140        assert!(c.order_by.is_some());
4141        assert_eq!(c.skip, Some(ReturnExpr::Lit(Literal::Int(1))));
4142        assert_eq!(c.limit, Some(ReturnExpr::Lit(Literal::Int(2))));
4143    }
4144
4145    #[test]
4146    fn with_where_compare() {
4147        let c = parse_with("WITH a WHERE a.x = 1").unwrap();
4148        let WithExpr::Compare(lhs, op, rhs) = c.where_clause.unwrap() else {
4149            panic!("expected WithExpr::Compare");
4150        };
4151        assert_eq!(
4152            lhs,
4153            ReturnExpr::Prop(PropAccess {
4154                var: "a".to_string(),
4155                prop: "x".to_string()
4156            })
4157        );
4158        assert_eq!(op, CompareOp::Eq);
4159        assert_eq!(rhs, ReturnExpr::Lit(Literal::Int(1)));
4160    }
4161
4162    #[test]
4163    fn with_where_and_or_not() {
4164        let c = parse_with("WITH a WHERE NOT (a.x = 1 AND a.y = 2)").unwrap();
4165        assert!(matches!(c.where_clause.unwrap(), WithExpr::Not(_)));
4166
4167        let c = parse_with("WITH a WHERE a.x = 1 OR a.y = 2").unwrap();
4168        assert!(matches!(c.where_clause.unwrap(), WithExpr::Or(_, _)));
4169    }
4170
4171    #[test]
4172    fn with_where_is_null() {
4173        let c = parse_with("WITH a WHERE a IS NULL").unwrap();
4174        assert!(matches!(c.where_clause.unwrap(), WithExpr::IsNull(_)));
4175    }
4176
4177    #[test]
4178    fn with_where_bare_expression() {
4179        // A boolean-valued expression with no comparison operator at all
4180        // (here: a HasLabel check) -- no exact WithExpr variant, so it
4181        // falls back to Bare rather than erroring.
4182        let c = parse_with("WITH n WHERE n:Person").unwrap();
4183        assert!(matches!(c.where_clause.unwrap(), WithExpr::Bare(_)));
4184    }
4185
4186    #[test]
4187    fn with_where_xor_becomes_bare() {
4188        // WithExpr has no Xor variant at all -- confirmed falls back to
4189        // Bare rather than silently dropping the XOR semantics.
4190        let c = parse_with("WITH a WHERE a.x XOR a.y").unwrap();
4191        assert!(matches!(c.where_clause.unwrap(), WithExpr::Bare(_)));
4192    }
4193
4194    #[test]
4195    fn unwind_basic() {
4196        let c = parse_unwind("UNWIND [1, 2, 3] AS x").unwrap();
4197        assert_eq!(c.var, "x");
4198        assert_eq!(
4199            c.source.0,
4200            ReturnExpr::ListLit(vec![
4201                ReturnExpr::Lit(Literal::Int(1)),
4202                ReturnExpr::Lit(Literal::Int(2)),
4203                ReturnExpr::Lit(Literal::Int(3)),
4204            ])
4205        );
4206        assert!(c.where_clause.is_none());
4207        assert!(c.with.is_none());
4208    }
4209
4210    #[test]
4211    fn set_prop() {
4212        let items = parse_set("SET n.name = 'x'").unwrap();
4213        assert_eq!(items.len(), 1);
4214        let SetItem::Prop(prop, value) = &items[0] else {
4215            panic!("expected SetItem::Prop");
4216        };
4217        assert_eq!(prop.var, "n");
4218        assert_eq!(prop.prop, "name");
4219        assert_eq!(*value, ReturnExpr::Lit(Literal::String("x".to_string())));
4220    }
4221
4222    #[test]
4223    fn set_labels() {
4224        let items = parse_set("SET n:A:B").unwrap();
4225        let SetItem::Labels(var, labels) = &items[0] else {
4226            panic!("expected SetItem::Labels");
4227        };
4228        assert_eq!(var, "n");
4229        assert_eq!(labels, &vec!["A".to_string(), "B".to_string()]);
4230    }
4231
4232    #[test]
4233    fn set_map_assign() {
4234        let items = parse_set("SET n = {a: 1}").unwrap();
4235        let SetItem::MapAssign { var, merge, .. } = &items[0] else {
4236            panic!("expected SetItem::MapAssign");
4237        };
4238        assert_eq!(var, "n");
4239        assert!(!merge);
4240
4241        let items = parse_set("SET n += {a: 1}").unwrap();
4242        let SetItem::MapAssign { merge, .. } = &items[0] else {
4243            panic!("expected SetItem::MapAssign");
4244        };
4245        assert!(merge);
4246    }
4247
4248    #[test]
4249    fn set_multiple_items() {
4250        assert_eq!(parse_set("SET n.a = 1, n.b = 2").unwrap().len(), 2);
4251    }
4252
4253    #[test]
4254    fn delete_items() {
4255        let d = parse_delete("DELETE n, r").unwrap();
4256        assert!(!d.detach);
4257        assert_eq!(d.items.len(), 2);
4258    }
4259
4260    #[test]
4261    fn detach_delete() {
4262        let d = parse_delete("DETACH DELETE n").unwrap();
4263        assert!(d.detach);
4264    }
4265
4266    #[test]
4267    fn remove_prop() {
4268        let items = parse_remove("REMOVE n.name").unwrap();
4269        let RemoveItem::Prop(prop) = &items[0] else {
4270            panic!("expected RemoveItem::Prop");
4271        };
4272        assert_eq!(prop.var, "n");
4273        assert_eq!(prop.prop, "name");
4274    }
4275
4276    #[test]
4277    fn remove_labels() {
4278        let items = parse_remove("REMOVE n:A:B").unwrap();
4279        let RemoveItem::Labels(var, labels) = &items[0] else {
4280            panic!("expected RemoveItem::Labels");
4281        };
4282        assert_eq!(var, "n");
4283        assert_eq!(labels, &vec!["A".to_string(), "B".to_string()]);
4284    }
4285
4286    #[test]
4287    fn create_single_pattern() {
4288        let patterns = parse_create("CREATE (a:Person)").unwrap();
4289        assert_eq!(patterns.len(), 1);
4290        assert_eq!(patterns[0].start.var.as_deref(), Some("a"));
4291    }
4292
4293    #[test]
4294    fn create_comma_patterns_stay_separate() {
4295        // Unlike MATCH, CREATE never splices shared-node comma patterns
4296        // into one linear chain -- each stays its own Pattern.
4297        let patterns = parse_create("CREATE (a), (a)-->(b)").unwrap();
4298        assert_eq!(patterns.len(), 2);
4299    }
4300
4301    #[test]
4302    fn create_named_path_errors() {
4303        assert!(parse_create("CREATE p = (a)-->(b)").is_err());
4304    }
4305
4306    #[test]
4307    fn merge_single_hop() {
4308        let m = parse_merge("MERGE (a)-[:KNOWS]->(b)").unwrap();
4309        assert_eq!(m.pattern.hops.len(), 1);
4310        assert!(m.on_create.is_empty());
4311        assert!(m.on_match.is_empty());
4312    }
4313
4314    #[test]
4315    fn merge_multi_hop_errors() {
4316        assert!(parse_merge("MERGE (a)-->(b)-->(c)").is_err());
4317    }
4318
4319    #[test]
4320    fn merge_named_path_capture() {
4321        let m = parse_merge("MERGE p = (a)-->(b)").unwrap();
4322        assert_eq!(m.path_var.as_deref(), Some("p"));
4323    }
4324
4325    #[test]
4326    fn merge_on_create_on_match() {
4327        let m = parse_merge("MERGE (a) ON CREATE SET a.created = true ON MATCH SET a.seen = true")
4328            .unwrap();
4329        assert_eq!(m.on_create.len(), 1);
4330        assert_eq!(m.on_match.len(), 1);
4331    }
4332
4333    #[test]
4334    fn merge_duplicate_on_create_errors() {
4335        assert!(parse_merge("MERGE (a) ON CREATE SET a.x = 1 ON CREATE SET a.y = 2").is_err());
4336    }
4337
4338    #[test]
4339    fn merge_duplicate_on_match_errors() {
4340        assert!(parse_merge("MERGE (a) ON MATCH SET a.x = 1 ON MATCH SET a.y = 2").is_err());
4341    }
4342
4343    #[test]
4344    fn statement_match_return() {
4345        let s = parse_statement("MATCH (a) RETURN a").unwrap();
4346        let Statement::Match {
4347            clauses,
4348            tail,
4349            order_by,
4350            skip,
4351            limit,
4352        } = s
4353        else {
4354            panic!("expected Statement::Match");
4355        };
4356        assert_eq!(clauses.len(), 1);
4357        assert!(matches!(clauses[0], QueryClause::Match(_)));
4358        assert!(matches!(tail, Some(Tail::Return(_, false))));
4359        assert!(order_by.is_none());
4360        assert!(skip.is_none());
4361        assert!(limit.is_none());
4362    }
4363
4364    #[test]
4365    fn statement_return_star() {
4366        let s = parse_statement("MATCH (a) RETURN *").unwrap();
4367        let Statement::Match { tail, .. } = s else {
4368            panic!("expected Statement::Match");
4369        };
4370        assert!(matches!(tail, Some(Tail::ReturnStar(false))));
4371    }
4372
4373    #[test]
4374    fn statement_order_by_skip_limit_on_bare_return() {
4375        let s = parse_statement("MATCH (a) RETURN a ORDER BY a SKIP 1 LIMIT 2").unwrap();
4376        let Statement::Match {
4377            order_by,
4378            skip,
4379            limit,
4380            ..
4381        } = s
4382        else {
4383            panic!("expected Statement::Match");
4384        };
4385        assert!(order_by.is_some());
4386        assert_eq!(skip, Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))));
4387        assert_eq!(limit, Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))));
4388    }
4389
4390    #[test]
4391    fn statement_multiple_reading_clauses() {
4392        let s = parse_statement("MATCH (a) UNWIND [1,2] AS x RETURN a, x").unwrap();
4393        let Statement::Match { clauses, .. } = s else {
4394            panic!("expected Statement::Match");
4395        };
4396        assert_eq!(clauses.len(), 2);
4397        assert!(matches!(clauses[0], QueryClause::Match(_)));
4398        assert!(matches!(clauses[1], QueryClause::Unwind(_)));
4399    }
4400
4401    #[test]
4402    fn statement_set_becomes_tail_with_return_tail() {
4403        let s = parse_statement("MATCH (n) SET n.x = 1 RETURN n").unwrap();
4404        let Statement::Match { clauses, tail, .. } = s else {
4405            panic!("expected Statement::Match");
4406        };
4407        assert_eq!(clauses.len(), 1);
4408        let Some(Tail::Set(items, Some(ret))) = tail else {
4409            panic!("expected Tail::Set with a ReturnTail");
4410        };
4411        assert_eq!(items.len(), 1);
4412        assert_eq!(ret.items.len(), 1);
4413    }
4414
4415    #[test]
4416    fn statement_set_without_trailing_return() {
4417        let s = parse_statement("MATCH (n) SET n.x = 1").unwrap();
4418        let Statement::Match { tail, .. } = s else {
4419            panic!("expected Statement::Match");
4420        };
4421        assert!(matches!(tail, Some(Tail::Set(_, None))));
4422    }
4423
4424    #[test]
4425    fn statement_detach_delete_tail() {
4426        let s = parse_statement("MATCH (n) DETACH DELETE n").unwrap();
4427        let Statement::Match { tail, .. } = s else {
4428            panic!("expected Statement::Match");
4429        };
4430        assert!(matches!(tail, Some(Tail::DetachDelete(_, None))));
4431    }
4432
4433    #[test]
4434    fn statement_two_updating_clauses_last_becomes_tail() {
4435        // SET is just another QueryClause; DELETE (last) becomes the Tail.
4436        let s = parse_statement("MATCH (n) SET n.x = 1 DELETE n RETURN count(n)").unwrap();
4437        let Statement::Match { clauses, tail, .. } = s else {
4438            panic!("expected Statement::Match");
4439        };
4440        assert_eq!(clauses.len(), 2);
4441        assert!(matches!(clauses[1], QueryClause::Set(_)));
4442        assert!(matches!(tail, Some(Tail::Delete(_, Some(_)))));
4443    }
4444
4445    #[test]
4446    fn statement_bare_merge_no_tail() {
4447        // MERGE alone (no RETURN) is the one case a missing Tail is valid
4448        // -- MERGE never becomes the Tail itself (no Tail::Merge variant).
4449        let s = parse_statement("MERGE (a)").unwrap();
4450        let Statement::Match { clauses, tail, .. } = s else {
4451            panic!("expected Statement::Match");
4452        };
4453        assert!(matches!(clauses[0], QueryClause::Merge(_)));
4454        assert!(tail.is_none());
4455    }
4456
4457    #[test]
4458    fn statement_merge_with_trailing_return() {
4459        // MERGE followed by RETURN: MERGE is a QueryClause, RETURN becomes
4460        // the statement's own full Tail::Return (order/skip/limit-capable),
4461        // not a narrower embedded ReturnTail the way SET/DELETE/REMOVE/
4462        // CREATE consume their own trailing RETURN.
4463        let s = parse_statement("MERGE (a) RETURN a ORDER BY a").unwrap();
4464        let Statement::Match {
4465            clauses,
4466            tail,
4467            order_by,
4468            ..
4469        } = s
4470        else {
4471            panic!("expected Statement::Match");
4472        };
4473        assert!(matches!(clauses[0], QueryClause::Merge(_)));
4474        assert!(matches!(tail, Some(Tail::Return(_, false))));
4475        assert!(order_by.is_some());
4476    }
4477
4478    #[test]
4479    fn statement_bare_match_without_tail_errors() {
4480        // Unlike MERGE, a bare MATCH with nothing after it is almost
4481        // certainly a mistake, not a deliberate no-op.
4482        assert!(parse_statement("MATCH (n)").is_err());
4483    }
4484
4485    #[test]
4486    fn statement_mutating_tail_order_by_skip_limit_apply_at_statement_level() {
4487        // ReturnTail itself (SET/DELETE/REMOVE/CREATE's own trailing
4488        // RETURN) has no room for ORDER BY/SKIP/LIMIT -- but real Cypher
4489        // still allows them here (TCK's Delete6/Remove3 "Persistence of
4490        // .../remove clause side effects"), applying to the *statement*,
4491        // same as pest's own grammar keeps them as siblings of tail_clause
4492        // rather than nested inside the RETURN.
4493        let s =
4494            parse_statement("MATCH (n) SET n.x = 1 RETURN n ORDER BY n.x SKIP 1 LIMIT 2").unwrap();
4495        let Statement::Match {
4496            tail,
4497            order_by,
4498            skip,
4499            limit,
4500            ..
4501        } = s
4502        else {
4503            panic!("expected Statement::Match");
4504        };
4505        assert!(matches!(tail, Some(Tail::Set(_, Some(_)))));
4506        assert!(order_by.is_some());
4507        assert_eq!(skip, Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))));
4508        assert_eq!(limit, Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))));
4509    }
4510
4511    #[test]
4512    fn statement_mutating_tail_return_star_errors() {
4513        assert!(parse_statement("MATCH (n) SET n.x = 1 RETURN *").is_err());
4514    }
4515
4516    #[test]
4517    fn statement_create_tail() {
4518        let s = parse_statement("CREATE (a) RETURN a").unwrap();
4519        let Statement::Match { tail, .. } = s else {
4520            panic!("expected Statement::Match");
4521        };
4522        assert!(matches!(tail, Some(Tail::Create(_, Some(_)))));
4523    }
4524
4525    #[test]
4526    fn statement_bare_create_is_not_wrapped_in_match() {
4527        // `CREATE (...)` with nothing else at all mirrors pest's
4528        // `create_stmt_only` -- a real `Statement::Create` directly, not
4529        // `Statement::Match{tail: Some(Tail::Create(...))}`. Found via a
4530        // Phase 3 dry-run: `explain.rs`'s "no query plan" output depends
4531        // on this exact shape distinction.
4532        let s = parse_antlr("CREATE (a);").unwrap();
4533        assert!(matches!(s, Statement::Create(_)));
4534    }
4535
4536    #[test]
4537    fn statement_remove_tail() {
4538        let s = parse_statement("MATCH (n) REMOVE n.x").unwrap();
4539        let Statement::Match { tail, .. } = s else {
4540            panic!("expected Statement::Match");
4541        };
4542        assert!(matches!(tail, Some(Tail::Remove(_, None))));
4543    }
4544
4545    #[test]
4546    fn multi_part_with_attaches_to_preceding_match() {
4547        let s = parse_multi_part_statement("MATCH (a:A) WITH a MATCH (b:B) RETURN a, b").unwrap();
4548        let Statement::Match { clauses, tail, .. } = s else {
4549            panic!("expected Statement::Match");
4550        };
4551        assert_eq!(clauses.len(), 2);
4552        let QueryClause::Match(first) = &clauses[0] else {
4553            panic!("expected first clause to be Match");
4554        };
4555        assert!(first.with.is_some());
4556        assert!(matches!(clauses[1], QueryClause::Match(_)));
4557        assert!(matches!(tail, Some(Tail::Return(_, false))));
4558    }
4559
4560    #[test]
4561    fn multi_part_chained_with_second_one_standalone() {
4562        // TCK's chained `WITH x AS y WITH y % 3 AS y` shape: the first WITH
4563        // attaches to the preceding MATCH, the second has nothing
4564        // attachable immediately before it (another WITH, not a fresh
4565        // clause) so it becomes its own standalone `QueryClause::With`.
4566        let s = parse_multi_part_statement("MATCH (a:A) WITH a.num AS x WITH x % 3 AS x RETURN x")
4567            .unwrap();
4568        let Statement::Match { clauses, .. } = s else {
4569            panic!("expected Statement::Match");
4570        };
4571        assert_eq!(clauses.len(), 2);
4572        let QueryClause::Match(first) = &clauses[0] else {
4573            panic!("expected first clause to be Match");
4574        };
4575        assert!(first.with.is_some());
4576        assert!(matches!(clauses[1], QueryClause::With(_)));
4577    }
4578
4579    #[test]
4580    fn multi_part_set_then_with_stays_separate_entries() {
4581        // SET has no `with` field on its `QueryClause` variant -- a
4582        // following WITH always becomes its own standalone entry, never
4583        // folded into the SET.
4584        let s = parse_multi_part_statement(
4585            "MATCH (n:N) WITH n, n.num AS num DELETE n WITH num WHERE num % 2 = 0 RETURN num",
4586        )
4587        .unwrap();
4588        let Statement::Match { clauses, tail, .. } = s else {
4589            panic!("expected Statement::Match");
4590        };
4591        assert_eq!(clauses.len(), 3);
4592        assert!(matches!(clauses[0], QueryClause::Match(_)));
4593        assert!(matches!(clauses[1], QueryClause::Delete { .. }));
4594        assert!(matches!(clauses[2], QueryClause::With(_)));
4595        assert!(matches!(tail, Some(Tail::Return(_, false))));
4596    }
4597
4598    #[test]
4599    fn multi_part_create_with_star_create_create_tail() {
4600        let s =
4601            parse_multi_part_statement("CREATE (a) WITH a WITH * CREATE (b) CREATE (a)<-[:T]-(b)")
4602                .unwrap();
4603        let Statement::Match { clauses, tail, .. } = s else {
4604            panic!("expected Statement::Match");
4605        };
4606        // Create(a), With(a) folded away into... no: Create has no `with`
4607        // field, so the first WITH is standalone; the second WITH (WITH *)
4608        // is likewise standalone (nothing attachable precedes it either).
4609        assert_eq!(clauses.len(), 4);
4610        assert!(matches!(clauses[0], QueryClause::Create(_)));
4611        assert!(matches!(clauses[1], QueryClause::With(_)));
4612        assert!(matches!(clauses[2], QueryClause::With(_)));
4613        assert!(matches!(clauses[3], QueryClause::Create(_)));
4614        assert!(matches!(tail, Some(Tail::Create(_, None))));
4615    }
4616
4617    #[test]
4618    fn multi_part_merge_with_attaches() {
4619        let s = parse_multi_part_statement("MERGE (a:A) WITH a MATCH (b:B) RETURN a, b").unwrap();
4620        let Statement::Match { clauses, .. } = s else {
4621            panic!("expected Statement::Match");
4622        };
4623        assert_eq!(clauses.len(), 2);
4624        let QueryClause::Merge(m) = &clauses[0] else {
4625            panic!("expected first clause to be Merge");
4626        };
4627        assert!(m.with.is_some());
4628    }
4629
4630    #[test]
4631    fn multi_part_trailing_bare_create_becomes_tail_not_top_level_statement() {
4632        // Regression: build_single_part_q's "bare CREATE with nothing
4633        // else" special case (-> Statement::Create directly) must NOT
4634        // leak out of multiPartQ's own trailing singlePartQ -- past at
4635        // least one WITH boundary, a trailing CREATE is still just this
4636        // statement's Tail::Create, same as any other trailing CREATE.
4637        // Previously panicked (found via a full TCK execution run).
4638        let s = parse_multi_part_statement("MATCH (a) WITH a CREATE (b)").unwrap();
4639        let Statement::Match { clauses, tail, .. } = s else {
4640            panic!("expected Statement::Match");
4641        };
4642        assert_eq!(clauses.len(), 1);
4643        assert!(matches!(clauses[0], QueryClause::Match(_)));
4644        assert!(matches!(tail, Some(Tail::Create(_, None))));
4645    }
4646
4647    #[test]
4648    fn parse_antlr_no_union_passes_through() {
4649        let s = parse_antlr("MATCH (a) RETURN a;").unwrap();
4650        assert!(matches!(s, Statement::Match { .. }));
4651    }
4652
4653    #[test]
4654    fn parse_antlr_union() {
4655        let s = parse_antlr("MATCH (a) RETURN a UNION MATCH (b) RETURN b;").unwrap();
4656        let Statement::Union { parts, all } = s else {
4657            panic!("expected Statement::Union");
4658        };
4659        assert_eq!(parts.len(), 2);
4660        assert!(!all);
4661    }
4662
4663    #[test]
4664    fn parse_antlr_union_all() {
4665        let s = parse_antlr("MATCH (a) RETURN a UNION ALL MATCH (b) RETURN b;").unwrap();
4666        let Statement::Union { parts, all } = s else {
4667            panic!("expected Statement::Union");
4668        };
4669        assert_eq!(parts.len(), 2);
4670        assert!(all);
4671    }
4672
4673    #[test]
4674    fn parse_antlr_union_three_parts() {
4675        let s =
4676            parse_antlr("MATCH (a) RETURN a UNION MATCH (b) RETURN b UNION MATCH (c) RETURN c;")
4677                .unwrap();
4678        let Statement::Union { parts, .. } = s else {
4679            panic!("expected Statement::Union");
4680        };
4681        assert_eq!(parts.len(), 3);
4682    }
4683
4684    #[test]
4685    fn parse_antlr_mixed_union_and_union_all_errors() {
4686        let err = parse_antlr(
4687            "MATCH (a) RETURN a UNION MATCH (b) RETURN b UNION ALL MATCH (c) RETURN c;",
4688        )
4689        .unwrap_err();
4690        assert!(matches!(err, QueryError::Syntax(_)));
4691    }
4692
4693    #[test]
4694    fn parse_antlr_standalone_call() {
4695        let stmt = parse_antlr("CALL db.labels() YIELD label").unwrap();
4696        let Statement::StandaloneCall(call) = stmt else {
4697            panic!("expected a Statement::StandaloneCall, got {stmt:?}");
4698        };
4699        assert_eq!(call.name, "db.labels");
4700        assert_eq!(call.args, Some(vec![]));
4701        assert!(matches!(
4702            call.yield_items,
4703            Some(CallYield::Items(items, None)) if items == vec![("label".to_string(), None)]
4704        ));
4705    }
4706
4707    #[test]
4708    fn parse_antlr_syntax_error() {
4709        assert!(parse_antlr("MATCH (a RETURN a;").is_err());
4710    }
4711
4712    #[test]
4713    fn parse_antlr_many_basic() {
4714        let stmts = parse_antlr_many("CREATE (a); CREATE (b); MATCH (n) RETURN n").unwrap();
4715        assert_eq!(stmts.len(), 3);
4716        // Bare `CREATE (...)` with nothing else is `Statement::Create`
4717        // directly, not `Statement::Match` -- see `build_single_part_q`'s
4718        // own docs.
4719        assert!(matches!(stmts[0], Statement::Create(_)));
4720        assert!(matches!(stmts[2], Statement::Match { .. }));
4721    }
4722
4723    #[test]
4724    fn parse_antlr_many_single_statement() {
4725        let stmts = parse_antlr_many("RETURN 1").unwrap();
4726        assert_eq!(stmts.len(), 1);
4727    }
4728
4729    #[test]
4730    fn parse_antlr_many_strips_single_trailing_semicolon() {
4731        let stmts = parse_antlr_many("CREATE (a);").unwrap();
4732        assert_eq!(stmts.len(), 1);
4733    }
4734
4735    #[test]
4736    fn parse_antlr_many_semicolon_inside_string_literal_not_a_separator() {
4737        let stmts = parse_antlr_many("RETURN ';'").unwrap();
4738        assert_eq!(stmts.len(), 1);
4739    }
4740
4741    #[test]
4742    fn split_statements_respects_all_three_quote_forms() {
4743        // Single-quoted, double-quoted, and backtick-quoted (identifier)
4744        // -- a `;` inside any of them is content, not a separator.
4745        assert_eq!(
4746            split_statements("RETURN ';'; RETURN 1"),
4747            vec!["RETURN ';'", " RETURN 1"]
4748        );
4749        assert_eq!(
4750            split_statements(r#"RETURN ";"; RETURN 1"#),
4751            vec![r#"RETURN ";""#, " RETURN 1"]
4752        );
4753        assert_eq!(
4754            split_statements("MATCH (`a;b`) RETURN 1; RETURN 2"),
4755            vec!["MATCH (`a;b`) RETURN 1", " RETURN 2"]
4756        );
4757    }
4758
4759    #[test]
4760    fn split_statements_handles_escaped_quotes_inside_a_literal() {
4761        // An escaped closing quote (`\'`) doesn't end the string early --
4762        // the real `;` separator is the *second* one, past both escaped
4763        // quotes.
4764        assert_eq!(
4765            split_statements(r"RETURN 'it\'s; a test'; RETURN 1"),
4766            vec![r"RETURN 'it\'s; a test'", " RETURN 1"]
4767        );
4768    }
4769
4770    #[test]
4771    fn split_statements_backtick_literal_has_no_escapes() {
4772        // Unlike '...'/"...", a backtick-quoted identifier has no escape
4773        // sequences in this grammar (`ESC_LITERAL : '`' .*? '`'`) -- a
4774        // backslash inside one is just a literal character, the *very
4775        // next* backtick closes it regardless of what precedes it.
4776        assert_eq!(
4777            split_statements(r"MATCH (`a\`) RETURN 1; RETURN 2"),
4778            vec![r"MATCH (`a\`) RETURN 1", " RETURN 2"]
4779        );
4780    }
4781
4782    #[test]
4783    fn parse_antlr_create_index() {
4784        let s = parse_antlr("CREATE INDEX ON :Person(name);").unwrap();
4785        let Statement::CreateIndex {
4786            label,
4787            prop,
4788            unique,
4789        } = s
4790        else {
4791            panic!("expected Statement::CreateIndex");
4792        };
4793        assert_eq!(label, "Person");
4794        assert_eq!(prop, "name");
4795        assert!(!unique);
4796    }
4797
4798    #[test]
4799    fn parse_antlr_create_index_unique() {
4800        let s = parse_antlr("CREATE INDEX ON :Person(name) UNIQUE;").unwrap();
4801        let Statement::CreateIndex { unique, .. } = s else {
4802            panic!("expected Statement::CreateIndex");
4803        };
4804        assert!(unique);
4805    }
4806
4807    #[test]
4808    fn parse_antlr_explain_match() {
4809        let s = parse_antlr("EXPLAIN MATCH (a) RETURN a;").unwrap();
4810        let Statement::Explain(inner) = s else {
4811            panic!("expected Statement::Explain");
4812        };
4813        assert!(matches!(*inner, Statement::Match { .. }));
4814    }
4815
4816    #[test]
4817    fn parse_antlr_explain_create_index() {
4818        let s = parse_antlr("EXPLAIN CREATE INDEX ON :Person(name);").unwrap();
4819        let Statement::Explain(inner) = s else {
4820            panic!("expected Statement::Explain");
4821        };
4822        assert!(matches!(*inner, Statement::CreateIndex { .. }));
4823    }
4824
4825    #[test]
4826    fn parse_antlr_index_still_usable_as_property_name() {
4827        // `INDEX`/`EXPLAIN` becoming real keyword tokens (needed for
4828        // `createIndexSt`/`explainSt`) must not break their use as
4829        // ordinary property/label names elsewhere -- `name : symbol |
4830        // reservedWord` still absorbs them there.
4831        let s = parse_antlr("MATCH (a) RETURN a.index;").unwrap();
4832        assert!(matches!(s, Statement::Match { .. }));
4833    }
4834}