cyrs-syntax 0.1.0

Lossless CST and recovering parser for Cypher / GQL (spec 0001 §4).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
//! Expression parser — Pratt operator precedence over the openCypher /
//! GQL operator table. Spec §4.2 ("hand-written event-based recursive-
//! descent with Pratt precedence for expressions").
//!
//! # Precedence table (loose to tight)
//!
//! Numeric priority is the binding power of the *left* operand; an
//! operator binds the right operand at `priority + 1` for left
//! associativity, `priority` for right associativity. Match openCypher /
//! GQL canonical ordering:
//!
//! | Priority | Operators                                                  | Assoc |
//! | -------: | ---------------------------------------------------------- | ----- |
//! |        1 | `OR`                                                       | left  |
//! |        2 | `XOR`                                                      | left  |
//! |        3 | `AND`                                                      | left  |
//! |        4 | unary `NOT`                                                | prefix|
//! |        5 | `=` `<>` `!=` `<` `<=` `>` `>=` `IS [NOT] NULL` `STARTS WITH` `ENDS WITH` `CONTAINS` `=~` `IN` | non-assoc |
//! |        6 | `+` `-`                                                    | left  |
//! |        7 | `*` `/` `%`                                                | left  |
//! |        8 | `^`                                                        | right |
//! |        9 | unary `-` / unary `+`                                      | prefix|
//! |       10 | postfix: `.`, `[]`, `()`                                   | left  |
//! |     atom | identifier / literal / parenthesised / parameter           | —     |
//!
//! # cy-nom scope
//!
//! Implemented: every operator in the table above. Atoms cover
//! identifier, int/float/string/bool/null literal, parameter, and
//! `(Expr)`. Postfix covers property access, function call, and index.
//!
//! Deferred (each tagged with `cy-nom: v1 scope` at its stub):
//! list literals `[...]`, map literals `{...}`, list/pattern
//! comprehensions, `CASE` expressions, pattern predicates in expressions,
//! `EXISTS(...)`, `COUNT(*)` standalone form.

use crate::SyntaxKind;
use crate::parser::{CompletedMarker, Marker, Parser, TokenSet, syntax_codes as sc};

use super::pattern;

/// Parse an expression and return a handle to the completed root node.
/// Returns `None` if the current token starts nothing expression-like —
/// the caller should emit its own "expected expression" diagnostic.
pub(crate) fn expr(p: &mut Parser<'_>) -> Option<CompletedMarker> {
    expr_bp(p, 0)
}

/// Recursion-safety cap. Pathological inputs like nested parens cannot
/// exceed this depth. Protects fuzz against stack overflow.
const MAX_EXPR_DEPTH: u32 = 256;

/// Pratt loop. `min_bp` is the minimum binding power a binary operator
/// must exceed to continue the expression on the right. Unary operators
/// and atoms are parsed in `lhs`.
fn expr_bp(p: &mut Parser<'_>, min_bp: u8) -> Option<CompletedMarker> {
    expr_bp_depth(p, min_bp, 0)
}

fn expr_bp_depth(p: &mut Parser<'_>, min_bp: u8, depth: u32) -> Option<CompletedMarker> {
    if depth > MAX_EXPR_DEPTH {
        p.error_code(
            sc::EXPR_NESTING_LIMIT,
            "expression nesting exceeds parser limit",
        );
        return None;
    }

    // --- Prefix / unary --------------------------------------------------
    let mut lhs = if let Some(prefix_bp) = prefix_bp(p.current()) {
        let m = p.start();
        let op_kind = p.current();
        p.bump_any();
        // Right binding power drives recursion. Unary is right-associative.
        if expr_bp_depth(p, prefix_bp, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_UNARY_OPERAND,
                format!("expected operand after unary {op_kind:?}"),
            );
        }
        m.complete(p, SyntaxKind::UNARY_EXPR)
    } else {
        atom(p, depth)?
    };

    // --- Postfix + infix loop -------------------------------------------
    loop {
        // Postfix operators always bind tightest.
        if let Some(postfix) = postfix_op(p) {
            if postfix.bp < min_bp {
                break;
            }
            lhs = apply_postfix(p, lhs, postfix, depth);
            continue;
        }

        // `IS [NOT] NULL` — postfix, priority 5 (comparison-level).
        if p.at(SyntaxKind::IS_KW) {
            let null_check_bp = 10;
            if null_check_bp < min_bp {
                break;
            }
            let m = lhs.precede(p);
            p.bump(SyntaxKind::IS_KW);
            p.eat(SyntaxKind::NOT_KW);
            if !p.eat(SyntaxKind::NULL_KW) {
                p.error_code(sc::EXPECTED_NULL_AFTER_IS, "expected NULL after IS");
            }
            lhs = m.complete(p, SyntaxKind::IS_NULL_EXPR);
            continue;
        }

        // Infix binary operators.
        if let Some(op) = infix_op(p) {
            if op.left_bp < min_bp {
                break;
            }
            let m = lhs.precede(p);
            // Consume the operator token(s).
            consume_infix_op(p, op.kind);
            // Right-hand side parses at right_bp.
            if expr_bp_depth(p, op.right_bp, depth + 1).is_none() {
                p.error_code(
                    sc::EXPECTED_BINOP_RHS,
                    "expected right-hand side of binary expression",
                );
            }
            lhs = m.complete(p, op.node);
            continue;
        }

        break;
    }

    Some(lhs)
}

// --------------------------------------------------------------------------
// Atoms
// --------------------------------------------------------------------------

fn atom(p: &mut Parser<'_>, depth: u32) -> Option<CompletedMarker> {
    let kind = p.current();
    Some(match kind {
        SyntaxKind::INT_LITERAL | SyntaxKind::FLOAT_LITERAL | SyntaxKind::STRING_LITERAL => {
            literal_atom(p, SyntaxKind::LITERAL_EXPR)
        }
        SyntaxKind::TRUE_KW | SyntaxKind::FALSE_KW => {
            literal_keyword_atom(p, SyntaxKind::LITERAL_EXPR)
        }
        SyntaxKind::NULL_KW => literal_keyword_atom(p, SyntaxKind::LITERAL_EXPR),
        SyntaxKind::PARAM => {
            let m = p.start();
            p.bump(SyntaxKind::PARAM);
            m.complete(p, SyntaxKind::PARAM_EXPR)
        }
        SyntaxKind::IDENT | SyntaxKind::QUOTED_IDENT => {
            // Variable reference. A following `(` is handled as a postfix
            // function-call in the infix/postfix loop.
            let m = p.start();
            p.bump_any();
            m.complete(p, SyntaxKind::VAR_EXPR)
        }
        // `EXISTS` has three surface forms (cy-lve, spec §6.1 / §19):
        //
        //   1. `EXISTS ( <pattern> )` — pattern predicate. Accepted; lowered
        //      to `PATTERN_PREDICATE` so HIR / sema see the same shape as
        //      a bare `(a)-->(b)` in WHERE position.
        //   2. `EXISTS ( <expr> )` — `exists(expr)` function call (e.g.
        //      `exists(n.prop)`). Falls through to the `VAR_EXPR` + postfix
        //      function-call path.
        //   3. `EXISTS { … }` — block-subquery form. Deferred per spec §19 /
        //      §20 D1; emit E4017 and swallow the braced body for recovery.
        //
        // Disambiguation between (1) and (2): openCypher patterns always
        // begin with an `(` (the first node pattern). A `(` immediately
        // after `EXISTS (` therefore indicates form (1); anything else
        // falls through to form (2). This is the same shape heuristic
        // tree-sitter-cypher uses for `exists_expression` vs.
        // `exists_function_invocation` (spec §19 "Pattern predicates in
        // expressions" — the ambiguity is resolved by the nested `(`).
        SyntaxKind::EXISTS_KW => {
            if p.nth(1) == SyntaxKind::L_BRACE {
                // Form (3): block subquery. Not in v1. Emit E4017 and
                // recover by consuming the balanced braces.
                exists_block_deferred(p)
            } else if p.nth(1) == SyntaxKind::L_PAREN && p.nth(2) == SyntaxKind::L_PAREN {
                // Form (1): pattern predicate.
                exists_pattern_predicate(p)
            } else {
                // Form (2): fall through to function-call shape.
                let m = p.start();
                p.bump_any();
                m.complete(p, SyntaxKind::VAR_EXPR)
            }
        }
        // `COUNT` lexes as a dedicated keyword token (lexer §4.1) but in
        // expression position it stands in for the aggregate function
        // identifier — `count(n)` / `count(*)`. Accept the keyword as a
        // VAR_EXPR so the postfix `(` loop can wrap it in a FUNCTION_CALL.
        SyntaxKind::COUNT_KW => {
            let m = p.start();
            p.bump_any();
            m.complete(p, SyntaxKind::VAR_EXPR)
        }
        // List predicates (cy-8x5). `ANY / ALL / NONE / SINGLE (x IN xs
        // [WHERE p])`. The discriminant keyword token stays as the first
        // child of the emitted `LIST_PREDICATE_EXPR` so downstream passes
        // (HIR lowering, pretty-printers) can classify without a per-kind
        // SyntaxKind. `ALL_KW` also appears in `UNION ALL`; there the
        // `(` lookahead is absent so the expression path does not fire.
        SyntaxKind::ANY_KW | SyntaxKind::ALL_KW | SyntaxKind::NONE_KW | SyntaxKind::SINGLE_KW
            if p.nth(1) == SyntaxKind::L_PAREN =>
        {
            list_predicate(p, depth)
        }
        // `(` in expression position is ambiguous between a parenthesised
        // expression (`(1 + 2)`, `(a.name)`, …) and a bare pattern predicate
        // (`(a)-->(b)`, `(:Label)-[:R]->()`, …) — spec §6.1 desugaring row
        // "Pattern predicates in expressions" / §19. Dispatch on a two-token
        // lookahead past the opening paren per cy-7lf; see
        // [`at_bare_pattern_predicate`] for the token table.
        SyntaxKind::L_PAREN => {
            if at_bare_pattern_predicate(p) {
                bare_pattern_predicate(p)
            } else {
                paren_expr(p, depth)
            }
        }
        SyntaxKind::L_BRACK => list_literal(p, depth),
        SyntaxKind::L_BRACE => map_literal(p, depth),
        // `CASE` expression — generic + simple-when forms (cy-41u,
        // spec §19 row "CASE").
        SyntaxKind::CASE_KW => case_expr(p, depth),
        // cy-nom: v1 scope — pattern predicates, EXISTS(...) land in
        // follow-up beads.
        _ => return None,
    })
}

/// `ListLiteral = '[' (Expr (',' Expr)*)? ']'` — spec `cypher.ungrammar`
/// `ListLiteral`. List comprehensions (`[x IN xs WHERE p | f(x)]`) share
/// the opening `[` with literals and are disambiguated here: if the first
/// element is an IDENT followed by `IN`, this parses as a
/// [`SyntaxKind::LIST_COMPREHENSION`]; otherwise it is a
/// [`SyntaxKind::LIST_LITERAL`].
fn list_literal(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_BRACK));

    // Comprehension lookahead: `[ IDENT IN ...`.
    // The first significant token past `[` is at nth(1); the IN check sits
    // at nth(2). We only dispatch to the comprehension parse path on an
    // exact match to avoid regressing the list-literal grammar (cy-7s6.1).
    if matches!(p.nth(1), SyntaxKind::IDENT | SyntaxKind::QUOTED_IDENT)
        && p.nth(2) == SyntaxKind::IN_KW
    {
        return list_comprehension(p, depth);
    }

    let m = p.start();
    p.bump(SyntaxKind::L_BRACK);
    if !p.at(SyntaxKind::R_BRACK) {
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_LIST_ELEM,
                "expected expression in list literal",
            );
        }
        while p.at(SyntaxKind::COMMA) {
            p.bump(SyntaxKind::COMMA);
            if expr_bp_depth(p, 0, depth + 1).is_none() {
                p.error_code(
                    sc::EXPECTED_LIST_ELEM,
                    "expected expression in list literal",
                );
                break;
            }
        }
    }
    if !p.eat(SyntaxKind::R_BRACK) {
        p.error_code(
            sc::EXPECTED_RBRACK_LIST,
            "expected ']' to close list literal",
        );
    }
    m.complete(p, SyntaxKind::LIST_LITERAL)
}

/// Parse a list comprehension (spec §19 row "List comprehensions",
/// ungrammar `ListComprehension`):
///
/// ```text
/// ListComprehension = '[' NameDef 'IN' Expr ( 'WHERE' Expr )? ( '|' Expr )? ']'
/// ```
///
/// Every production is optional except the iteration variable binder and
/// the source expression (`NameDef 'IN' Expr`). The four legal shapes:
///
/// - `[x IN xs]`                              — no predicate, no map
/// - `[x IN xs WHERE p(x)]`                   — filter only (implicit identity map)
/// - `[x IN xs | f(x)]`                       — map only
/// - `[x IN xs WHERE p(x) | f(x)]`            — filter and map
///
/// Enters on the opening `[`; `nth(1)` / `nth(2)` lookahead already
/// confirmed the `IDENT IN` prefix at the [`list_literal`] dispatch point.
fn list_comprehension(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_BRACK));
    let m = p.start();
    p.bump(SyntaxKind::L_BRACK);

    // NameDef — wrap the identifier in a NAME node so lowering can find it.
    {
        let name = p.start();
        if !(p.eat(SyntaxKind::IDENT) || p.eat(SyntaxKind::QUOTED_IDENT)) {
            // The dispatch lookahead guarantees we are at an IDENT here.
            // Defensive fallback: emit and close an empty NAME so the tree
            // still round-trips.
            p.error_code(
                sc::EXPECTED_IDENT,
                "expected iteration variable in list comprehension",
            );
        }
        name.complete(p, SyntaxKind::NAME);
    }

    // 'IN' — required.
    if !p.eat(SyntaxKind::IN_KW) {
        p.error_code(
            sc::EXPECTED_IN_LIST_COMP,
            "expected `IN` in list comprehension",
        );
    }

    // Source expression (iterable) — required.
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(
            sc::EXPECTED_LIST_ELEM,
            "expected expression for list-comprehension source",
        );
    }

    // Optional WHERE predicate.
    if p.at(SyntaxKind::WHERE_KW) {
        p.bump(SyntaxKind::WHERE_KW);
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_WHERE_EXPR,
                "expected predicate expression after `WHERE` in list comprehension",
            );
        }
    }

    // Optional `|` projection. Matches openCypher §3.3 (list comprehension
    // production). After the optional WHERE predicate the grammar accepts
    // either `|` followed by the projection expression, or directly `]`.
    if p.at(SyntaxKind::PIPE) {
        p.bump(SyntaxKind::PIPE);
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_BINOP_RHS,
                "expected projection expression after `|` in list comprehension",
            );
        }
    }

    if !p.eat(SyntaxKind::R_BRACK) {
        p.error_code(
            sc::EXPECTED_PIPE_OR_RBRACK_LIST_COMP,
            "expected `|` or `]` in list comprehension",
        );
    }

    m.complete(p, SyntaxKind::LIST_COMPREHENSION)
}

/// `MapLiteral = '{' (PropertyKV (',' PropertyKV)*)? '}'` — spec
/// `cypher.ungrammar` `MapLiteral`. Same shape as the property-map
/// shorthand inside patterns; when the `{` appears in *expression*
/// position the parser binds this production, when it appears inside a
/// `NodePattern` / `RelDetail` the caller's existing property-map
/// handling owns it (see `grammar::pattern::property_map`).
fn map_literal(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_BRACE));
    let m = p.start();
    p.bump(SyntaxKind::L_BRACE);
    if !p.at(SyntaxKind::R_BRACE) {
        map_entry(p, depth);
        while p.at(SyntaxKind::COMMA) {
            p.bump(SyntaxKind::COMMA);
            if p.at(SyntaxKind::R_BRACE) {
                break;
            }
            map_entry(p, depth);
        }
    }
    if !p.eat(SyntaxKind::R_BRACE) {
        p.error_code(sc::EXPECTED_RBRACE_MAP, "expected '}' to close map literal");
    }
    m.complete(p, SyntaxKind::MAP_LITERAL)
}

fn map_entry(p: &mut Parser<'_>, depth: u32) {
    if !(p.eat(SyntaxKind::IDENT) || p.eat(SyntaxKind::QUOTED_IDENT)) {
        p.error_code(sc::EXPECTED_MAP_KEY, "expected key in map literal");
    }
    if !p.eat(SyntaxKind::COLON) {
        p.error_code(sc::EXPECTED_COLON_MAP, "expected ':' in map entry");
    }
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(sc::EXPECTED_MAP_VALUE, "expected expression for map value");
    }
}

fn literal_atom(p: &mut Parser<'_>, node: SyntaxKind) -> CompletedMarker {
    let m = p.start();
    p.bump_any();
    m.complete(p, node)
}

/// TRUE/FALSE/NULL keywords are wrapped into a literal expression so the
/// AST sees them uniformly with the numeric/string literals above.
fn literal_keyword_atom(p: &mut Parser<'_>, node: SyntaxKind) -> CompletedMarker {
    let m = p.start();
    p.bump_any();
    m.complete(p, node)
}

/// Parse a list-predicate expression: `ANY|ALL|NONE|SINGLE(x IN xs [WHERE p])`.
///
/// Spec §19 row "List predicates". The returned `LIST_PREDICATE_EXPR`
/// preserves the discriminant keyword as its first child token so HIR
/// lowering can classify without a dedicated `SyntaxKind` per keyword.
/// Grammar identical shape for all four:
///
/// ```text
/// LIST_PREDICATE_EXPR
///   (ANY_KW | ALL_KW | NONE_KW | SINGLE_KW)
///   '('
///   NAME
///   IN_KW
///   <iterable Expr>
///   (WHERE_KW <predicate Expr>)?
///   ')'
/// ```
///
/// Recovery per AGENTS.md §10:
///   E0065 — missing `(` after the predicate keyword
///   E0066 — missing `IN`
///   E0067 — missing `)` to close the predicate
fn list_predicate(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(matches!(
        p.current(),
        SyntaxKind::ANY_KW | SyntaxKind::ALL_KW | SyntaxKind::NONE_KW | SyntaxKind::SINGLE_KW
    ));
    let m = p.start();
    // Discriminant keyword. Consumed as-is so it survives as the first
    // token child of the emitted node.
    p.bump_any();

    if !p.eat(SyntaxKind::L_PAREN) {
        p.error_code(
            sc::EXPECTED_LPAREN_LIST_PREDICATE,
            "expected `(` after ANY/ALL/NONE/SINGLE",
        );
    }

    // The binder name. Wrap it in a NAME node so AST / HIR can address it
    // uniformly (mirrors how `UNWIND ... AS v` and LIST_COMPREHENSION
    // emit a NAME child).
    let name_marker = p.start();
    if !(p.eat(SyntaxKind::IDENT) || p.eat(SyntaxKind::QUOTED_IDENT)) {
        p.error_code(
            sc::EXPECTED_IDENT,
            "expected binder identifier in list predicate",
        );
    }
    name_marker.complete(p, SyntaxKind::NAME);

    if !p.eat(SyntaxKind::IN_KW) {
        p.error_code(sc::EXPECTED_IN_LIST_PREDICATE, "expected `IN`");
    }

    // Iterable expression.
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(
            sc::EXPECTED_BINOP_RHS,
            "expected iterable expression in list predicate",
        );
    }

    // Optional `WHERE <expr>` predicate. Per openCypher semantics the
    // WHERE clause is optional: bare `ANY(x IN xs)` is true iff xs is
    // non-empty, etc. — we accept the form and leave the filter absent.
    if p.eat(SyntaxKind::WHERE_KW) && expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(
            sc::EXPECTED_WHERE_EXPR,
            "expected predicate expression after WHERE in list predicate",
        );
    }

    if !p.eat(SyntaxKind::R_PAREN) {
        p.error_code(
            sc::EXPECTED_RPAREN_LIST_PREDICATE,
            "expected `)` to close list predicate",
        );
    }

    m.complete(p, SyntaxKind::LIST_PREDICATE_EXPR)
}

/// Parse a `CASE` expression — generic or simple-when form (spec §19 row
/// "CASE"; cy-41u).
///
/// ```text
/// GenericCase = 'CASE' (WHEN Expr THEN Expr)+ ('ELSE' Expr)? 'END'
/// SimpleCase  = 'CASE' Expr (WHEN Expr THEN Expr)+ ('ELSE' Expr)? 'END'
/// ```
///
/// The two forms share an emitted shape: a `CASE_EXPR` node with an
/// optional scrutinee expression child (present iff a token other than
/// `WHEN` follows the leading `CASE`), one or more `CASE_WHEN_ARM`
/// children, and an optional trailing `CASE_ELSE_ARM`.
///
/// Recovery:
///   E0070 — missing `THEN` after `WHEN <value>`
///   E0071 — missing `END` at the close of the expression
fn case_expr(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::CASE_KW));
    let m = p.start();
    p.bump(SyntaxKind::CASE_KW);

    // Optional scrutinee — present iff the token following `CASE` is not
    // a `WHEN` / `ELSE` / `END`. `ELSE` / `END` here mean an empty CASE
    // (no arms), which is ill-formed but we accept for recovery — the
    // `WHEN` loop below will emit `E0007`-style missing-arm diagnostics
    // via the standard expr recovery path.
    if !matches!(
        p.current(),
        SyntaxKind::WHEN_KW | SyntaxKind::ELSE_KW | SyntaxKind::END_KW
    ) && expr_bp_depth(p, 0, depth + 1).is_none()
    {
        p.error_code(
            sc::EXPECTED_BINOP_RHS,
            "expected expression after `CASE` (simple-when scrutinee)",
        );
    }

    // One or more WHEN arms.
    while p.at(SyntaxKind::WHEN_KW) {
        let arm = p.start();
        p.bump(SyntaxKind::WHEN_KW);
        // `WHEN <value / predicate>` — required expression.
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_BINOP_RHS,
                "expected expression after `WHEN` in CASE arm",
            );
        }
        if !p.eat(SyntaxKind::THEN_KW) {
            p.error_code(sc::EXPECTED_THEN_CASE, "expected `THEN` in CASE arm");
        }
        // `THEN <result>` — required expression.
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_BINOP_RHS,
                "expected expression after `THEN` in CASE arm",
            );
        }
        arm.complete(p, SyntaxKind::CASE_WHEN_ARM);
    }

    // Optional ELSE arm.
    if p.at(SyntaxKind::ELSE_KW) {
        let else_arm = p.start();
        p.bump(SyntaxKind::ELSE_KW);
        if expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(
                sc::EXPECTED_BINOP_RHS,
                "expected expression after `ELSE` in CASE",
            );
        }
        else_arm.complete(p, SyntaxKind::CASE_ELSE_ARM);
    }

    // Closing `END` — required. Virtual-token insertion on miss so the
    // CST round-trips and downstream passes see a well-formed node.
    if !p.eat(SyntaxKind::END_KW) {
        p.error_code(
            sc::EXPECTED_END_CASE,
            "expected `END` to close CASE expression",
        );
    }

    m.complete(p, SyntaxKind::CASE_EXPR)
}

/// Parse a pattern-predicate `EXISTS ( <pattern> )` — spec §6.1 (sugar
/// desugared in HIR) / §19 row "Pattern predicates in expressions".
///
/// Enters on the `EXISTS` keyword with the two-token lookahead
/// `EXISTS ( (` already confirmed by [`atom`]. Consumes the keyword, the
/// outer `(`, a path pattern, and the closing `)`. Returns a
/// [`SyntaxKind::PATTERN_PREDICATE`] node so HIR lowering reuses the same
/// `Expr::PatternPredicate` path as a bare `(a)-->(b)` would if it were
/// reachable from expression position.
///
/// Recovery: E0072 on a missing `)` after the pattern. The outer opening
/// `(` is guaranteed by the dispatch lookahead, so no miss diagnostic is
/// needed there.
///
/// # Ambiguity note (spec §19 "Pattern predicates in expressions")
///
/// `EXISTS ( <expr> )` remains a function-call form and is handled by the
/// fallthrough branch in [`atom`]. Disambiguation is the two-token
/// lookahead `EXISTS ( (`: a pattern always begins with a parenthesised
/// node pattern, and `exists(expr)` never starts with `(`. This matches
/// the tree-sitter grammar's `exists_expression` vs.
/// `exists_function_invocation` split.
fn exists_pattern_predicate(p: &mut Parser<'_>) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::EXISTS_KW));
    let m = p.start();
    p.bump(SyntaxKind::EXISTS_KW);
    // Outer `(` — guaranteed by the atom dispatch lookahead.
    p.bump(SyntaxKind::L_PAREN);
    // Reuse the canonical pattern parser so we pick up every pattern
    // shape the grammar accepts in MATCH position (labels, rels with
    // types / directions, chained path elements).
    pattern::pattern(p);
    if !p.eat(SyntaxKind::R_PAREN) {
        p.error_code(
            sc::EXPECTED_RPAREN_EXISTS,
            "expected ')' to close EXISTS pattern predicate",
        );
    }
    m.complete(p, SyntaxKind::PATTERN_PREDICATE)
}

/// Reject the block-subquery form `EXISTS { ... }` with the
/// `exists_subquery` dialect-gate code E4017 (spec §9.3 / §19 row
/// "`EXISTS { <subquery> }`" / §20 D1).
///
/// The form is not part of either v1 dialect and will not be in v1. We
/// still parse it permissively enough to recover: consume the keyword,
/// skip the balanced braces, and emit an ERROR-marker so the rest of the
/// statement parses.
fn exists_block_deferred(p: &mut Parser<'_>) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::EXISTS_KW));
    debug_assert!(p.nth(1) == SyntaxKind::L_BRACE);
    let m = p.start();
    p.error_code(
        sc::EXISTS_BLOCK_DEFERRED,
        "EXISTS { ... } block subqueries are deferred per spec §19 / §20 D1",
    );
    // Consume the keyword and the brace-delimited body without
    // interpreting its contents. Track brace depth so nested maps
    // inside the body don't prematurely end the skip.
    p.bump(SyntaxKind::EXISTS_KW);
    p.bump(SyntaxKind::L_BRACE);
    let mut depth: u32 = 1;
    while depth > 0 && !p.at(SyntaxKind::EOF) {
        match p.current() {
            SyntaxKind::L_BRACE => {
                depth += 1;
                p.bump(SyntaxKind::L_BRACE);
            }
            SyntaxKind::R_BRACE => {
                depth -= 1;
                p.bump(SyntaxKind::R_BRACE);
            }
            _ => p.bump_any(),
        }
    }
    // Tag as ERROR so downstream passes (sema/plan) do not try to
    // interpret this as a valid expression. The primary diagnostic is
    // already on the CST.
    m.complete(p, SyntaxKind::ERROR)
}

/// Two-token lookahead disambiguator for an `L_PAREN` in expression
/// position: decides whether the `(` starts a bare pattern predicate
/// (`(a)-->(b)`, `(:Label)`, `(a {k: 1})`, …) or a parenthesised
/// expression (`(1 + 2)`, `(a.name)`, …). Spec §6.1 / §19 row
/// "Pattern predicates in expressions" (cy-7lf).
///
/// The parser is positioned *at* the opening paren; `nth(1)` is the
/// first token inside, `nth(2)` the second. Matches the classification
/// table below — every token combination maps to exactly one branch so
/// the caller never needs backtracking:
///
/// | `nth(1)` | `nth(2)` | Interpretation               |
/// | -------- | -------- | ---------------------------- |
/// | `)`      | —        | bare pattern (empty node)    |
/// | `:`      | —        | bare pattern (`(:Label)`)    |
/// | `{`      | —        | bare pattern (`({k: v})`)    |
/// | ident    | `:`      | bare pattern (`(a:Label)`)   |
/// | ident    | `,`      | bare pattern (comma in path) |
/// | ident    | `)`      | **ambiguous → pattern**      |
/// | ident    | `-`      | bare pattern (rel follows)   |
/// | ident    | `<-`     | bare pattern (rel follows)   |
/// | ident    | `{`      | bare pattern (inline props)  |
/// | anything else        | parenthesised expression     |
///
/// The `ident` + `)` ambiguity is resolved in favour of the pattern
/// form per the bead's spec; `(a)` read as a pattern predicate lowers to an
/// existential check on node `a`, while `(a)` read as an expression is
/// just `a` — they are not equivalent in type, but openCypher's bare
/// pattern form is the high-value reading (see TCK `expressions/pattern`
/// scenario [13] `MATCH (n) WHERE (n) RETURN n`). Users who meant the
/// expression form can disambiguate with `.prop`, an operator, or by
/// dropping the parens entirely.
fn at_bare_pattern_predicate(p: &mut Parser<'_>) -> bool {
    debug_assert!(p.at(SyntaxKind::L_PAREN));
    match p.nth(1) {
        // `()` — empty node pattern. Also `(:Label)`, `({k: v})` —
        // node pattern without a binder.
        SyntaxKind::R_PAREN | SyntaxKind::COLON | SyntaxKind::L_BRACE => true,
        // `(IDENT …)` — inspect the next token to decide.
        SyntaxKind::IDENT | SyntaxKind::QUOTED_IDENT => matches!(
            p.nth(2),
            // Label decoration → pattern.
            SyntaxKind::COLON
            // Inline property map → pattern.
            | SyntaxKind::L_BRACE
            // Ambiguous `(a)` → pattern per cy-7lf disambiguation rule.
            | SyntaxKind::R_PAREN
            // A trailing relationship always means a pattern: `(a)-[]->(b)`
            // opens with `MINUS` or `ARROW_L` after the first node pattern
            // closes, so seeing one inside means we're still mid-binder.
            // The `MINUS` / `ARROW_L` tokens here apply to a following rel
            // pattern after the closing `)` — but if they appear in the
            // *next* slot they never belong to an expression `(a - b)`:
            // expressions need whitespace-tolerant `a - b` which is `IDENT
            // MINUS IDENT`; so an `IDENT MINUS IDENT` shape stays an expr.
            // We only dispatch to pattern when we see a `,` which only
            // appears in comma-separated pattern lists.
            | SyntaxKind::COMMA
        ),
        // Everything else (literal, param, keyword, operator…) is an
        // expression.
        _ => false,
    }
}

/// Parse a bare pattern predicate in expression position: `(a)-->(b)`,
/// `(:Label)`, … — spec §6.1 / §19 row "Pattern predicates in
/// expressions" (cy-7lf).
///
/// Enters at the opening `(` of the first node pattern. Delegates the
/// whole path to [`pattern::pattern`], which walks `NodePattern
/// (RelPattern NodePattern)*` and leaves the cursor past the final
/// closing paren. The result is wrapped in a [`SyntaxKind::PATTERN_PREDICATE`]
/// node so HIR lowering reuses the same `Expr::PatternPredicate` path
/// as the `EXISTS(<pattern>)` form (cy-lve).
fn bare_pattern_predicate(p: &mut Parser<'_>) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_PAREN));
    let m = p.start();
    pattern::pattern(p);
    m.complete(p, SyntaxKind::PATTERN_PREDICATE)
}

fn paren_expr(p: &mut Parser<'_>, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_PAREN));
    let m = p.start();
    p.bump(SyntaxKind::L_PAREN);
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(
            sc::EXPECTED_EXPR_IN_PARENS,
            "expected expression inside parentheses",
        );
    }
    if !p.eat(SyntaxKind::R_PAREN) {
        // Virtual-token insertion per spec §4.3.
        p.error_code(sc::EXPECTED_RPAREN_EXPR, "expected ')' to close expression");
    }
    m.complete(p, SyntaxKind::PAREN_EXPR)
}

// --------------------------------------------------------------------------
// Prefix / unary binding
// --------------------------------------------------------------------------

fn prefix_bp(kind: SyntaxKind) -> Option<u8> {
    Some(match kind {
        // `NOT` at priority 4 — lower than comparison, higher than AND/XOR/OR.
        SyntaxKind::NOT_KW => 8,
        // Unary `-` / `+` at priority 9 — higher than multiplicative ops.
        SyntaxKind::MINUS | SyntaxKind::PLUS => 18,
        _ => return None,
    })
}

// --------------------------------------------------------------------------
// Infix binary operators
// --------------------------------------------------------------------------

/// Binding powers use doubled priorities (2 per table row) so left-assoc
/// can set `right_bp` = `left_bp` + 1 and right-assoc can set them equal —
/// the standard Pratt encoding.
#[derive(Copy, Clone, Debug)]
struct InfixOp {
    kind: InfixKind,
    left_bp: u8,
    right_bp: u8,
    /// `SyntaxKind` used for the resulting node.
    node: SyntaxKind,
}

#[derive(Copy, Clone, Debug)]
enum InfixKind {
    /// Single-token operator — just bump `tok`.
    Single(SyntaxKind),
    /// `STARTS WITH` / `ENDS WITH` — two keyword tokens.
    StartsWith,
    EndsWith,
}

fn infix_op(p: &mut Parser<'_>) -> Option<InfixOp> {
    let c = p.current();
    Some(match c {
        // Priority 1: OR
        SyntaxKind::OR_KW => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 2,
            right_bp: 3,
            node: SyntaxKind::BINARY_EXPR,
        },
        // Priority 2: XOR
        SyntaxKind::XOR_KW => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 4,
            right_bp: 5,
            node: SyntaxKind::BINARY_EXPR,
        },
        // Priority 3: AND
        SyntaxKind::AND_KW => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 6,
            right_bp: 7,
            node: SyntaxKind::BINARY_EXPR,
        },
        // Priority 5: comparison family (non-assoc — but implemented as
        // left-assoc with a spec-aligned diagnostic later; harmless for
        // well-formed input).
        SyntaxKind::EQ
        | SyntaxKind::NEQ
        | SyntaxKind::BANG_EQ
        | SyntaxKind::LT
        | SyntaxKind::LE
        | SyntaxKind::GT
        | SyntaxKind::GE => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::BINARY_EXPR,
        },
        SyntaxKind::REGEX_EQ => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::REGEX_MATCH_EXPR,
        },
        SyntaxKind::IN_KW => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::IN_EXPR,
        },
        SyntaxKind::STARTS_KW => InfixOp {
            kind: InfixKind::StartsWith,
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::STRING_OP_EXPR,
        },
        SyntaxKind::ENDS_KW => InfixOp {
            kind: InfixKind::EndsWith,
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::STRING_OP_EXPR,
        },
        SyntaxKind::CONTAINS_KW => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 10,
            right_bp: 11,
            node: SyntaxKind::STRING_OP_EXPR,
        },
        // Priority 6: additive
        SyntaxKind::PLUS | SyntaxKind::MINUS => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 12,
            right_bp: 13,
            node: SyntaxKind::BINARY_EXPR,
        },
        // Priority 7: multiplicative
        SyntaxKind::STAR | SyntaxKind::SLASH | SyntaxKind::PERCENT => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 14,
            right_bp: 15,
            node: SyntaxKind::BINARY_EXPR,
        },
        // Priority 8: power (right-assoc → right_bp == left_bp).
        SyntaxKind::CARET => InfixOp {
            kind: InfixKind::Single(c),
            left_bp: 16,
            right_bp: 16,
            node: SyntaxKind::BINARY_EXPR,
        },
        _ => return None,
    })
}

fn consume_infix_op(p: &mut Parser<'_>, kind: InfixKind) {
    match kind {
        InfixKind::Single(tok) => p.bump(tok),
        InfixKind::StartsWith => {
            p.bump(SyntaxKind::STARTS_KW);
            if !p.eat(SyntaxKind::WITH_KW) {
                p.error_code(sc::EXPECTED_WITH_AFTER_STARTS, "expected WITH after STARTS");
            }
        }
        InfixKind::EndsWith => {
            p.bump(SyntaxKind::ENDS_KW);
            if !p.eat(SyntaxKind::WITH_KW) {
                p.error_code(sc::EXPECTED_WITH_AFTER_ENDS, "expected WITH after ENDS");
            }
        }
    }
}

// --------------------------------------------------------------------------
// Postfix
// --------------------------------------------------------------------------

#[derive(Copy, Clone, Debug)]
struct PostfixOp {
    bp: u8,
    kind: PostfixKind,
}

#[derive(Copy, Clone, Debug)]
enum PostfixKind {
    /// `.ident` — property access.
    Dot,
    /// `[expr]` or `[i..j]` — list indexing / slicing. The helper
    /// [`index_or_slice_postfix`] disambiguates after the opening `[`
    /// (cy-7s6.1).
    Index,
    /// `(arg, arg, ...)` — function call. Only allowed when the lhs is
    /// an IDENT — the Pratt loop checks this via `postfix_op`.
    Call,
    /// `{ .p, key: v, .*, * }` — map projection over a subject expression.
    /// Spec §6.1 (desugar in HIR) / §19 row "Map projection". The trailer
    /// position is what distinguishes this from a standalone map literal
    /// `{ k: v }` (cy-01q).
    MapProjection,
    /// `IS NULL` / `IS NOT NULL`. `IS` is also handled as a binary op
    /// above because openCypher uses `IS NULL` with the lhs as operand —
    /// the infix path handles all well-formed cases.
    /// (Kept as a placeholder variant for future null-check recovery.)
    #[allow(dead_code)]
    IsNull,
}

fn postfix_op(p: &mut Parser<'_>) -> Option<PostfixOp> {
    let bp = 20; // higher than any infix left_bp.
    Some(match p.current() {
        SyntaxKind::DOT => PostfixOp {
            bp,
            kind: PostfixKind::Dot,
        },
        SyntaxKind::L_BRACK => PostfixOp {
            bp,
            kind: PostfixKind::Index,
        },
        SyntaxKind::L_PAREN => PostfixOp {
            bp,
            kind: PostfixKind::Call,
        },
        // `{` immediately following an atom expression is a map projection
        // trailer (cy-01q, spec §6.1 / §19). A standalone `{ k: v }` map
        // literal is parsed by the `atom` dispatch on `L_BRACE`; that path
        // never reaches the postfix loop because the literal *is* the lhs.
        // Conversely, once a lhs has been completed, an immediately-trailing
        // `{` always reads as projection — there is no other valid
        // expression continuation that begins with `{`.
        SyntaxKind::L_BRACE => PostfixOp {
            bp,
            kind: PostfixKind::MapProjection,
        },
        _ => return None,
    })
}

fn apply_postfix(
    p: &mut Parser<'_>,
    lhs: CompletedMarker,
    op: PostfixOp,
    depth: u32,
) -> CompletedMarker {
    match op.kind {
        PostfixKind::Dot => {
            let m = lhs.precede(p);
            p.bump(SyntaxKind::DOT);
            if !(p.eat(SyntaxKind::IDENT) || p.eat(SyntaxKind::QUOTED_IDENT)) {
                p.error_code(
                    sc::EXPECTED_PROP_KEY_AFTER_DOT,
                    "expected property key after '.'",
                );
            }
            m.complete(p, SyntaxKind::PROP_ACCESS_EXPR)
        }
        PostfixKind::Index => index_or_slice_postfix(p, lhs, depth),
        PostfixKind::Call => call_postfix(p, lhs, depth),
        PostfixKind::MapProjection => map_projection_postfix(p, lhs, depth),
        PostfixKind::IsNull => {
            let m = lhs.precede(p);
            // Unused currently; reserved for non-infix IS paths.
            m.complete(p, SyntaxKind::IS_NULL_EXPR)
        }
    }
}

fn call_postfix(p: &mut Parser<'_>, lhs: CompletedMarker, depth: u32) -> CompletedMarker {
    let m = lhs.precede(p);
    p.bump(SyntaxKind::L_PAREN);
    // Optional inline `DISTINCT` (aggregation form).
    p.eat(SyntaxKind::DISTINCT_KW);
    // Arg list.
    if !p.at(SyntaxKind::R_PAREN) {
        let args = p.start();
        call_arg(p, depth);
        while p.at(SyntaxKind::COMMA) {
            p.bump(SyntaxKind::COMMA);
            call_arg(p, depth);
        }
        args.complete(p, SyntaxKind::ARG_LIST);
    }
    if !p.eat(SyntaxKind::R_PAREN) {
        p.error_code(
            sc::EXPECTED_RPAREN_CALL,
            "expected ')' to close function call",
        );
    }
    m.complete(p, SyntaxKind::FUNCTION_CALL)
}

fn call_arg(p: &mut Parser<'_>, depth: u32) {
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(sc::EXPECTED_CALL_ARG, "expected function argument");
    }
}

/// Parse a map-projection trailer: `<lhs> { item (',' item)* }` where each
/// item is one of:
///
/// - `.NAME`          — property selector (key=name, value=lhs.name)
/// - `IDENT ':' Expr` — literal item (key=ident, value=Expr)
/// - `.*`             — all-properties spread of the subject
/// - `*`              — all-bound-vars spread (rare; openCypher allows it)
///
/// Spec §6.1 (sugar; desugared in HIR) / §19 row "Map projection" (cy-01q).
///
/// Each item is wrapped in a `MAP_PROJECTION_ITEM` node so HIR lowering can
/// classify the four kinds by inspecting the leading token (`.` + IDENT,
/// `.` + `*`, IDENT + `:`, or bare `*`). The completed wrapper carries the
/// lhs as its first `Expr` child via the `lhs.precede(p)` rebase, mirroring
/// how every other postfix shape (property access, index, call) wraps its
/// receiver.
fn map_projection_postfix(p: &mut Parser<'_>, lhs: CompletedMarker, depth: u32) -> CompletedMarker {
    debug_assert!(p.at(SyntaxKind::L_BRACE));
    let m = lhs.precede(p);
    p.bump(SyntaxKind::L_BRACE);

    if !p.at(SyntaxKind::R_BRACE) {
        map_projection_item(p, depth);
        while p.at(SyntaxKind::COMMA) {
            p.bump(SyntaxKind::COMMA);
            if p.at(SyntaxKind::R_BRACE) {
                break;
            }
            map_projection_item(p, depth);
        }
    }

    if !p.eat(SyntaxKind::R_BRACE) {
        p.error_code(
            sc::EXPECTED_RBRACE_MAP_PROJECTION,
            "expected '}' to close map projection",
        );
    }
    m.complete(p, SyntaxKind::MAP_PROJECTION)
}

/// Parse one item inside a map projection. Each kind emits its own marker
/// so the resulting CST has uniform `MAP_PROJECTION_ITEM` children — HIR
/// lowering inspects the first significant token of each item to classify.
fn map_projection_item(p: &mut Parser<'_>, depth: u32) {
    let m = p.start();
    match p.current() {
        // `.*` (all-properties spread) or `.NAME` (property selector).
        SyntaxKind::DOT => {
            p.bump(SyntaxKind::DOT);
            if p.at(SyntaxKind::STAR) {
                p.bump(SyntaxKind::STAR);
            } else if !(p.eat(SyntaxKind::IDENT) || p.eat(SyntaxKind::QUOTED_IDENT)) {
                p.error_code(
                    sc::EXPECTED_PROP_OR_STAR_AFTER_DOT_IN_PROJECTION,
                    "expected property name or '*' after '.' in map projection item",
                );
            }
        }
        // `*` (all-bound-vars spread). Rare openCypher form; lowered as a
        // scope-wide spread by HIR.
        SyntaxKind::STAR => {
            p.bump(SyntaxKind::STAR);
        }
        // `IDENT ':' Expr` — literal item, same shape as a map-literal entry.
        SyntaxKind::IDENT | SyntaxKind::QUOTED_IDENT => {
            p.bump_any();
            if !p.eat(SyntaxKind::COLON) {
                p.error_code(
                    sc::EXPECTED_COLON_MAP_PROJECTION,
                    "expected ':' in map projection literal item",
                );
            }
            if expr_bp_depth(p, 0, depth + 1).is_none() {
                p.error_code(
                    sc::EXPECTED_VALUE_MAP_PROJECTION,
                    "expected expression for map projection value",
                );
            }
        }
        _ => {
            p.error_code(
                sc::EXPECTED_MAP_PROJECTION_ITEM,
                "expected `.name`, `key: expr`, `.*`, or `*` in map projection",
            );
            // Token-bump to make recovery progress; the outer loop will
            // either find a `,` or `}` and continue.
            if !p.at(SyntaxKind::R_BRACE) && !p.at(SyntaxKind::COMMA) {
                p.bump_any();
            }
        }
    }
    m.complete(p, SyntaxKind::MAP_PROJECTION_ITEM);
}

/// Parse the `[...]` postfix form and classify it as either
/// [`SyntaxKind::INDEX_EXPR`] (`xs[0]`) or [`SyntaxKind::SLICE_EXPR`]
/// (`xs[i..j]`, `xs[..j]`, `xs[i..]`). Both forms can elide inner
/// expressions: a slice with both bounds elided is `xs[..]`.
///
/// Recovery: an unclosed bracket yields diagnostic
/// [`sc::UNCLOSED_INDEX_BRACKET`] (E0064) — distinct from the legacy
/// `SUBSCRIPT_EXPR` path's E0033 so tooling can tell the two apart.
///
/// Grammar:
/// ```text
/// IndexExpr = Expr '[' Expr ']'
/// SliceExpr = Expr '[' Expr? '..' Expr? ']'
/// ```
///
/// cy-7s6.1 (spec §19 row "List indexing / slicing").
fn index_or_slice_postfix(p: &mut Parser<'_>, lhs: CompletedMarker, depth: u32) -> CompletedMarker {
    let m = lhs.precede(p);
    p.bump(SyntaxKind::L_BRACK);

    // Start marker: we don't yet know if this is an INDEX_EXPR or SLICE_EXPR.
    // Decide based on whether:
    //   - the first token is `..` (slice with elided start), or
    //   - after parsing an expression we see `..` (slice form), or
    //   - after parsing an expression we see `]` (index form).

    // Elided-start form: `[..j]` or `[..]`.
    if p.at(SyntaxKind::DOT_DOT) {
        p.bump(SyntaxKind::DOT_DOT);
        // Optional end expression.
        if !p.at(SyntaxKind::R_BRACK) && expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(sc::EXPECTED_INDEX_EXPR, "expected slice end expression");
        }
        if !p.eat(SyntaxKind::R_BRACK) {
            p.error_code(
                sc::UNCLOSED_INDEX_BRACKET,
                "expected ']' to close indexing bracket",
            );
        }
        return m.complete(p, SyntaxKind::SLICE_EXPR);
    }

    // Non-elided: parse the first expression.
    if expr_bp_depth(p, 0, depth + 1).is_none() {
        p.error_code(sc::EXPECTED_INDEX_EXPR, "expected index expression");
    }

    if p.at(SyntaxKind::DOT_DOT) {
        // Slice form with start expression: `[i..]` or `[i..j]`.
        p.bump(SyntaxKind::DOT_DOT);
        if !p.at(SyntaxKind::R_BRACK) && expr_bp_depth(p, 0, depth + 1).is_none() {
            p.error_code(sc::EXPECTED_INDEX_EXPR, "expected slice end expression");
        }
        if !p.eat(SyntaxKind::R_BRACK) {
            p.error_code(
                sc::UNCLOSED_INDEX_BRACKET,
                "expected ']' to close indexing bracket",
            );
        }
        m.complete(p, SyntaxKind::SLICE_EXPR)
    } else {
        // Plain index form: `[i]`.
        if !p.eat(SyntaxKind::R_BRACK) {
            p.error_code(
                sc::UNCLOSED_INDEX_BRACKET,
                "expected ']' to close indexing bracket",
            );
        }
        m.complete(p, SyntaxKind::INDEX_EXPR)
    }
}

// --------------------------------------------------------------------------
// Unused helpers (kept for grammar extensibility)
// --------------------------------------------------------------------------

#[allow(dead_code)]
fn _recovery_anchor_placeholder(_: &mut Parser<'_>, _: TokenSet, _: Marker) {
    // Present so future per-production recovery tables (cy-2vh) can be
    // threaded without re-plumbing every call site.
}