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` (Phase 3
2697/// cutover) -- parses a `;`-separated batch of one or more statements
2698/// (`"CREATE (a); CREATE (b); MATCH (n) RETURN n"`). `queries : query
2699/// (SEMI query)* EOF` is a mars-specific grammar extension (see
2700/// `grammar/README.md`), including stripping a single genuinely-trailing
2701/// `;` in Rust before parsing -- the grammar rule itself has no trailing
2702/// `SEMI?`, to avoid a `queries`/`script` prefix ambiguity.
2703pub fn parse_antlr_many(input: &str) -> Result<Vec<Statement>, QueryError> {
2704    use crate::generated::cypherlexer::CypherLexer;
2705    use crate::generated::cypherparser::{CypherParser, QueriesContextAttrs};
2706    use antlr4rust::common_token_stream::CommonTokenStream;
2707    use antlr4rust::error_listener::ErrorListener;
2708    use antlr4rust::recognizer::Recognizer;
2709    use antlr4rust::token_factory::TokenFactory;
2710    use antlr4rust::InputStream;
2711    use antlr4rust::Parser as _;
2712    use std::cell::RefCell;
2713
2714    struct CollectErrors(Rc<RefCell<Vec<String>>>);
2715    impl<'a, T: Recognizer<'a>> ErrorListener<'a, T> for CollectErrors {
2716        fn syntax_error(
2717            &self,
2718            _recognizer: &T,
2719            _offending_symbol: Option<&<T::TF as TokenFactory<'a>>::Inner>,
2720            line: isize,
2721            column: isize,
2722            msg: &str,
2723            _e: Option<&antlr4rust::errors::ANTLRError>,
2724        ) {
2725            self.0
2726                .borrow_mut()
2727                .push(format!("line {line}:{column} {msg}"));
2728        }
2729    }
2730
2731    let trimmed = input.trim_end();
2732    let trimmed = trimmed.strip_suffix(';').unwrap_or(trimmed);
2733
2734    let errors = Rc::new(RefCell::new(Vec::new()));
2735    let stream = InputStream::new(trimmed);
2736    let mut lexer = CypherLexer::new(stream);
2737    lexer.remove_error_listeners();
2738    lexer.add_error_listener(Box::new(CollectErrors(errors.clone())));
2739    let tokens = CommonTokenStream::new(lexer);
2740    let mut parser = CypherParser::new(tokens);
2741    parser.remove_error_listeners();
2742    parser.add_error_listener(Box::new(CollectErrors(errors.clone())));
2743    let ctx = parser
2744        .queries()
2745        .map_err(|e| QueryError::Syntax(e.to_string()))?;
2746    if let Some(msg) = errors.borrow().first() {
2747        return Err(QueryError::Syntax(format!("syntax error: {msg}")));
2748    }
2749    ctx.query_all()
2750        .into_iter()
2751        .map(|q| AstBuilder::new().visit(&*q).into_statement())
2752        .collect()
2753}
2754
2755/// `where`'s grammar reuses the same `expression` rule as everywhere else
2756/// (unlike pest, which has a separate, narrower `with_expr` grammar chain
2757/// building `WithExpr` directly) -- so a full `ReturnExpr` has to be built
2758/// first and then folded down into `WithExpr` here. Only the variants with
2759/// an exact `WithExpr` counterpart (`And`/`Or`/`Not`/`Compare`/`IsNull`)
2760/// unwrap recursively; everything else (including `Xor`, which `WithExpr`
2761/// has no variant for at all) becomes `Bare` -- `WithExpr::Bare`'s own
2762/// docs already cover "any boolean-valued expression used directly as a
2763/// predicate", which this falls under regardless of its exact shape.
2764fn return_expr_to_with_expr(expr: ReturnExpr) -> WithExpr {
2765    match expr {
2766        ReturnExpr::And(l, r) => WithExpr::And(
2767            Box::new(return_expr_to_with_expr(*l)),
2768            Box::new(return_expr_to_with_expr(*r)),
2769        ),
2770        ReturnExpr::Or(l, r) => WithExpr::Or(
2771            Box::new(return_expr_to_with_expr(*l)),
2772            Box::new(return_expr_to_with_expr(*r)),
2773        ),
2774        ReturnExpr::Not(inner) => WithExpr::Not(Box::new(return_expr_to_with_expr(*inner))),
2775        ReturnExpr::Compare(l, op, r) => WithExpr::Compare(*l, op, *r),
2776        ReturnExpr::IsNull(inner) => WithExpr::IsNull(*inner),
2777        other => WithExpr::Bare(other),
2778    }
2779}
2780
2781/// `matchSt`'s `where`, like `withSt`'s, reuses the same generic
2782/// `expression` rule as everywhere else (unlike pest, which has dedicated
2783/// narrower grammar rules -- `comparison`/`general_comparison`/
2784/// `label_predicate`/`var_compare` -- picking the right `Expr` variant
2785/// directly at parse time). So the same fold-down-after-the-fact approach
2786/// as `return_expr_to_with_expr` applies here too, just against `Expr`'s
2787/// wider shape: a `Compare` between two bare `Prop`s becomes `PropCompare`,
2788/// a `Prop` compared to a `Lit` keeps the planner-fusable `Compare` variant
2789/// pest's `comparison` rule reserves for exactly that shape, two bare
2790/// `Var`s becomes identity comparison (`VarEq`/`Not(VarEq)`, matching
2791/// pest's `var_compare`'s restriction to `=`/`<>` — anything else is a real
2792/// error, not a silent `GeneralCompare` fallback, since no ordering exists
2793/// between two nodes/relationships), anything else falls back to
2794/// `GeneralCompare`. Similarly `IsNull` on a bare `Prop` keeps the narrow
2795/// variant, anything else becomes `GeneralIsNull`. `HasLabel` folds
2796/// multiple labels into a `HasLabel` `And` chain exactly like pest's
2797/// `parse_label_predicate`. Everything else becomes `GeneralBare`.
2798fn return_expr_to_expr(expr: ReturnExpr) -> Result<Expr, QueryError> {
2799    Ok(match expr {
2800        ReturnExpr::And(l, r) => Expr::And(
2801            Box::new(return_expr_to_expr(*l)?),
2802            Box::new(return_expr_to_expr(*r)?),
2803        ),
2804        ReturnExpr::Or(l, r) => Expr::Or(
2805            Box::new(return_expr_to_expr(*l)?),
2806            Box::new(return_expr_to_expr(*r)?),
2807        ),
2808        ReturnExpr::Not(inner) => Expr::Not(Box::new(return_expr_to_expr(*inner)?)),
2809        ReturnExpr::Compare(l, op, r) => match (*l, *r) {
2810            (ReturnExpr::Prop(pa), ReturnExpr::Lit(lit)) => Expr::Compare(pa, op, lit),
2811            (ReturnExpr::Prop(pa1), ReturnExpr::Prop(pa2)) => Expr::PropCompare(pa1, op, pa2),
2812            (ReturnExpr::Var(a), ReturnExpr::Var(b)) => match op {
2813                CompareOp::Eq => Expr::VarEq(a, b),
2814                CompareOp::Ne => Expr::Not(Box::new(Expr::VarEq(a, b))),
2815                _ => {
2816                    return Err(QueryError::Syntax(format!(
2817                        "{a} {op:?} {b}: only = and <> are meaningful for comparing two \
2818                         nodes/relationships by identity (no ordering exists between them)"
2819                    )))
2820                }
2821            },
2822            (l, r) => Expr::GeneralCompare(l, op, r),
2823        },
2824        ReturnExpr::IsNull(inner) => match *inner {
2825            ReturnExpr::Prop(pa) => Expr::IsNull(pa),
2826            other => Expr::GeneralIsNull(other),
2827        },
2828        ReturnExpr::HasLabel(var, labels) => {
2829            let mut labels = labels.into_iter();
2830            let first = labels
2831                .next()
2832                .expect("HasLabel always carries at least one label");
2833            labels.fold(Expr::HasLabel(var.clone(), first), |acc, label| {
2834                Expr::And(Box::new(acc), Box::new(Expr::HasLabel(var.clone(), label)))
2835            })
2836        }
2837        ReturnExpr::PatternPredicate(pattern) => Expr::Pattern(pattern),
2838        ReturnExpr::ExistsPattern {
2839            pattern,
2840            where_clause,
2841        } => Expr::Exists {
2842            pattern,
2843            where_clause,
2844        },
2845        ReturnExpr::ExistsSubquery(stmt) => Expr::ExistsSubquery(stmt),
2846        other => Expr::GeneralBare(other),
2847    })
2848}
2849
2850#[cfg(test)]
2851mod tests {
2852    use super::*;
2853    use crate::generated::cypherlexer::CypherLexer;
2854    use crate::generated::cypherparser::CypherParser;
2855    use antlr4rust::common_token_stream::CommonTokenStream;
2856    use antlr4rust::InputStream;
2857
2858    fn parse_literal_expr(input: &str) -> Result<Literal, QueryError> {
2859        let stream = InputStream::new(input);
2860        let lexer = CypherLexer::new(stream);
2861        let tokens = CommonTokenStream::new(lexer);
2862        let mut parser = CypherParser::new(tokens);
2863        let ctx = parser
2864            .literal()
2865            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `literal`: {e:?}"));
2866        AstBuilder::new().visit(&*ctx).into_literal()
2867    }
2868
2869    fn parse_pattern(input: &str) -> Result<Pattern, QueryError> {
2870        let stream = InputStream::new(input);
2871        let lexer = CypherLexer::new(stream);
2872        let tokens = CommonTokenStream::new(lexer);
2873        let mut parser = CypherParser::new(tokens);
2874        let ctx = parser
2875            .patternElem()
2876            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `patternElem`: {e:?}"));
2877        AstBuilder::new().visit(&*ctx).into_pattern()
2878    }
2879
2880    fn parse_match(input: &str) -> Result<Vec<QueryPart>, QueryError> {
2881        let stream = InputStream::new(input);
2882        let lexer = CypherLexer::new(stream);
2883        let tokens = CommonTokenStream::new(lexer);
2884        let mut parser = CypherParser::new(tokens);
2885        let ctx = parser
2886            .matchSt()
2887            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `matchSt`: {e:?}"));
2888        AstBuilder::new().visit(&*ctx).into_query_parts()
2889    }
2890
2891    fn parse_expr(input: &str) -> Result<ReturnExpr, QueryError> {
2892        let stream = InputStream::new(input);
2893        let lexer = CypherLexer::new(stream);
2894        let tokens = CommonTokenStream::new(lexer);
2895        let mut parser = CypherParser::new(tokens);
2896        let ctx = parser
2897            .expression()
2898            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `expression`: {e:?}"));
2899        AstBuilder::new().visit(&*ctx).into_return_expr()
2900    }
2901
2902    fn parse_return(input: &str) -> Result<ParsedReturnClause, QueryError> {
2903        let stream = InputStream::new(input);
2904        let lexer = CypherLexer::new(stream);
2905        let tokens = CommonTokenStream::new(lexer);
2906        let mut parser = CypherParser::new(tokens);
2907        let ctx = parser
2908            .returnSt()
2909            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `returnSt`: {e:?}"));
2910        AstBuilder::new().visit(&*ctx).into_return_clause()
2911    }
2912
2913    fn parse_with(input: &str) -> Result<WithClause, QueryError> {
2914        let stream = InputStream::new(input);
2915        let lexer = CypherLexer::new(stream);
2916        let tokens = CommonTokenStream::new(lexer);
2917        let mut parser = CypherParser::new(tokens);
2918        let ctx = parser
2919            .withSt()
2920            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `withSt`: {e:?}"));
2921        AstBuilder::new().visit(&*ctx).into_with_clause()
2922    }
2923
2924    fn parse_unwind(input: &str) -> Result<UnwindClause, QueryError> {
2925        let stream = InputStream::new(input);
2926        let lexer = CypherLexer::new(stream);
2927        let tokens = CommonTokenStream::new(lexer);
2928        let mut parser = CypherParser::new(tokens);
2929        let ctx = parser
2930            .unwindSt()
2931            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `unwindSt`: {e:?}"));
2932        AstBuilder::new().visit(&*ctx).into_unwind_clause()
2933    }
2934
2935    fn parse_set(input: &str) -> Result<Vec<SetItem>, QueryError> {
2936        let stream = InputStream::new(input);
2937        let lexer = CypherLexer::new(stream);
2938        let tokens = CommonTokenStream::new(lexer);
2939        let mut parser = CypherParser::new(tokens);
2940        let ctx = parser
2941            .setSt()
2942            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `setSt`: {e:?}"));
2943        AstBuilder::new().visit(&*ctx).into_set_items()
2944    }
2945
2946    fn parse_delete(input: &str) -> Result<ParsedDelete, QueryError> {
2947        let stream = InputStream::new(input);
2948        let lexer = CypherLexer::new(stream);
2949        let tokens = CommonTokenStream::new(lexer);
2950        let mut parser = CypherParser::new(tokens);
2951        let ctx = parser
2952            .deleteSt()
2953            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `deleteSt`: {e:?}"));
2954        AstBuilder::new().visit(&*ctx).into_delete_items()
2955    }
2956
2957    fn parse_remove(input: &str) -> Result<Vec<RemoveItem>, QueryError> {
2958        let stream = InputStream::new(input);
2959        let lexer = CypherLexer::new(stream);
2960        let tokens = CommonTokenStream::new(lexer);
2961        let mut parser = CypherParser::new(tokens);
2962        let ctx = parser
2963            .removeSt()
2964            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `removeSt`: {e:?}"));
2965        AstBuilder::new().visit(&*ctx).into_remove_items()
2966    }
2967
2968    fn parse_create(input: &str) -> Result<Vec<Pattern>, QueryError> {
2969        let stream = InputStream::new(input);
2970        let lexer = CypherLexer::new(stream);
2971        let tokens = CommonTokenStream::new(lexer);
2972        let mut parser = CypherParser::new(tokens);
2973        let ctx = parser
2974            .createSt()
2975            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `createSt`: {e:?}"));
2976        AstBuilder::new().visit(&*ctx).into_create_patterns()
2977    }
2978
2979    fn parse_merge(input: &str) -> Result<MergeClause, QueryError> {
2980        let stream = InputStream::new(input);
2981        let lexer = CypherLexer::new(stream);
2982        let tokens = CommonTokenStream::new(lexer);
2983        let mut parser = CypherParser::new(tokens);
2984        let ctx = parser
2985            .mergeSt()
2986            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `mergeSt`: {e:?}"));
2987        AstBuilder::new().visit(&*ctx).into_merge_clause()
2988    }
2989
2990    fn parse_statement(input: &str) -> Result<Statement, QueryError> {
2991        let stream = InputStream::new(input);
2992        let lexer = CypherLexer::new(stream);
2993        let tokens = CommonTokenStream::new(lexer);
2994        let mut parser = CypherParser::new(tokens);
2995        let ctx = parser
2996            .singlePartQ()
2997            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `singlePartQ`: {e:?}"));
2998        AstBuilder::new().visit(&*ctx).into_statement()
2999    }
3000
3001    fn parse_multi_part_statement(input: &str) -> Result<Statement, QueryError> {
3002        let stream = InputStream::new(input);
3003        let lexer = CypherLexer::new(stream);
3004        let tokens = CommonTokenStream::new(lexer);
3005        let mut parser = CypherParser::new(tokens);
3006        let ctx = parser
3007            .multiPartQ()
3008            .unwrap_or_else(|e| panic!("failed to parse {input:?} as `multiPartQ`: {e:?}"));
3009        AstBuilder::new().visit(&*ctx).into_statement()
3010    }
3011
3012    #[test]
3013    fn bool_literals() {
3014        assert_eq!(parse_literal_expr("true").unwrap(), Literal::Bool(true));
3015        assert_eq!(parse_literal_expr("FALSE").unwrap(), Literal::Bool(false));
3016    }
3017
3018    #[test]
3019    fn null_literal() {
3020        assert_eq!(parse_literal_expr("null").unwrap(), Literal::Null);
3021    }
3022
3023    #[test]
3024    fn decimal_int() {
3025        assert_eq!(parse_literal_expr("42").unwrap(), Literal::Int(42));
3026        assert_eq!(parse_literal_expr("007").unwrap(), Literal::Int(7));
3027    }
3028
3029    #[test]
3030    fn hex_and_octal_int() {
3031        assert_eq!(parse_literal_expr("0x1A").unwrap(), Literal::Int(26));
3032        assert_eq!(parse_literal_expr("0o17").unwrap(), Literal::Int(15));
3033    }
3034
3035    // `i64::MIN`'s two's-complement edge case (`-9223372036854775808`) is
3036    // exercised once sign-folding lands at the `unaryAddSubExpression`
3037    // level (see this file's module doc) -- unlike pest's `int_literal`,
3038    // which included an optional leading `-` in the literal token itself,
3039    // this grammar's `literal`/`numLit` never carries a sign at all; `-`
3040    // is strictly `unaryAddSubExpression`'s prefix operator, one level up.
3041    // `parse_int_literal` (reused from `parser.rs`) already handles the
3042    // two's-complement case correctly given a leading `-` in its input --
3043    // that part's covered; only the fold-sign-into-literal-vs-build-a-Neg-
3044    // node decision at the expression level remains.
3045
3046    #[test]
3047    fn float_literals() {
3048        assert_eq!(parse_literal_expr("2.5").unwrap(), Literal::Float(2.5));
3049        assert_eq!(parse_literal_expr("1e10").unwrap(), Literal::Float(1e10));
3050        assert_eq!(parse_literal_expr(".5").unwrap(), Literal::Float(0.5));
3051    }
3052
3053    #[test]
3054    fn float_overflow_errors() {
3055        assert!(parse_literal_expr("1e999").is_err());
3056    }
3057
3058    #[test]
3059    fn string_and_char_literals() {
3060        assert_eq!(
3061            parse_literal_expr("\"hello\"").unwrap(),
3062            Literal::String("hello".to_string())
3063        );
3064        assert_eq!(
3065            parse_literal_expr("'a string with spaces and a hyphen-in-it'").unwrap(),
3066            Literal::String("a string with spaces and a hyphen-in-it".to_string())
3067        );
3068    }
3069
3070    #[test]
3071    fn string_escapes() {
3072        assert_eq!(
3073            parse_literal_expr(r#"'line1\nline2'"#).unwrap(),
3074            Literal::String("line1\nline2".to_string())
3075        );
3076        assert_eq!(
3077            parse_literal_expr(r#"'é'"#).unwrap(),
3078            Literal::String("é".to_string())
3079        );
3080    }
3081
3082    #[test]
3083    fn single_node() {
3084        let p = parse_pattern("(a:Person)").unwrap();
3085        assert_eq!(p.start.var.as_deref(), Some("a"));
3086        assert_eq!(p.start.labels, vec!["Person".to_string()]);
3087        assert!(p.hops.is_empty());
3088    }
3089
3090    #[test]
3091    fn anonymous_node() {
3092        let p = parse_pattern("()").unwrap();
3093        assert_eq!(p.start.var, None);
3094        assert!(p.start.labels.is_empty());
3095    }
3096
3097    #[test]
3098    fn multiple_labels() {
3099        let p = parse_pattern("(a:Person:Employee)").unwrap();
3100        assert_eq!(
3101            p.start.labels,
3102            vec!["Person".to_string(), "Employee".to_string()]
3103        );
3104    }
3105
3106    #[test]
3107    fn escaped_identifier() {
3108        let p = parse_pattern("(`weird name`)").unwrap();
3109        assert_eq!(p.start.var.as_deref(), Some("weird name"));
3110    }
3111
3112    #[test]
3113    fn directions() {
3114        assert_eq!(
3115            parse_pattern("(a)-->(b)").unwrap().hops[0].0.direction,
3116            RelDirection::Right
3117        );
3118        assert_eq!(
3119            parse_pattern("(a)<--(b)").unwrap().hops[0].0.direction,
3120            RelDirection::Left
3121        );
3122        assert_eq!(
3123            parse_pattern("(a)--(b)").unwrap().hops[0].0.direction,
3124            RelDirection::Either
3125        );
3126        // Both arrowheads (`<-...->`) is the same undirected/either shape
3127        // as neither -- regression found via the TCK (Match6 [12]/
3128        // Create2 [20]): used to silently resolve to Left,
3129        // checking LT before GT and never noticing GT was also present.
3130        assert_eq!(
3131            parse_pattern("(a)<-->(b)").unwrap().hops[0].0.direction,
3132            RelDirection::Either
3133        );
3134    }
3135
3136    #[test]
3137    fn rel_type_and_var() {
3138        let p = parse_pattern("(a)-[r:KNOWS]->(b)").unwrap();
3139        let (rel, node) = &p.hops[0];
3140        assert_eq!(rel.var.as_deref(), Some("r"));
3141        assert_eq!(rel.rel_types, vec!["KNOWS".to_string()]);
3142        assert_eq!(node.var.as_deref(), Some("b"));
3143        assert_eq!(rel.hop_range, None);
3144    }
3145
3146    #[test]
3147    fn multiple_rel_types() {
3148        let p = parse_pattern("(a)-[:KNOWS|LIKES]->(b)").unwrap();
3149        assert_eq!(
3150            p.hops[0].0.rel_types,
3151            vec!["KNOWS".to_string(), "LIKES".to_string()]
3152        );
3153    }
3154
3155    #[test]
3156    fn var_length_bounds() {
3157        // Exercises the DIGIT/ID lexer fixes end to end -- `*0`/`*2` used
3158        // to hard-fail before those were fixed upstream.
3159        assert_eq!(
3160            parse_pattern("(a)-[*0]->(b)").unwrap().hops[0].0.hop_range,
3161            Some((0, Some(0)))
3162        );
3163        assert_eq!(
3164            parse_pattern("(a)-[*2]->(b)").unwrap().hops[0].0.hop_range,
3165            Some((2, Some(2)))
3166        );
3167        assert_eq!(
3168            parse_pattern("(a)-[*1..3]->(b)").unwrap().hops[0]
3169                .0
3170                .hop_range,
3171            Some((1, Some(3)))
3172        );
3173        assert_eq!(
3174            parse_pattern("(a)-[*]->(b)").unwrap().hops[0].0.hop_range,
3175            Some((1, None))
3176        );
3177    }
3178
3179    #[test]
3180    fn multi_hop_chain() {
3181        let p = parse_pattern("(a)-[:KNOWS]->(b)<-[:LIKES]-(c)").unwrap();
3182        assert_eq!(p.hops.len(), 2);
3183        assert_eq!(p.hops[0].0.direction, RelDirection::Right);
3184        assert_eq!(p.hops[1].0.direction, RelDirection::Left);
3185    }
3186
3187    #[test]
3188    fn node_pattern_properties() {
3189        let pattern = parse_pattern("(a {name: 'x', age: 1 + 1})").unwrap();
3190        assert_eq!(
3191            pattern.start.props,
3192            vec![
3193                (
3194                    "name".to_string(),
3195                    ReturnExpr::Lit(Literal::String("x".to_string()))
3196                ),
3197                (
3198                    "age".to_string(),
3199                    ReturnExpr::Arith(
3200                        Box::new(ReturnExpr::Lit(Literal::Int(1))),
3201                        ArithOp::Add,
3202                        Box::new(ReturnExpr::Lit(Literal::Int(1))),
3203                    )
3204                ),
3205            ]
3206        );
3207    }
3208
3209    #[test]
3210    fn rel_pattern_properties() {
3211        let pattern = parse_pattern("(a)-[:T {weight: 5}]->(b)").unwrap();
3212        assert_eq!(
3213            pattern.hops[0].0.props,
3214            vec![("weight".to_string(), ReturnExpr::Lit(Literal::Int(5)))]
3215        );
3216    }
3217
3218    #[test]
3219    fn pattern_properties_parameter_not_supported() {
3220        assert!(parse_pattern("(a $props)").is_err());
3221    }
3222
3223    #[test]
3224    fn simple_match() {
3225        let parts = parse_match("MATCH (a:Person)-[:KNOWS]->(b)").unwrap();
3226        assert_eq!(parts.len(), 1);
3227        assert!(!parts[0].optional);
3228        assert_eq!(parts[0].path_var, None);
3229        assert_eq!(parts[0].pattern.start.var.as_deref(), Some("a"));
3230        assert_eq!(parts[0].pattern.hops.len(), 1);
3231    }
3232
3233    #[test]
3234    fn optional_match() {
3235        let parts = parse_match("OPTIONAL MATCH (a)").unwrap();
3236        assert!(parts[0].optional);
3237    }
3238
3239    #[test]
3240    fn named_path() {
3241        let parts = parse_match("MATCH p = (a)-->(b)").unwrap();
3242        assert_eq!(parts.len(), 1);
3243        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3244    }
3245
3246    #[test]
3247    fn comma_pattern_shared_node_merges_into_one_linear_chain() {
3248        // `(a)-->(b), (b)-->(c)` shares `b` -- one QueryPart, three-node
3249        // chain, not two disjoint ones. Exercises group_into_linear_patterns.
3250        let parts = parse_match("MATCH (a)-->(b), (b)-->(c)").unwrap();
3251        assert_eq!(parts.len(), 1);
3252        assert_eq!(parts[0].pattern.hops.len(), 2);
3253    }
3254
3255    #[test]
3256    fn comma_pattern_disjoint_becomes_multiple_query_parts() {
3257        let parts = parse_match("MATCH (a), (b)").unwrap();
3258        assert_eq!(parts.len(), 2);
3259    }
3260
3261    #[test]
3262    fn named_path_over_disjoint_cross_join_errors() {
3263        assert!(parse_match("MATCH p = (a), (b)").is_err());
3264    }
3265
3266    #[test]
3267    fn shortest_path() {
3268        let parts = parse_match("MATCH shortestPath((a)-[*1..3]->(b))").unwrap();
3269        assert_eq!(parts.len(), 1);
3270        assert!(parts[0].shortest_path);
3271        assert_eq!(parts[0].pattern.hops.len(), 1);
3272    }
3273
3274    #[test]
3275    fn shortest_path_with_named_path_capture() {
3276        let parts = parse_match("MATCH p = shortestPath((a)-[*1..3]->(b))").unwrap();
3277        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3278        assert!(parts[0].shortest_path);
3279    }
3280
3281    #[test]
3282    fn shortest_path_requires_variable_length_hop() {
3283        assert!(parse_match("MATCH shortestPath((a)-->(b))").is_err());
3284    }
3285
3286    #[test]
3287    fn shortest_path_not_first_in_cross_join_errors() {
3288        assert!(parse_match("MATCH (c), shortestPath((a)-[*1..3]->(b))").is_err());
3289    }
3290
3291    #[test]
3292    fn shortest_path_over_disjoint_cross_join_errors() {
3293        assert!(parse_match("MATCH shortestPath((a)-[*1..3]->(b)), (c)").is_err());
3294    }
3295
3296    #[test]
3297    fn shortest_path_not_valid_in_create() {
3298        assert!(parse_statement("CREATE shortestPath((a)-[*1..3]->(b))").is_err());
3299    }
3300
3301    #[test]
3302    fn shortest_path_not_valid_in_merge() {
3303        assert!(parse_merge("MERGE shortestPath((a)-[*1..3]->(b))").is_err());
3304    }
3305
3306    #[test]
3307    fn named_path_over_a_single_variable_length_hop_is_supported() {
3308        // TCK's Quantifier1-4 [8]/[9] -- a single variable-length hop is
3309        // fine; only *mixing* one with another hop stays rejected (see
3310        // the next test).
3311        let parts = parse_match("MATCH p = (a)-[*1..3]->(b)").unwrap();
3312        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3313    }
3314
3315    #[test]
3316    fn named_path_over_variable_length_mixed_with_another_hop_is_supported() {
3317        // Was rejected until the `LogicalPlan::VarExpand` edge-isomorphism
3318        // gap was fixed -- see `validate_named_path_pattern`'s docs.
3319        let parts = parse_match("MATCH p = (a)-[*1..3]->(b)-->(c)").unwrap();
3320        assert_eq!(parts[0].path_var.as_deref(), Some("p"));
3321    }
3322
3323    #[test]
3324    fn match_where() {
3325        let parts = parse_match("MATCH (a) WHERE a.x = 1").unwrap();
3326        assert_eq!(parts.len(), 1);
3327        assert!(matches!(
3328            parts[0].where_clause,
3329            Some(Expr::Compare(
3330                PropAccess { .. },
3331                CompareOp::Eq,
3332                Literal::Int(1),
3333            ))
3334        ));
3335    }
3336
3337    #[test]
3338    fn match_where_var_eq() {
3339        let parts = parse_match("MATCH (a), (b) WHERE a = b").unwrap();
3340        assert!(matches!(parts[1].where_clause, Some(Expr::VarEq(_, _))));
3341    }
3342
3343    #[test]
3344    fn match_where_label_predicate() {
3345        let parts = parse_match("MATCH (a) WHERE a:A:B").unwrap();
3346        assert!(matches!(parts[0].where_clause, Some(Expr::And(_, _))));
3347    }
3348
3349    #[test]
3350    fn match_where_pattern_predicate() {
3351        let parts = parse_match("MATCH (n) WHERE (n)-[]->() RETURN n")
3352            .unwrap_or_else(|e| panic!("expected pattern predicate to parse, got {e:?}"));
3353        let Some(Expr::Pattern(pattern)) = &parts[0].where_clause else {
3354            panic!("expected Expr::Pattern");
3355        };
3356        assert_eq!(pattern.hops.len(), 1);
3357    }
3358
3359    #[test]
3360    fn match_where_pattern_predicate_combined_with_and() {
3361        let parts = parse_match("MATCH (n) WHERE (n)-->() AND n.x = 1").unwrap();
3362        let Some(Expr::And(l, r)) = &parts[0].where_clause else {
3363            panic!("expected Expr::And");
3364        };
3365        assert!(matches!(**l, Expr::Pattern(_)));
3366        assert!(matches!(**r, Expr::Compare(..)));
3367    }
3368
3369    #[test]
3370    fn pattern_predicate_outside_where_still_parses() {
3371        // Grammatically legal anywhere an expression is (real Cypher
3372        // restricts it to WHERE) -- parses fine as a ReturnExpr;
3373        // semantic::infer_expr is what rejects it outside a WHERE-folded
3374        // position, at compile time (see that function's own docs).
3375        let expr = parse_expr("(n)-->()").unwrap();
3376        assert!(matches!(expr, ReturnExpr::PatternPredicate(_)));
3377    }
3378
3379    #[test]
3380    fn match_where_on_last_group_of_cross_join() {
3381        let parts = parse_match("MATCH (a), (b) WHERE b.x = 1").unwrap();
3382        assert_eq!(parts.len(), 2);
3383        assert!(parts[0].where_clause.is_none());
3384        assert!(parts[1].where_clause.is_some());
3385    }
3386
3387    #[test]
3388    fn arithmetic_precedence() {
3389        // 1 + 2 * 3 = 7, not 9 -- * binds tighter than +.
3390        assert_eq!(
3391            parse_expr("1 + 2 * 3").unwrap(),
3392            ReturnExpr::Arith(
3393                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3394                ArithOp::Add,
3395                Box::new(ReturnExpr::Arith(
3396                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3397                    ArithOp::Mul,
3398                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3399                )),
3400            )
3401        );
3402    }
3403
3404    #[test]
3405    fn arithmetic_left_associative() {
3406        // 10 - 2 - 3 = (10 - 2) - 3 = 5, not 10 - (2 - 3) = 11.
3407        assert_eq!(
3408            parse_expr("10 - 2 - 3").unwrap(),
3409            ReturnExpr::Arith(
3410                Box::new(ReturnExpr::Arith(
3411                    Box::new(ReturnExpr::Lit(Literal::Int(10))),
3412                    ArithOp::Sub,
3413                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3414                )),
3415                ArithOp::Sub,
3416                Box::new(ReturnExpr::Lit(Literal::Int(3))),
3417            )
3418        );
3419    }
3420
3421    #[test]
3422    fn power_left_associative() {
3423        assert_eq!(
3424            parse_expr("4 ^ 3 ^ 2").unwrap(),
3425            ReturnExpr::Arith(
3426                Box::new(ReturnExpr::Arith(
3427                    Box::new(ReturnExpr::Lit(Literal::Int(4))),
3428                    ArithOp::Pow,
3429                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3430                )),
3431                ArithOp::Pow,
3432                Box::new(ReturnExpr::Lit(Literal::Int(2))),
3433            )
3434        );
3435    }
3436
3437    #[test]
3438    fn binary_minus_no_whitespace() {
3439        // Exercises the DIGIT-sign-removal grammar fix end to end: `5-1`
3440        // used to tokenize as two adjacent DIGIT tokens with no operator.
3441        assert_eq!(
3442            parse_expr("5-1").unwrap(),
3443            ReturnExpr::Arith(
3444                Box::new(ReturnExpr::Lit(Literal::Int(5))),
3445                ArithOp::Sub,
3446                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3447            )
3448        );
3449    }
3450
3451    #[test]
3452    fn unary_minus_on_variable() {
3453        assert_eq!(
3454            parse_expr("-x").unwrap(),
3455            ReturnExpr::Neg(Box::new(ReturnExpr::Var("x".to_string())))
3456        );
3457    }
3458
3459    #[test]
3460    fn unary_minus_folds_into_literal() {
3461        assert_eq!(parse_expr("-5").unwrap(), ReturnExpr::Lit(Literal::Int(-5)));
3462        assert_eq!(
3463            parse_expr("-5.5").unwrap(),
3464            ReturnExpr::Lit(Literal::Float(-5.5))
3465        );
3466    }
3467
3468    #[test]
3469    fn unary_minus_int_min_two_complement_edge_case() {
3470        // 9223372036854775808 (2^63) doesn't fit in a positive i64 at all
3471        // -- only i64::MIN's magnitude does. Folding the sign directly
3472        // into the literal (rather than building Neg(Lit(Int(...)))) is
3473        // what makes this representable.
3474        assert_eq!(
3475            parse_expr("-9223372036854775808").unwrap(),
3476            ReturnExpr::Lit(Literal::Int(i64::MIN))
3477        );
3478    }
3479
3480    #[test]
3481    fn comparison_chain_folds_into_nested_and() {
3482        // 1 < x < 3 -> (1 < x) AND (x < 3), real Cypher's chained-
3483        // comparison semantics, not a separate AST shape.
3484        assert_eq!(
3485            parse_expr("1 < x < 3").unwrap(),
3486            ReturnExpr::And(
3487                Box::new(ReturnExpr::Compare(
3488                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3489                    CompareOp::Lt,
3490                    Box::new(ReturnExpr::Var("x".to_string())),
3491                )),
3492                Box::new(ReturnExpr::Compare(
3493                    Box::new(ReturnExpr::Var("x".to_string())),
3494                    CompareOp::Lt,
3495                    Box::new(ReturnExpr::Lit(Literal::Int(3))),
3496                )),
3497            )
3498        );
3499    }
3500
3501    #[test]
3502    fn boolean_operators() {
3503        assert_eq!(
3504            parse_expr("true AND false").unwrap(),
3505            ReturnExpr::And(
3506                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3507                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3508            )
3509        );
3510        assert_eq!(
3511            parse_expr("true OR false").unwrap(),
3512            ReturnExpr::Or(
3513                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3514                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3515            )
3516        );
3517        assert_eq!(
3518            parse_expr("true XOR false").unwrap(),
3519            ReturnExpr::Xor(
3520                Box::new(ReturnExpr::Lit(Literal::Bool(true))),
3521                Box::new(ReturnExpr::Lit(Literal::Bool(false))),
3522            )
3523        );
3524    }
3525
3526    #[test]
3527    fn double_negation() {
3528        // Exercises the notExpression NOT* grammar fix end to end.
3529        assert_eq!(
3530            parse_expr("NOT NOT true").unwrap(),
3531            ReturnExpr::Not(Box::new(ReturnExpr::Not(Box::new(ReturnExpr::Lit(
3532                Literal::Bool(true)
3533            )))))
3534        );
3535    }
3536
3537    #[test]
3538    fn is_null() {
3539        assert_eq!(
3540            parse_expr("x IS NULL").unwrap(),
3541            ReturnExpr::IsNull(Box::new(ReturnExpr::Var("x".to_string())))
3542        );
3543        assert_eq!(
3544            parse_expr("x IS NOT NULL").unwrap(),
3545            ReturnExpr::Not(Box::new(ReturnExpr::IsNull(Box::new(ReturnExpr::Var(
3546                "x".to_string()
3547            )))))
3548        );
3549    }
3550
3551    #[test]
3552    fn in_operator() {
3553        assert_eq!(
3554            parse_expr("x IN y").unwrap(),
3555            ReturnExpr::In(
3556                Box::new(ReturnExpr::Var("x".to_string())),
3557                Box::new(ReturnExpr::Var("y".to_string())),
3558            )
3559        );
3560    }
3561
3562    #[test]
3563    fn is_null_binds_looser_than_arithmetic() {
3564        // Precedence bug found via a Phase 3 behavioral dry-run: `IS
3565        // NULL`/`IN`/`STARTS WITH` etc must bind above `+`/`-`/`*`/`/`/`^`
3566        // (openCypher.bnf's <comparison predicate> chain), so `x + 0 IS
3567        // NULL` is `(x + 0) IS NULL`, not `x + (0 IS NULL)`.
3568        assert_eq!(
3569            parse_expr("x + 0 IS NULL").unwrap(),
3570            ReturnExpr::IsNull(Box::new(ReturnExpr::Arith(
3571                Box::new(ReturnExpr::Var("x".to_string())),
3572                ArithOp::Add,
3573                Box::new(ReturnExpr::Lit(Literal::Int(0))),
3574            )))
3575        );
3576    }
3577
3578    #[test]
3579    fn in_binds_looser_than_arithmetic_and_operand_can_be_sliced() {
3580        assert_eq!(
3581            parse_expr("3 IN [1, 2, 3][0..2]").unwrap(),
3582            ReturnExpr::In(
3583                Box::new(ReturnExpr::Lit(Literal::Int(3))),
3584                Box::new(ReturnExpr::Slice(
3585                    Box::new(ReturnExpr::ListLit(vec![
3586                        ReturnExpr::Lit(Literal::Int(1)),
3587                        ReturnExpr::Lit(Literal::Int(2)),
3588                        ReturnExpr::Lit(Literal::Int(3)),
3589                    ])),
3590                    Some(Box::new(ReturnExpr::Lit(Literal::Int(0)))),
3591                    Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))),
3592                ))
3593            )
3594        );
3595    }
3596
3597    #[test]
3598    fn starts_with_operand_can_be_an_arithmetic_expression() {
3599        assert_eq!(
3600            parse_expr("x STARTS WITH y + z").unwrap(),
3601            ReturnExpr::Compare(
3602                Box::new(ReturnExpr::Var("x".to_string())),
3603                CompareOp::StartsWith,
3604                Box::new(ReturnExpr::Arith(
3605                    Box::new(ReturnExpr::Var("y".to_string())),
3606                    ArithOp::Add,
3607                    Box::new(ReturnExpr::Var("z".to_string())),
3608                )),
3609            )
3610        );
3611    }
3612
3613    #[test]
3614    fn chained_index_postfix_still_works() {
3615        assert_eq!(
3616            parse_expr("[[1, 2], [3, 4]][0][1]").unwrap(),
3617            ReturnExpr::Index(
3618                Box::new(ReturnExpr::Index(
3619                    Box::new(ReturnExpr::ListLit(vec![
3620                        ReturnExpr::ListLit(vec![
3621                            ReturnExpr::Lit(Literal::Int(1)),
3622                            ReturnExpr::Lit(Literal::Int(2)),
3623                        ]),
3624                        ReturnExpr::ListLit(vec![
3625                            ReturnExpr::Lit(Literal::Int(3)),
3626                            ReturnExpr::Lit(Literal::Int(4)),
3627                        ]),
3628                    ])),
3629                    Box::new(ReturnExpr::Lit(Literal::Int(0))),
3630                )),
3631                Box::new(ReturnExpr::Lit(Literal::Int(1))),
3632            )
3633        );
3634    }
3635
3636    #[test]
3637    fn case_searched_form() {
3638        assert_eq!(
3639            parse_expr("CASE WHEN x > 1 THEN 'big' WHEN x > 0 THEN 'small' ELSE 'none' END")
3640                .unwrap(),
3641            ReturnExpr::Case {
3642                test: None,
3643                whens: vec![
3644                    (
3645                        ReturnExpr::Compare(
3646                            Box::new(ReturnExpr::Var("x".to_string())),
3647                            CompareOp::Gt,
3648                            Box::new(ReturnExpr::Lit(Literal::Int(1))),
3649                        ),
3650                        ReturnExpr::Lit(Literal::String("big".to_string())),
3651                    ),
3652                    (
3653                        ReturnExpr::Compare(
3654                            Box::new(ReturnExpr::Var("x".to_string())),
3655                            CompareOp::Gt,
3656                            Box::new(ReturnExpr::Lit(Literal::Int(0))),
3657                        ),
3658                        ReturnExpr::Lit(Literal::String("small".to_string())),
3659                    ),
3660                ],
3661                else_: Some(Box::new(ReturnExpr::Lit(Literal::String(
3662                    "none".to_string()
3663                )))),
3664            }
3665        );
3666    }
3667
3668    #[test]
3669    fn case_simple_form_with_test_no_else() {
3670        assert_eq!(
3671            parse_expr("CASE x WHEN 1 THEN 'one' WHEN 2 THEN 'two' END").unwrap(),
3672            ReturnExpr::Case {
3673                test: Some(Box::new(ReturnExpr::Var("x".to_string()))),
3674                whens: vec![
3675                    (
3676                        ReturnExpr::Lit(Literal::Int(1)),
3677                        ReturnExpr::Lit(Literal::String("one".to_string())),
3678                    ),
3679                    (
3680                        ReturnExpr::Lit(Literal::Int(2)),
3681                        ReturnExpr::Lit(Literal::String("two".to_string())),
3682                    ),
3683                ],
3684                else_: None,
3685            }
3686        );
3687    }
3688
3689    #[test]
3690    fn quantifier_none() {
3691        assert_eq!(
3692            parse_expr("none(x IN [1,2] WHERE x > 1)").unwrap(),
3693            ReturnExpr::Quantifier {
3694                kind: QuantifierKind::None,
3695                var: "x".to_string(),
3696                source: Box::new(ReturnExpr::ListLit(vec![
3697                    ReturnExpr::Lit(Literal::Int(1)),
3698                    ReturnExpr::Lit(Literal::Int(2)),
3699                ])),
3700                where_clause: Some(Box::new(ReturnExpr::Compare(
3701                    Box::new(ReturnExpr::Var("x".to_string())),
3702                    CompareOp::Gt,
3703                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3704                ))),
3705            }
3706        );
3707    }
3708
3709    #[test]
3710    fn quantifier_all_any_single_no_where() {
3711        assert!(matches!(
3712            parse_expr("all(x IN [1]) ").unwrap(),
3713            ReturnExpr::Quantifier {
3714                kind: QuantifierKind::All,
3715                where_clause: None,
3716                ..
3717            }
3718        ));
3719        assert!(matches!(
3720            parse_expr("any(x IN [1])").unwrap(),
3721            ReturnExpr::Quantifier {
3722                kind: QuantifierKind::Any,
3723                ..
3724            }
3725        ));
3726        assert!(matches!(
3727            parse_expr("single(x IN [1])").unwrap(),
3728            ReturnExpr::Quantifier {
3729                kind: QuantifierKind::Single,
3730                ..
3731            }
3732        ));
3733    }
3734
3735    #[test]
3736    fn list_comprehension_with_projection() {
3737        assert_eq!(
3738            parse_expr("[x IN [1,2] WHERE x > 1 | x * 2]").unwrap(),
3739            ReturnExpr::ListComp {
3740                var: "x".to_string(),
3741                source: Box::new(ReturnExpr::ListLit(vec![
3742                    ReturnExpr::Lit(Literal::Int(1)),
3743                    ReturnExpr::Lit(Literal::Int(2)),
3744                ])),
3745                where_clause: Some(Box::new(ReturnExpr::Compare(
3746                    Box::new(ReturnExpr::Var("x".to_string())),
3747                    CompareOp::Gt,
3748                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3749                ))),
3750                project: Some(Box::new(ReturnExpr::Arith(
3751                    Box::new(ReturnExpr::Var("x".to_string())),
3752                    ArithOp::Mul,
3753                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
3754                ))),
3755            }
3756        );
3757    }
3758
3759    #[test]
3760    fn list_comprehension_with_where_no_project() {
3761        assert_eq!(
3762            parse_expr("[x IN [1,2] WHERE x > 1]").unwrap(),
3763            ReturnExpr::ListComp {
3764                var: "x".to_string(),
3765                source: Box::new(ReturnExpr::ListLit(vec![
3766                    ReturnExpr::Lit(Literal::Int(1)),
3767                    ReturnExpr::Lit(Literal::Int(2)),
3768                ])),
3769                where_clause: Some(Box::new(ReturnExpr::Compare(
3770                    Box::new(ReturnExpr::Var("x".to_string())),
3771                    CompareOp::Gt,
3772                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
3773                ))),
3774                project: None,
3775            }
3776        );
3777    }
3778
3779    #[test]
3780    fn list_comprehension_bare_identity_no_where_no_project() {
3781        // `[x IN list]` (neither WHERE nor `| project`) is genuinely
3782        // ambiguous with a one-element `listLit` containing the boolean
3783        // `x IN list` membership test -- `atom`'s alternatives are
3784        // ordered so `listComprehension` wins (real, spec-valid Cypher on
3785        // its own per openCypher.bnf's `<list comprehension>`, whose
3786        // filter/projection half is optional; found wrong via a Phase 3
3787        // behavioral dry-run, not the TCK).
3788        assert_eq!(
3789            parse_expr("[x IN [1, 2, 3]]").unwrap(),
3790            ReturnExpr::ListComp {
3791                var: "x".to_string(),
3792                source: Box::new(ReturnExpr::ListLit(vec![
3793                    ReturnExpr::Lit(Literal::Int(1)),
3794                    ReturnExpr::Lit(Literal::Int(2)),
3795                    ReturnExpr::Lit(Literal::Int(3)),
3796                ])),
3797                where_clause: None,
3798                project: None,
3799            }
3800        );
3801    }
3802
3803    #[test]
3804    fn string_predicates() {
3805        assert_eq!(
3806            parse_expr("x STARTS WITH y").unwrap(),
3807            ReturnExpr::Compare(
3808                Box::new(ReturnExpr::Var("x".to_string())),
3809                CompareOp::StartsWith,
3810                Box::new(ReturnExpr::Var("y".to_string())),
3811            )
3812        );
3813        assert_eq!(
3814            parse_expr("x ENDS WITH y").unwrap(),
3815            ReturnExpr::Compare(
3816                Box::new(ReturnExpr::Var("x".to_string())),
3817                CompareOp::EndsWith,
3818                Box::new(ReturnExpr::Var("y".to_string())),
3819            )
3820        );
3821        assert_eq!(
3822            parse_expr("x CONTAINS y").unwrap(),
3823            ReturnExpr::Compare(
3824                Box::new(ReturnExpr::Var("x".to_string())),
3825                CompareOp::Contains,
3826                Box::new(ReturnExpr::Var("y".to_string())),
3827            )
3828        );
3829    }
3830
3831    #[test]
3832    fn index_and_slice() {
3833        assert_eq!(
3834            parse_expr("list[0]").unwrap(),
3835            ReturnExpr::Index(
3836                Box::new(ReturnExpr::Var("list".to_string())),
3837                Box::new(ReturnExpr::Lit(Literal::Int(0))),
3838            )
3839        );
3840        assert_eq!(
3841            parse_expr("list[1..3]").unwrap(),
3842            ReturnExpr::Slice(
3843                Box::new(ReturnExpr::Var("list".to_string())),
3844                Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))),
3845                Some(Box::new(ReturnExpr::Lit(Literal::Int(3)))),
3846            )
3847        );
3848        assert_eq!(
3849            parse_expr("list[..3]").unwrap(),
3850            ReturnExpr::Slice(
3851                Box::new(ReturnExpr::Var("list".to_string())),
3852                None,
3853                Some(Box::new(ReturnExpr::Lit(Literal::Int(3)))),
3854            )
3855        );
3856        assert_eq!(
3857            parse_expr("list[1..]").unwrap(),
3858            ReturnExpr::Slice(
3859                Box::new(ReturnExpr::Var("list".to_string())),
3860                Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))),
3861                None,
3862            )
3863        );
3864    }
3865
3866    #[test]
3867    fn property_access() {
3868        assert_eq!(
3869            parse_expr("n.name").unwrap(),
3870            ReturnExpr::Prop(PropAccess {
3871                var: "n".to_string(),
3872                prop: "name".to_string(),
3873            })
3874        );
3875    }
3876
3877    #[test]
3878    fn property_access_with_backtick_escaped_name() {
3879        // Regression (found via the TCK, Map1 [5]): `.get_text()` on the
3880        // `name` context kept the surrounding backticks as part of the
3881        // property name (`` `name` `` instead of `name`), so this always
3882        // looked up the wrong key. `name_text` strips them, same as
3883        // `symbol_text` already does for backtick-escaped variable names.
3884        assert_eq!(
3885            parse_expr("n.`weird name`").unwrap(),
3886            ReturnExpr::Prop(PropAccess {
3887                var: "n".to_string(),
3888                prop: "weird name".to_string(),
3889            })
3890        );
3891    }
3892
3893    #[test]
3894    fn property_access_on_computed_expr_becomes_prop_of() {
3895        // `<expr>.prop` where `<expr>` isn't a bare variable -- `ReturnExpr::
3896        // PropOf`, evaluated by evaluating the base first, then looking the
3897        // property up on whatever `Value` it produced (TCK's Graph6 [4]/
3898        // [8], Map1 [3], Merge5 [11]).
3899        let expr = parse_expr("duration.between(a, b).days").unwrap();
3900        let ReturnExpr::PropOf(base, prop) = expr else {
3901            panic!("expected PropOf, got {expr:?}");
3902        };
3903        assert_eq!(prop, "days");
3904        assert!(matches!(*base, ReturnExpr::Call { .. }));
3905    }
3906
3907    #[test]
3908    fn chained_property_access_folds_left_to_right() {
3909        // `a.b.c` -> `PropOf(Prop{a,b}, c)` -- TCK's With2 [2].
3910        let expr = parse_expr("a.b.c").unwrap();
3911        let ReturnExpr::PropOf(base, prop) = expr else {
3912            panic!("expected PropOf, got {expr:?}");
3913        };
3914        assert_eq!(prop, "c");
3915        assert_eq!(
3916            *base,
3917            ReturnExpr::Prop(PropAccess {
3918                var: "a".to_string(),
3919                prop: "b".to_string(),
3920            })
3921        );
3922    }
3923
3924    #[test]
3925    fn has_label() {
3926        assert_eq!(
3927            parse_expr("n:Person").unwrap(),
3928            ReturnExpr::HasLabel("n".to_string(), vec!["Person".to_string()])
3929        );
3930    }
3931
3932    #[test]
3933    fn function_call() {
3934        assert_eq!(
3935            parse_expr("size(list)").unwrap(),
3936            ReturnExpr::Call {
3937                name: "size".to_string(),
3938                args: vec![ReturnExpr::Var("list".to_string())],
3939                distinct: false,
3940            }
3941        );
3942    }
3943
3944    #[test]
3945    fn namespaced_function_call() {
3946        assert_eq!(
3947            parse_expr("duration.between(a, b)").unwrap(),
3948            ReturnExpr::Call {
3949                name: "duration.between".to_string(),
3950                args: vec![
3951                    ReturnExpr::Var("a".to_string()),
3952                    ReturnExpr::Var("b".to_string())
3953                ],
3954                distinct: false,
3955            }
3956        );
3957    }
3958
3959    #[test]
3960    fn count_star() {
3961        assert_eq!(parse_expr("count(*)").unwrap(), ReturnExpr::CountStar);
3962    }
3963
3964    #[test]
3965    fn aggregate_distinct() {
3966        assert_eq!(
3967            parse_expr("count(DISTINCT x)").unwrap(),
3968            ReturnExpr::Call {
3969                name: "count".to_string(),
3970                args: vec![ReturnExpr::Var("x".to_string())],
3971                distinct: true,
3972            }
3973        );
3974    }
3975
3976    #[test]
3977    fn distinct_on_non_aggregate_errors() {
3978        assert!(parse_expr("size(DISTINCT x)").is_err());
3979    }
3980
3981    #[test]
3982    fn distinct_on_namespaced_call_errors() {
3983        assert!(parse_expr("duration.between(DISTINCT a, b)").is_err());
3984    }
3985
3986    #[test]
3987    fn parameter_by_name() {
3988        assert_eq!(
3989            parse_expr("$name").unwrap(),
3990            ReturnExpr::Lit(Literal::Param("name".to_string()))
3991        );
3992    }
3993
3994    #[test]
3995    fn parameter_by_position() {
3996        assert_eq!(
3997            parse_expr("$0").unwrap(),
3998            ReturnExpr::Lit(Literal::Param("0".to_string()))
3999        );
4000    }
4001
4002    #[test]
4003    fn parenthesized_expression() {
4004        assert_eq!(
4005            parse_expr("(1 + 2) * 3").unwrap(),
4006            ReturnExpr::Arith(
4007                Box::new(ReturnExpr::Arith(
4008                    Box::new(ReturnExpr::Lit(Literal::Int(1))),
4009                    ArithOp::Add,
4010                    Box::new(ReturnExpr::Lit(Literal::Int(2))),
4011                )),
4012                ArithOp::Mul,
4013                Box::new(ReturnExpr::Lit(Literal::Int(3))),
4014            )
4015        );
4016    }
4017
4018    #[test]
4019    fn return_simple_items() {
4020        let c = parse_return("RETURN a, b.name AS name").unwrap();
4021        let Tail::Return(items, distinct) = c.tail else {
4022            panic!("expected Tail::Return");
4023        };
4024        assert!(!distinct);
4025        assert_eq!(items.len(), 2);
4026        assert_eq!(items[0].expr, ReturnExpr::Var("a".to_string()));
4027        assert_eq!(items[0].alias, None);
4028        assert_eq!(
4029            items[1].expr,
4030            ReturnExpr::Prop(PropAccess {
4031                var: "b".to_string(),
4032                prop: "name".to_string(),
4033            })
4034        );
4035        assert_eq!(items[1].alias.as_deref(), Some("name"));
4036    }
4037
4038    #[test]
4039    fn return_distinct() {
4040        let c = parse_return("RETURN DISTINCT a").unwrap();
4041        let Tail::Return(_, distinct) = c.tail else {
4042            panic!("expected Tail::Return");
4043        };
4044        assert!(distinct);
4045    }
4046
4047    #[test]
4048    fn return_star() {
4049        let c = parse_return("RETURN *").unwrap();
4050        assert!(matches!(c.tail, Tail::ReturnStar(false)));
4051    }
4052
4053    #[test]
4054    fn return_order_by_skip_limit() {
4055        let c = parse_return("RETURN a ORDER BY a DESC SKIP 5 LIMIT 10").unwrap();
4056        let order_by = c.order_by.unwrap();
4057        assert_eq!(order_by.len(), 1);
4058        assert_eq!(order_by[0].0, ReturnExpr::Var("a".to_string()));
4059        assert_eq!(order_by[0].1, SortDir::Desc);
4060        assert_eq!(c.skip, Some(ReturnExpr::Lit(Literal::Int(5))));
4061        assert_eq!(c.limit, Some(ReturnExpr::Lit(Literal::Int(10))));
4062    }
4063
4064    #[test]
4065    fn order_by_default_ascending() {
4066        let c = parse_return("RETURN a ORDER BY a").unwrap();
4067        assert_eq!(c.order_by.unwrap()[0].1, SortDir::Asc);
4068    }
4069
4070    #[test]
4071    fn limit_accepts_arbitrary_expression() {
4072        // skipSt/limitSt grammar-allow any expression -- SKIP/LIMIT no
4073        // longer restrict to a literal integer at parse time (real Cypher
4074        // permits `SKIP $n`/`LIMIT toInteger(rand()*9)`, TCK's
4075        // `ReturnSkipLimit1 [2]`/`[3]`); the non-negative-integer check
4076        // happens once at execution time instead (see
4077        // `executor::resolve_skip_limit`).
4078        let c = parse_return("RETURN a LIMIT 1 + 1").unwrap();
4079        assert!(c.limit.is_some());
4080    }
4081
4082    #[test]
4083    fn return_star_with_extra_items_errors() {
4084        // projectionItems syntactically allows `* , x` (MULT then a
4085        // COMMA'd projectionItem), but Tail::ReturnStar has no field to
4086        // carry the extra item -- must error, not silently drop it.
4087        assert!(parse_return("RETURN *, x AS y").is_err());
4088    }
4089
4090    #[test]
4091    fn with_items() {
4092        let c = parse_with("WITH a, b.name AS name").unwrap();
4093        assert!(!c.star);
4094        assert!(!c.distinct);
4095        assert_eq!(c.items.len(), 2);
4096        assert_eq!(c.items[0].expr, ReturnExpr::Var("a".to_string()));
4097        assert_eq!(c.items[1].alias.as_deref(), Some("name"));
4098    }
4099
4100    #[test]
4101    fn with_star() {
4102        let c = parse_with("WITH *").unwrap();
4103        assert!(c.star);
4104        assert!(c.items.is_empty());
4105    }
4106
4107    #[test]
4108    fn with_star_and_items() {
4109        // Unlike RETURN *, WithClause has both `star` and `items` fields
4110        // -- real Cypher's `WITH *, x AS y` is fully representable.
4111        let c = parse_with("WITH *, x AS y").unwrap();
4112        assert!(c.star);
4113        assert_eq!(c.items.len(), 1);
4114        assert_eq!(c.items[0].alias.as_deref(), Some("y"));
4115    }
4116
4117    #[test]
4118    fn with_distinct_order_skip_limit() {
4119        let c = parse_with("WITH DISTINCT a ORDER BY a SKIP 1 LIMIT 2").unwrap();
4120        assert!(c.distinct);
4121        assert!(c.order_by.is_some());
4122        assert_eq!(c.skip, Some(ReturnExpr::Lit(Literal::Int(1))));
4123        assert_eq!(c.limit, Some(ReturnExpr::Lit(Literal::Int(2))));
4124    }
4125
4126    #[test]
4127    fn with_where_compare() {
4128        let c = parse_with("WITH a WHERE a.x = 1").unwrap();
4129        let WithExpr::Compare(lhs, op, rhs) = c.where_clause.unwrap() else {
4130            panic!("expected WithExpr::Compare");
4131        };
4132        assert_eq!(
4133            lhs,
4134            ReturnExpr::Prop(PropAccess {
4135                var: "a".to_string(),
4136                prop: "x".to_string()
4137            })
4138        );
4139        assert_eq!(op, CompareOp::Eq);
4140        assert_eq!(rhs, ReturnExpr::Lit(Literal::Int(1)));
4141    }
4142
4143    #[test]
4144    fn with_where_and_or_not() {
4145        let c = parse_with("WITH a WHERE NOT (a.x = 1 AND a.y = 2)").unwrap();
4146        assert!(matches!(c.where_clause.unwrap(), WithExpr::Not(_)));
4147
4148        let c = parse_with("WITH a WHERE a.x = 1 OR a.y = 2").unwrap();
4149        assert!(matches!(c.where_clause.unwrap(), WithExpr::Or(_, _)));
4150    }
4151
4152    #[test]
4153    fn with_where_is_null() {
4154        let c = parse_with("WITH a WHERE a IS NULL").unwrap();
4155        assert!(matches!(c.where_clause.unwrap(), WithExpr::IsNull(_)));
4156    }
4157
4158    #[test]
4159    fn with_where_bare_expression() {
4160        // A boolean-valued expression with no comparison operator at all
4161        // (here: a HasLabel check) -- no exact WithExpr variant, so it
4162        // falls back to Bare rather than erroring.
4163        let c = parse_with("WITH n WHERE n:Person").unwrap();
4164        assert!(matches!(c.where_clause.unwrap(), WithExpr::Bare(_)));
4165    }
4166
4167    #[test]
4168    fn with_where_xor_becomes_bare() {
4169        // WithExpr has no Xor variant at all -- confirmed falls back to
4170        // Bare rather than silently dropping the XOR semantics.
4171        let c = parse_with("WITH a WHERE a.x XOR a.y").unwrap();
4172        assert!(matches!(c.where_clause.unwrap(), WithExpr::Bare(_)));
4173    }
4174
4175    #[test]
4176    fn unwind_basic() {
4177        let c = parse_unwind("UNWIND [1, 2, 3] AS x").unwrap();
4178        assert_eq!(c.var, "x");
4179        assert_eq!(
4180            c.source.0,
4181            ReturnExpr::ListLit(vec![
4182                ReturnExpr::Lit(Literal::Int(1)),
4183                ReturnExpr::Lit(Literal::Int(2)),
4184                ReturnExpr::Lit(Literal::Int(3)),
4185            ])
4186        );
4187        assert!(c.where_clause.is_none());
4188        assert!(c.with.is_none());
4189    }
4190
4191    #[test]
4192    fn set_prop() {
4193        let items = parse_set("SET n.name = 'x'").unwrap();
4194        assert_eq!(items.len(), 1);
4195        let SetItem::Prop(prop, value) = &items[0] else {
4196            panic!("expected SetItem::Prop");
4197        };
4198        assert_eq!(prop.var, "n");
4199        assert_eq!(prop.prop, "name");
4200        assert_eq!(*value, ReturnExpr::Lit(Literal::String("x".to_string())));
4201    }
4202
4203    #[test]
4204    fn set_labels() {
4205        let items = parse_set("SET n:A:B").unwrap();
4206        let SetItem::Labels(var, labels) = &items[0] else {
4207            panic!("expected SetItem::Labels");
4208        };
4209        assert_eq!(var, "n");
4210        assert_eq!(labels, &vec!["A".to_string(), "B".to_string()]);
4211    }
4212
4213    #[test]
4214    fn set_map_assign() {
4215        let items = parse_set("SET n = {a: 1}").unwrap();
4216        let SetItem::MapAssign { var, merge, .. } = &items[0] else {
4217            panic!("expected SetItem::MapAssign");
4218        };
4219        assert_eq!(var, "n");
4220        assert!(!merge);
4221
4222        let items = parse_set("SET n += {a: 1}").unwrap();
4223        let SetItem::MapAssign { merge, .. } = &items[0] else {
4224            panic!("expected SetItem::MapAssign");
4225        };
4226        assert!(merge);
4227    }
4228
4229    #[test]
4230    fn set_multiple_items() {
4231        assert_eq!(parse_set("SET n.a = 1, n.b = 2").unwrap().len(), 2);
4232    }
4233
4234    #[test]
4235    fn delete_items() {
4236        let d = parse_delete("DELETE n, r").unwrap();
4237        assert!(!d.detach);
4238        assert_eq!(d.items.len(), 2);
4239    }
4240
4241    #[test]
4242    fn detach_delete() {
4243        let d = parse_delete("DETACH DELETE n").unwrap();
4244        assert!(d.detach);
4245    }
4246
4247    #[test]
4248    fn remove_prop() {
4249        let items = parse_remove("REMOVE n.name").unwrap();
4250        let RemoveItem::Prop(prop) = &items[0] else {
4251            panic!("expected RemoveItem::Prop");
4252        };
4253        assert_eq!(prop.var, "n");
4254        assert_eq!(prop.prop, "name");
4255    }
4256
4257    #[test]
4258    fn remove_labels() {
4259        let items = parse_remove("REMOVE n:A:B").unwrap();
4260        let RemoveItem::Labels(var, labels) = &items[0] else {
4261            panic!("expected RemoveItem::Labels");
4262        };
4263        assert_eq!(var, "n");
4264        assert_eq!(labels, &vec!["A".to_string(), "B".to_string()]);
4265    }
4266
4267    #[test]
4268    fn create_single_pattern() {
4269        let patterns = parse_create("CREATE (a:Person)").unwrap();
4270        assert_eq!(patterns.len(), 1);
4271        assert_eq!(patterns[0].start.var.as_deref(), Some("a"));
4272    }
4273
4274    #[test]
4275    fn create_comma_patterns_stay_separate() {
4276        // Unlike MATCH, CREATE never splices shared-node comma patterns
4277        // into one linear chain -- each stays its own Pattern.
4278        let patterns = parse_create("CREATE (a), (a)-->(b)").unwrap();
4279        assert_eq!(patterns.len(), 2);
4280    }
4281
4282    #[test]
4283    fn create_named_path_errors() {
4284        assert!(parse_create("CREATE p = (a)-->(b)").is_err());
4285    }
4286
4287    #[test]
4288    fn merge_single_hop() {
4289        let m = parse_merge("MERGE (a)-[:KNOWS]->(b)").unwrap();
4290        assert_eq!(m.pattern.hops.len(), 1);
4291        assert!(m.on_create.is_empty());
4292        assert!(m.on_match.is_empty());
4293    }
4294
4295    #[test]
4296    fn merge_multi_hop_errors() {
4297        assert!(parse_merge("MERGE (a)-->(b)-->(c)").is_err());
4298    }
4299
4300    #[test]
4301    fn merge_named_path_capture() {
4302        let m = parse_merge("MERGE p = (a)-->(b)").unwrap();
4303        assert_eq!(m.path_var.as_deref(), Some("p"));
4304    }
4305
4306    #[test]
4307    fn merge_on_create_on_match() {
4308        let m = parse_merge("MERGE (a) ON CREATE SET a.created = true ON MATCH SET a.seen = true")
4309            .unwrap();
4310        assert_eq!(m.on_create.len(), 1);
4311        assert_eq!(m.on_match.len(), 1);
4312    }
4313
4314    #[test]
4315    fn merge_duplicate_on_create_errors() {
4316        assert!(parse_merge("MERGE (a) ON CREATE SET a.x = 1 ON CREATE SET a.y = 2").is_err());
4317    }
4318
4319    #[test]
4320    fn merge_duplicate_on_match_errors() {
4321        assert!(parse_merge("MERGE (a) ON MATCH SET a.x = 1 ON MATCH SET a.y = 2").is_err());
4322    }
4323
4324    #[test]
4325    fn statement_match_return() {
4326        let s = parse_statement("MATCH (a) RETURN a").unwrap();
4327        let Statement::Match {
4328            clauses,
4329            tail,
4330            order_by,
4331            skip,
4332            limit,
4333        } = s
4334        else {
4335            panic!("expected Statement::Match");
4336        };
4337        assert_eq!(clauses.len(), 1);
4338        assert!(matches!(clauses[0], QueryClause::Match(_)));
4339        assert!(matches!(tail, Some(Tail::Return(_, false))));
4340        assert!(order_by.is_none());
4341        assert!(skip.is_none());
4342        assert!(limit.is_none());
4343    }
4344
4345    #[test]
4346    fn statement_return_star() {
4347        let s = parse_statement("MATCH (a) RETURN *").unwrap();
4348        let Statement::Match { tail, .. } = s else {
4349            panic!("expected Statement::Match");
4350        };
4351        assert!(matches!(tail, Some(Tail::ReturnStar(false))));
4352    }
4353
4354    #[test]
4355    fn statement_order_by_skip_limit_on_bare_return() {
4356        let s = parse_statement("MATCH (a) RETURN a ORDER BY a SKIP 1 LIMIT 2").unwrap();
4357        let Statement::Match {
4358            order_by,
4359            skip,
4360            limit,
4361            ..
4362        } = s
4363        else {
4364            panic!("expected Statement::Match");
4365        };
4366        assert!(order_by.is_some());
4367        assert_eq!(skip, Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))));
4368        assert_eq!(limit, Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))));
4369    }
4370
4371    #[test]
4372    fn statement_multiple_reading_clauses() {
4373        let s = parse_statement("MATCH (a) UNWIND [1,2] AS x RETURN a, x").unwrap();
4374        let Statement::Match { clauses, .. } = s else {
4375            panic!("expected Statement::Match");
4376        };
4377        assert_eq!(clauses.len(), 2);
4378        assert!(matches!(clauses[0], QueryClause::Match(_)));
4379        assert!(matches!(clauses[1], QueryClause::Unwind(_)));
4380    }
4381
4382    #[test]
4383    fn statement_set_becomes_tail_with_return_tail() {
4384        let s = parse_statement("MATCH (n) SET n.x = 1 RETURN n").unwrap();
4385        let Statement::Match { clauses, tail, .. } = s else {
4386            panic!("expected Statement::Match");
4387        };
4388        assert_eq!(clauses.len(), 1);
4389        let Some(Tail::Set(items, Some(ret))) = tail else {
4390            panic!("expected Tail::Set with a ReturnTail");
4391        };
4392        assert_eq!(items.len(), 1);
4393        assert_eq!(ret.items.len(), 1);
4394    }
4395
4396    #[test]
4397    fn statement_set_without_trailing_return() {
4398        let s = parse_statement("MATCH (n) SET n.x = 1").unwrap();
4399        let Statement::Match { tail, .. } = s else {
4400            panic!("expected Statement::Match");
4401        };
4402        assert!(matches!(tail, Some(Tail::Set(_, None))));
4403    }
4404
4405    #[test]
4406    fn statement_detach_delete_tail() {
4407        let s = parse_statement("MATCH (n) DETACH DELETE n").unwrap();
4408        let Statement::Match { tail, .. } = s else {
4409            panic!("expected Statement::Match");
4410        };
4411        assert!(matches!(tail, Some(Tail::DetachDelete(_, None))));
4412    }
4413
4414    #[test]
4415    fn statement_two_updating_clauses_last_becomes_tail() {
4416        // SET is just another QueryClause; DELETE (last) becomes the Tail.
4417        let s = parse_statement("MATCH (n) SET n.x = 1 DELETE n RETURN count(n)").unwrap();
4418        let Statement::Match { clauses, tail, .. } = s else {
4419            panic!("expected Statement::Match");
4420        };
4421        assert_eq!(clauses.len(), 2);
4422        assert!(matches!(clauses[1], QueryClause::Set(_)));
4423        assert!(matches!(tail, Some(Tail::Delete(_, Some(_)))));
4424    }
4425
4426    #[test]
4427    fn statement_bare_merge_no_tail() {
4428        // MERGE alone (no RETURN) is the one case a missing Tail is valid
4429        // -- MERGE never becomes the Tail itself (no Tail::Merge variant).
4430        let s = parse_statement("MERGE (a)").unwrap();
4431        let Statement::Match { clauses, tail, .. } = s else {
4432            panic!("expected Statement::Match");
4433        };
4434        assert!(matches!(clauses[0], QueryClause::Merge(_)));
4435        assert!(tail.is_none());
4436    }
4437
4438    #[test]
4439    fn statement_merge_with_trailing_return() {
4440        // MERGE followed by RETURN: MERGE is a QueryClause, RETURN becomes
4441        // the statement's own full Tail::Return (order/skip/limit-capable),
4442        // not a narrower embedded ReturnTail the way SET/DELETE/REMOVE/
4443        // CREATE consume their own trailing RETURN.
4444        let s = parse_statement("MERGE (a) RETURN a ORDER BY a").unwrap();
4445        let Statement::Match {
4446            clauses,
4447            tail,
4448            order_by,
4449            ..
4450        } = s
4451        else {
4452            panic!("expected Statement::Match");
4453        };
4454        assert!(matches!(clauses[0], QueryClause::Merge(_)));
4455        assert!(matches!(tail, Some(Tail::Return(_, false))));
4456        assert!(order_by.is_some());
4457    }
4458
4459    #[test]
4460    fn statement_bare_match_without_tail_errors() {
4461        // Unlike MERGE, a bare MATCH with nothing after it is almost
4462        // certainly a mistake, not a deliberate no-op.
4463        assert!(parse_statement("MATCH (n)").is_err());
4464    }
4465
4466    #[test]
4467    fn statement_mutating_tail_order_by_skip_limit_apply_at_statement_level() {
4468        // ReturnTail itself (SET/DELETE/REMOVE/CREATE's own trailing
4469        // RETURN) has no room for ORDER BY/SKIP/LIMIT -- but real Cypher
4470        // still allows them here (TCK's Delete6/Remove3 "Persistence of
4471        // .../remove clause side effects"), applying to the *statement*,
4472        // same as pest's own grammar keeps them as siblings of tail_clause
4473        // rather than nested inside the RETURN.
4474        let s =
4475            parse_statement("MATCH (n) SET n.x = 1 RETURN n ORDER BY n.x SKIP 1 LIMIT 2").unwrap();
4476        let Statement::Match {
4477            tail,
4478            order_by,
4479            skip,
4480            limit,
4481            ..
4482        } = s
4483        else {
4484            panic!("expected Statement::Match");
4485        };
4486        assert!(matches!(tail, Some(Tail::Set(_, Some(_)))));
4487        assert!(order_by.is_some());
4488        assert_eq!(skip, Some(Box::new(ReturnExpr::Lit(Literal::Int(1)))));
4489        assert_eq!(limit, Some(Box::new(ReturnExpr::Lit(Literal::Int(2)))));
4490    }
4491
4492    #[test]
4493    fn statement_mutating_tail_return_star_errors() {
4494        assert!(parse_statement("MATCH (n) SET n.x = 1 RETURN *").is_err());
4495    }
4496
4497    #[test]
4498    fn statement_create_tail() {
4499        let s = parse_statement("CREATE (a) RETURN a").unwrap();
4500        let Statement::Match { tail, .. } = s else {
4501            panic!("expected Statement::Match");
4502        };
4503        assert!(matches!(tail, Some(Tail::Create(_, Some(_)))));
4504    }
4505
4506    #[test]
4507    fn statement_bare_create_is_not_wrapped_in_match() {
4508        // `CREATE (...)` with nothing else at all mirrors pest's
4509        // `create_stmt_only` -- a real `Statement::Create` directly, not
4510        // `Statement::Match{tail: Some(Tail::Create(...))}`. Found via a
4511        // Phase 3 dry-run: `explain.rs`'s "no query plan" output depends
4512        // on this exact shape distinction.
4513        let s = parse_antlr("CREATE (a);").unwrap();
4514        assert!(matches!(s, Statement::Create(_)));
4515    }
4516
4517    #[test]
4518    fn statement_remove_tail() {
4519        let s = parse_statement("MATCH (n) REMOVE n.x").unwrap();
4520        let Statement::Match { tail, .. } = s else {
4521            panic!("expected Statement::Match");
4522        };
4523        assert!(matches!(tail, Some(Tail::Remove(_, None))));
4524    }
4525
4526    #[test]
4527    fn multi_part_with_attaches_to_preceding_match() {
4528        let s = parse_multi_part_statement("MATCH (a:A) WITH a MATCH (b:B) RETURN a, b").unwrap();
4529        let Statement::Match { clauses, tail, .. } = s else {
4530            panic!("expected Statement::Match");
4531        };
4532        assert_eq!(clauses.len(), 2);
4533        let QueryClause::Match(first) = &clauses[0] else {
4534            panic!("expected first clause to be Match");
4535        };
4536        assert!(first.with.is_some());
4537        assert!(matches!(clauses[1], QueryClause::Match(_)));
4538        assert!(matches!(tail, Some(Tail::Return(_, false))));
4539    }
4540
4541    #[test]
4542    fn multi_part_chained_with_second_one_standalone() {
4543        // TCK's chained `WITH x AS y WITH y % 3 AS y` shape: the first WITH
4544        // attaches to the preceding MATCH, the second has nothing
4545        // attachable immediately before it (another WITH, not a fresh
4546        // clause) so it becomes its own standalone `QueryClause::With`.
4547        let s = parse_multi_part_statement("MATCH (a:A) WITH a.num AS x WITH x % 3 AS x RETURN x")
4548            .unwrap();
4549        let Statement::Match { clauses, .. } = s else {
4550            panic!("expected Statement::Match");
4551        };
4552        assert_eq!(clauses.len(), 2);
4553        let QueryClause::Match(first) = &clauses[0] else {
4554            panic!("expected first clause to be Match");
4555        };
4556        assert!(first.with.is_some());
4557        assert!(matches!(clauses[1], QueryClause::With(_)));
4558    }
4559
4560    #[test]
4561    fn multi_part_set_then_with_stays_separate_entries() {
4562        // SET has no `with` field on its `QueryClause` variant -- a
4563        // following WITH always becomes its own standalone entry, never
4564        // folded into the SET.
4565        let s = parse_multi_part_statement(
4566            "MATCH (n:N) WITH n, n.num AS num DELETE n WITH num WHERE num % 2 = 0 RETURN num",
4567        )
4568        .unwrap();
4569        let Statement::Match { clauses, tail, .. } = s else {
4570            panic!("expected Statement::Match");
4571        };
4572        assert_eq!(clauses.len(), 3);
4573        assert!(matches!(clauses[0], QueryClause::Match(_)));
4574        assert!(matches!(clauses[1], QueryClause::Delete { .. }));
4575        assert!(matches!(clauses[2], QueryClause::With(_)));
4576        assert!(matches!(tail, Some(Tail::Return(_, false))));
4577    }
4578
4579    #[test]
4580    fn multi_part_create_with_star_create_create_tail() {
4581        let s =
4582            parse_multi_part_statement("CREATE (a) WITH a WITH * CREATE (b) CREATE (a)<-[:T]-(b)")
4583                .unwrap();
4584        let Statement::Match { clauses, tail, .. } = s else {
4585            panic!("expected Statement::Match");
4586        };
4587        // Create(a), With(a) folded away into... no: Create has no `with`
4588        // field, so the first WITH is standalone; the second WITH (WITH *)
4589        // is likewise standalone (nothing attachable precedes it either).
4590        assert_eq!(clauses.len(), 4);
4591        assert!(matches!(clauses[0], QueryClause::Create(_)));
4592        assert!(matches!(clauses[1], QueryClause::With(_)));
4593        assert!(matches!(clauses[2], QueryClause::With(_)));
4594        assert!(matches!(clauses[3], QueryClause::Create(_)));
4595        assert!(matches!(tail, Some(Tail::Create(_, None))));
4596    }
4597
4598    #[test]
4599    fn multi_part_merge_with_attaches() {
4600        let s = parse_multi_part_statement("MERGE (a:A) WITH a MATCH (b:B) RETURN a, b").unwrap();
4601        let Statement::Match { clauses, .. } = s else {
4602            panic!("expected Statement::Match");
4603        };
4604        assert_eq!(clauses.len(), 2);
4605        let QueryClause::Merge(m) = &clauses[0] else {
4606            panic!("expected first clause to be Merge");
4607        };
4608        assert!(m.with.is_some());
4609    }
4610
4611    #[test]
4612    fn multi_part_trailing_bare_create_becomes_tail_not_top_level_statement() {
4613        // Regression: build_single_part_q's "bare CREATE with nothing
4614        // else" special case (-> Statement::Create directly) must NOT
4615        // leak out of multiPartQ's own trailing singlePartQ -- past at
4616        // least one WITH boundary, a trailing CREATE is still just this
4617        // statement's Tail::Create, same as any other trailing CREATE.
4618        // Previously panicked (found via a full TCK execution run).
4619        let s = parse_multi_part_statement("MATCH (a) WITH a CREATE (b)").unwrap();
4620        let Statement::Match { clauses, tail, .. } = s else {
4621            panic!("expected Statement::Match");
4622        };
4623        assert_eq!(clauses.len(), 1);
4624        assert!(matches!(clauses[0], QueryClause::Match(_)));
4625        assert!(matches!(tail, Some(Tail::Create(_, None))));
4626    }
4627
4628    #[test]
4629    fn parse_antlr_no_union_passes_through() {
4630        let s = parse_antlr("MATCH (a) RETURN a;").unwrap();
4631        assert!(matches!(s, Statement::Match { .. }));
4632    }
4633
4634    #[test]
4635    fn parse_antlr_union() {
4636        let s = parse_antlr("MATCH (a) RETURN a UNION MATCH (b) RETURN b;").unwrap();
4637        let Statement::Union { parts, all } = s else {
4638            panic!("expected Statement::Union");
4639        };
4640        assert_eq!(parts.len(), 2);
4641        assert!(!all);
4642    }
4643
4644    #[test]
4645    fn parse_antlr_union_all() {
4646        let s = parse_antlr("MATCH (a) RETURN a UNION ALL MATCH (b) RETURN b;").unwrap();
4647        let Statement::Union { parts, all } = s else {
4648            panic!("expected Statement::Union");
4649        };
4650        assert_eq!(parts.len(), 2);
4651        assert!(all);
4652    }
4653
4654    #[test]
4655    fn parse_antlr_union_three_parts() {
4656        let s =
4657            parse_antlr("MATCH (a) RETURN a UNION MATCH (b) RETURN b UNION MATCH (c) RETURN c;")
4658                .unwrap();
4659        let Statement::Union { parts, .. } = s else {
4660            panic!("expected Statement::Union");
4661        };
4662        assert_eq!(parts.len(), 3);
4663    }
4664
4665    #[test]
4666    fn parse_antlr_mixed_union_and_union_all_errors() {
4667        let err = parse_antlr(
4668            "MATCH (a) RETURN a UNION MATCH (b) RETURN b UNION ALL MATCH (c) RETURN c;",
4669        )
4670        .unwrap_err();
4671        assert!(matches!(err, QueryError::Syntax(_)));
4672    }
4673
4674    #[test]
4675    fn parse_antlr_standalone_call() {
4676        let stmt = parse_antlr("CALL db.labels() YIELD label").unwrap();
4677        let Statement::StandaloneCall(call) = stmt else {
4678            panic!("expected a Statement::StandaloneCall, got {stmt:?}");
4679        };
4680        assert_eq!(call.name, "db.labels");
4681        assert_eq!(call.args, Some(vec![]));
4682        assert!(matches!(
4683            call.yield_items,
4684            Some(CallYield::Items(items, None)) if items == vec![("label".to_string(), None)]
4685        ));
4686    }
4687
4688    #[test]
4689    fn parse_antlr_syntax_error() {
4690        assert!(parse_antlr("MATCH (a RETURN a;").is_err());
4691    }
4692
4693    #[test]
4694    fn parse_antlr_many_basic() {
4695        let stmts = parse_antlr_many("CREATE (a); CREATE (b); MATCH (n) RETURN n").unwrap();
4696        assert_eq!(stmts.len(), 3);
4697        // Bare `CREATE (...)` with nothing else is `Statement::Create`
4698        // directly, not `Statement::Match` -- see `build_single_part_q`'s
4699        // own docs.
4700        assert!(matches!(stmts[0], Statement::Create(_)));
4701        assert!(matches!(stmts[2], Statement::Match { .. }));
4702    }
4703
4704    #[test]
4705    fn parse_antlr_many_single_statement() {
4706        let stmts = parse_antlr_many("RETURN 1").unwrap();
4707        assert_eq!(stmts.len(), 1);
4708    }
4709
4710    #[test]
4711    fn parse_antlr_many_strips_single_trailing_semicolon() {
4712        let stmts = parse_antlr_many("CREATE (a);").unwrap();
4713        assert_eq!(stmts.len(), 1);
4714    }
4715
4716    #[test]
4717    fn parse_antlr_many_semicolon_inside_string_literal_not_a_separator() {
4718        let stmts = parse_antlr_many("RETURN ';'").unwrap();
4719        assert_eq!(stmts.len(), 1);
4720    }
4721
4722    #[test]
4723    fn parse_antlr_create_index() {
4724        let s = parse_antlr("CREATE INDEX ON :Person(name);").unwrap();
4725        let Statement::CreateIndex {
4726            label,
4727            prop,
4728            unique,
4729        } = s
4730        else {
4731            panic!("expected Statement::CreateIndex");
4732        };
4733        assert_eq!(label, "Person");
4734        assert_eq!(prop, "name");
4735        assert!(!unique);
4736    }
4737
4738    #[test]
4739    fn parse_antlr_create_index_unique() {
4740        let s = parse_antlr("CREATE INDEX ON :Person(name) UNIQUE;").unwrap();
4741        let Statement::CreateIndex { unique, .. } = s else {
4742            panic!("expected Statement::CreateIndex");
4743        };
4744        assert!(unique);
4745    }
4746
4747    #[test]
4748    fn parse_antlr_explain_match() {
4749        let s = parse_antlr("EXPLAIN MATCH (a) RETURN a;").unwrap();
4750        let Statement::Explain(inner) = s else {
4751            panic!("expected Statement::Explain");
4752        };
4753        assert!(matches!(*inner, Statement::Match { .. }));
4754    }
4755
4756    #[test]
4757    fn parse_antlr_explain_create_index() {
4758        let s = parse_antlr("EXPLAIN CREATE INDEX ON :Person(name);").unwrap();
4759        let Statement::Explain(inner) = s else {
4760            panic!("expected Statement::Explain");
4761        };
4762        assert!(matches!(*inner, Statement::CreateIndex { .. }));
4763    }
4764
4765    #[test]
4766    fn parse_antlr_index_still_usable_as_property_name() {
4767        // `INDEX`/`EXPLAIN` becoming real keyword tokens (needed for
4768        // `createIndexSt`/`explainSt`) must not break their use as
4769        // ordinary property/label names elsewhere -- `name : symbol |
4770        // reservedWord` still absorbs them there.
4771        let s = parse_antlr("MATCH (a) RETURN a.index;").unwrap();
4772        assert!(matches!(s, Statement::Match { .. }));
4773    }
4774}