relate-parser 1.0.1

Cypher lexer, parser, and AST for the Relate graph database
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
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
use super::*;

/// `parse_reduce_head`'s result: the `( acc = init, var IN list | expr`
/// head shared by `reduce` and `allReduce`.
struct ReduceHead {
    accumulator: SmallName,
    init_expr: Expr,
    variable: SmallName,
    list_expr: Expr,
    expression: Expr,
}

impl<'a> Parser<'a> {
    // ---- Expression parsing (precedence climbing) ----

    pub(super) fn parse_expression(&mut self) -> ParseResult<Expr> {
        // ADR-0257: every nested expression descends through here, so this
        // single counter bounds all expression recursion (LABS-69).
        self.with_expr_depth(Self::parse_or)
    }

    /// The `<expr> (, <expr>)*` production shared by `SHOW SETTINGS`
    /// `<names>`, `SHOW TRANSACTIONS` `<id-list>` and `TERMINATE
    /// TRANSACTIONS` `<id-list>` (CIP-68/CIP-84). Parses the first
    /// expression itself; the caller checks
    /// `peek_starts_show_filter_expr` first when the list is optional.
    pub(super) fn parse_comma_separated_exprs(&mut self) -> ParseResult<Vec<Expr>> {
        let mut items = vec![self.parse_expression()?];
        while self.peek_type() == TokenType::Comma {
            self.next_token();
            items.push(self.parse_expression()?);
        }
        Ok(items)
    }

    pub(super) fn parse_or(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_xor()?;
        while self.peek_type() == TokenType::OR {
            self.next_token();
            let right = self.parse_xor()?;
            left = Expr::Binary(Box::new(BinaryExpr {
                left,
                op: OR,
                right,
            }));
        }
        Ok(left)
    }

    pub(super) fn parse_xor(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_and()?;
        while self.peek_type() == TokenType::XOR {
            self.next_token();
            let right = self.parse_and()?;
            left = Expr::Binary(Box::new(BinaryExpr {
                left,
                op: XOR,
                right,
            }));
        }
        Ok(left)
    }

    pub(super) fn parse_and(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_not()?;
        while self.peek_type() == TokenType::AND {
            self.next_token();
            let right = self.parse_not()?;
            left = Expr::Binary(Box::new(BinaryExpr {
                left,
                op: AND,
                right,
            }));
        }
        Ok(left)
    }

    pub(super) fn parse_not(&mut self) -> ParseResult<Expr> {
        if self.peek_type() == TokenType::NOT {
            self.next_token();
            // ADR-0257: `NOT` chains recurse here directly, bypassing
            // `parse_expression`, so each step must count separately
            // (LABS-69).
            let expr = self.with_expr_depth(|p| p.parse_not())?;
            return Ok(Expr::Unary(Box::new(UnaryExpr { op: NOT, expr })));
        }
        self.parse_comparison()
    }

    pub(super) fn parse_comparison(&mut self) -> ParseResult<Expr> {
        let left = self.parse_string_null_check()?;

        let op = comparison_op(self.peek_type());
        if op.is_none() {
            return Ok(left);
        }
        let op = op.unwrap();
        self.next_token();
        let mut right = self.parse_string_null_check()?;
        let mut result = Expr::Comparison(Box::new(ComparisonExpr {
            left,
            op,
            right: right.clone(),
        }));

        // Chained comparisons
        loop {
            let next_op = comparison_op(self.peek_type());
            if next_op.is_none() {
                break;
            }
            let next_op = next_op.unwrap();
            self.next_token();
            let next_right = self.parse_string_null_check()?;
            result = Expr::Binary(Box::new(BinaryExpr {
                left: result,
                op: AND,
                right: Expr::Comparison(Box::new(ComparisonExpr {
                    left: right,
                    op: next_op,
                    right: next_right.clone(),
                })),
            }));
            right = next_right;
        }

        Ok(result)
    }

    /// Parses `ComparisonExpression6`: an `AddOrSubtractExpression` followed
    /// by *at most one* of `IN`/`STARTS WITH`/`ENDS WITH`/`CONTAINS`/`IS
    /// [NOT] NULL`/`IS [NOT] [<normal form>] NORMALIZED`/the CIP-87 type
    /// predicate (`IS [NOT] ::`, `IS [NOT] TYPED`, bare `::`). These
    /// alternatives do not chain: per CIP-87's "Precedence of Type
    /// Predicate Expression" section, combining any two of them without
    /// parentheses (e.g. `"ab" STARTS WITH "a" IS :: BOOLEAN`, or two type
    /// predicates back to back) is a compile-time syntax error, so this is
    /// a single optional suffix rather than a loop.
    pub(super) fn parse_string_null_check(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_add_sub()?;
        let mut consumed_suffix = true;
        match self.peek_type() {
            TokenType::IN => {
                self.next_token();
                let right = self.parse_add_sub()?;
                left = Expr::In(Box::new(InExpr {
                    expr: left,
                    list: right,
                }));
            }
            TokenType::STARTS => {
                self.next_token();
                self.expect(TokenType::WITH)?;
                let right = self.parse_add_sub()?;
                left = Expr::StringMatch(Box::new(StringMatchExpr {
                    left,
                    op: STARTS_WITH,
                    right,
                }));
            }
            TokenType::ENDS => {
                self.next_token();
                self.expect(TokenType::WITH)?;
                let right = self.parse_add_sub()?;
                left = Expr::StringMatch(Box::new(StringMatchExpr {
                    left,
                    op: ENDS_WITH,
                    right,
                }));
            }
            TokenType::CONTAINS => {
                self.next_token();
                let right = self.parse_add_sub()?;
                left = Expr::StringMatch(Box::new(StringMatchExpr {
                    left,
                    op: CONTAINS,
                    right,
                }));
            }
            _ => {
                consumed_suffix = false;
            }
        }

        // Per CIP-87's precedence rules, a string/list predicate and an
        // IS-suffix (null/type/normalized check) do not combine without
        // parens: only try the IS-suffix if the above didn't already fire.
        if consumed_suffix {
            return Ok(left);
        }

        match self.peek_type() {
            TokenType::IS => {
                self.next_token();
                let negated = if self.peek_type() == TokenType::NOT {
                    self.next_token();
                    true
                } else {
                    false
                };

                if let Some(op) = self.peek_chronological_op() {
                    // a IS [NOT] BEFORE | AFTER | SAME INSTANT | SAME
                    // REPRESENTATION b  (Cypher 25 chronological
                    // comparison; the four words are contextual
                    // identifiers, not reserved).
                    self.consume_chronological_op(op);
                    let right = self.parse_add_sub()?;
                    left = Expr::ChronologicalCompare(Box::new(ChronologicalCompareExpr {
                        left,
                        op,
                        right,
                        negated,
                    }));
                } else if self.peek_type() == TokenType::DoubleColon {
                    // x IS [NOT] :: <value type>  (CIP-87 type predicate)
                    self.next_token();
                    let type_expr = self.parse_value_type()?;
                    left = Expr::IsType(Box::new(IsTypeExpr {
                        expr: left,
                        type_expr,
                        negated,
                    }));
                } else if self.peek_is_typed_keyword() {
                    // x IS [NOT] TYPED <value type>  (CIP-87 type predicate)
                    self.next_token();
                    let type_expr = self.parse_value_type()?;
                    left = Expr::IsType(Box::new(IsTypeExpr {
                        expr: left,
                        type_expr,
                        negated,
                    }));
                } else if self.peek_is_normal_form_or_normalized() {
                    // x IS [NOT] [<normal form>] NORMALIZED  (CIP-133)
                    let form = self.try_consume_normal_form_keyword();
                    self.expect_keyword_ident("NORMALIZED")?;
                    left = Expr::IsNormalized(Box::new(IsNormalizedExpr {
                        expr: left,
                        form,
                        negated,
                    }));
                } else if self.peek_is_labeled_keyword() {
                    // x IS [NOT] LABELED <label-expr>  (CIP-249)
                    self.next_token();
                    let label_expr = self.parse_label_expr_body(true, false)?.expr;
                    left = Expr::HasLabel(Box::new(HasLabelExpr {
                        expr: left,
                        label_expr,
                        negated,
                        strict: true,
                    }));
                } else if self.peek_type() == TokenType::NULL {
                    // x IS [NOT] NULL
                    self.next_token();
                    left = Expr::IsNull(Box::new(IsNullExpr {
                        expr: left,
                        negated,
                    }));
                } else if self.peek_can_start_label_expr() {
                    // x IS <label-expr>  (CIP-14, non-negated, interchangeable
                    // with `:`) or x IS NOT <label-expr>  (CIP-249 shorthand
                    // for IS NOT LABELED <label-expr>).
                    let label_expr = self.parse_label_expr_body(true, false)?.expr;
                    left = Expr::HasLabel(Box::new(HasLabelExpr {
                        expr: left,
                        label_expr,
                        negated,
                        strict: negated,
                    }));
                } else {
                    self.expect(TokenType::NULL)?;
                    left = Expr::IsNull(Box::new(IsNullExpr {
                        expr: left,
                        negated,
                    }));
                }
            }
            TokenType::DoubleColon => {
                // x :: <value type>  (CIP-87 bare shorthand for IS ::)
                self.next_token();
                let type_expr = self.parse_value_type()?;
                left = Expr::IsType(Box::new(IsTypeExpr {
                    expr: left,
                    type_expr,
                    negated: false,
                }));
            }
            TokenType::Colon => {
                // x:<label-expr>  (CIP-14, colon spelling of the label
                // predicate, interchangeable with `IS <label-expr>`).
                // CIP-190 moves this from `<postfix operator>` (tighter than
                // `+`) to here, `<advanced comparison predicate part 2>`
                // (looser than `+`): `[1,'abc',3] + n:A` now parses as
                // `([1,'abc',3] + n):A`, not `[1,'abc',3] + (n:A)`
                // (label-expression-precedence.feature [1]/[3]). Unlike the
                // pre-CIP-190 postfix version, `left` here is a whole
                // `<add or subtract expression>`, not necessarily a bare
                // variable -- but that's fine: SET/REMOVE's own `n:Label`
                // grammar is parsed by its own bespoke logic before ever
                // reaching general expression parsing, and
                // `parse_general_property_target` (SET's complex-target
                // fallback) calls `parse_postfix` directly, which no longer
                // handles `:` at all, so there's still no conflict.
                let label_expr = self.parse_label_spec(true)?.expr;
                left = Expr::HasLabel(Box::new(HasLabelExpr {
                    expr: left,
                    label_expr,
                    negated: false,
                    strict: false,
                }));
            }
            _ => {}
        }

        Ok(left)
    }

    /// True if the current token is the contextual `TYPED` keyword (like
    /// `NORMALIZED`, not a reserved word in the lexer).
    pub(super) fn peek_is_typed_keyword(&self) -> bool {
        let tok = self.peek();
        tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case("TYPED")
    }

    /// The chronological comparison operator starting at the current token
    /// (Cypher 25): `BEFORE`, `AFTER`, or the two-token `SAME INSTANT` /
    /// `SAME REPRESENTATION`. `None` when the current token starts none of
    /// them -- a lone `SAME` (a variable so spelled) is not an operator
    /// without its second word.
    pub(super) fn peek_chronological_op(&self) -> Option<ChronologicalOp> {
        if self.peek_is_ident("BEFORE") {
            Some(ChronologicalOp::Before)
        } else if self.peek_is_ident("AFTER") {
            Some(ChronologicalOp::After)
        } else if self.peek_is_ident("SAME") {
            if self.peek_at_is_ident(1, "INSTANT") {
                Some(ChronologicalOp::SameInstant)
            } else if self.peek_at_is_ident(1, "REPRESENTATION") {
                Some(ChronologicalOp::SameRepresentation)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Consume the one or two contextual identifier words of the
    /// chronological operator `op` ([`Self::peek_chronological_op`]
    /// reported it).
    pub(super) fn consume_chronological_op(&mut self, op: ChronologicalOp) {
        self.next_token();
        if matches!(
            op,
            ChronologicalOp::SameInstant | ChronologicalOp::SameRepresentation
        ) {
            self.next_token();
        }
    }

    /// Returns the canonical uppercase form name ("NFC"/"NFD"/"NFKC"/"NFKD")
    /// if the current token is one of the normal-form keywords, else None.
    pub(super) fn peek_normal_form_keyword(&self) -> Option<String> {
        let tok = self.peek();
        if tok.ty == TokenType::Identifier {
            let upper = tok.literal.to_ascii_uppercase();
            if matches!(upper.as_str(), "NFC" | "NFD" | "NFKC" | "NFKD") {
                return Some(upper);
            }
        }
        None
    }

    /// True if the current token starts a `[<normal form>] NORMALIZED` tail
    /// (used to distinguish `IS NORMALIZED`/`IS <form> NORMALIZED` from `IS NULL`).
    pub(super) fn peek_is_normal_form_or_normalized(&self) -> bool {
        if self.peek_normal_form_keyword().is_some() {
            return true;
        }
        let tok = self.peek();
        tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case("NORMALIZED")
    }

    /// Consumes and returns a normal-form keyword if present; otherwise leaves
    /// the token stream untouched and returns None.
    pub(super) fn try_consume_normal_form_keyword(&mut self) -> Option<String> {
        let form = self.peek_normal_form_keyword();
        if form.is_some() {
            self.next_token();
        }
        form
    }

    /// Expects the current token to be a case-insensitive identifier keyword
    /// -- one that is not a reserved word in the lexer, e.g. `NORMALIZED`,
    /// or a word of the multi-word DDL/SHOW forms (`CURRENT GRAPH TYPE`,
    /// `DEFAULT DATABASE`, `CURRENT USER`) where only one spelling is valid
    /// at this position. `keyword` is written uppercase, as the error shows
    /// it.
    pub(super) fn expect_keyword_ident(&mut self, keyword: &str) -> ParseResult<()> {
        let tok = self.peek().clone();
        if tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case(keyword) {
            self.next_token();
            Ok(())
        } else {
            Err(self.error_at_token(&tok, format!("expected {}, got {:?}", keyword, tok.literal)))
        }
    }

    /// The consume-and-validate gate for a command's kind word: the next
    /// token must be the `singular` keyword token itself, or an identifier
    /// spelled `singular_ident` or `plural` (CIP-68's singular/plural KIND
    /// acceptance). Serves the SHOW family's kind word (`FUNCTION(S)`,
    /// `INDEX(ES)`, `CONSTRAINT(S)`, ...) and TERMINATE's `TRANSACTION(S)`.
    /// Pass `TokenType::Identifier` as `singular` when the word has no
    /// reserved token of its own (`FUNCTION(S)`, `DEFINED`) -- the
    /// identifier-spelling check is then the whole gate. Anything else gets
    /// an `expected <expected>, got <literal>` error.
    pub(super) fn expect_kind_word(
        &mut self,
        singular: TokenType,
        singular_ident: &str,
        plural: Option<&str>,
        expected: &str,
    ) -> ParseResult<()> {
        let tok = self.next_token();
        let is_singular_token = singular != TokenType::Identifier && tok.ty == singular;
        let is_ident_spelling = tok.ty == TokenType::Identifier
            && (tok.literal.eq_ignore_ascii_case(singular_ident)
                || plural.is_some_and(|p| tok.literal.eq_ignore_ascii_case(p)));
        if !(is_singular_token || is_ident_spelling) {
            return Err(
                self.error_at_token(&tok, format!("expected {expected}, got {:?}", tok.literal))
            );
        }
        Ok(())
    }

    /// Parses `normalize(input)` or `normalize(input, normalForm)`. The
    /// second argument (if present) must be a bare normal-form keyword
    /// (NFC/NFD/NFKC/NFKD) — a quoted string, parameter, or any other
    /// expression there is a compile-time error (CIP-132), so this bypasses
    /// the generic argument-list parser.
    pub(super) fn parse_normalize_call(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume (
        if self.peek_type() == TokenType::RightParen {
            return Err(self.error("normalize() requires at least 1 argument"));
        }
        let input = self.parse_expression()?;
        let mut args = vec![input];
        if self.peek_type() == TokenType::Comma {
            self.next_token();
            let form = self.try_consume_normal_form_keyword().ok_or_else(|| {
                let tok = self.peek().clone();
                self.error_at_token(
                    &tok,
                    format!(
                        "invalid normal form: expected NFC, NFD, NFKC, or NFKD, got {:?}",
                        tok.literal
                    ),
                )
            })?;
            args.push(Expr::Literal(LiteralValue::String(form)));
            if self.peek_type() == TokenType::Comma {
                return Err(self.error("normalize() accepts at most 2 arguments"));
            }
        }
        self.expect(TokenType::RightParen)?;
        Ok(Expr::FunctionCall(FunctionCallExpr {
            name: SmallName::from_name("normalize"),
            args,
            distinct: false,
        }))
    }

    /// Parses the GQL TRIM special form (CIP-149):
    /// `trim([[LEADING|TRAILING|BOTH] [trimCharacterString] FROM] input)`,
    /// plus its comma spelling
    /// `trim(trimSpecification [, trimCharacterString], input)`, whose
    /// specification is an ordinary expression and so selects the direction
    /// at run time (the internal `trim_spec` call).
    /// `LEADING`/`TRAILING`/`BOTH` are not reserved keywords elsewhere, so
    /// they lex as plain identifiers and are recognized here by their
    /// literal spelling. The trim specification and character string
    /// selects which of the three underlying dispatch names ("trim" for
    /// BOTH/default, "trim_leading", "trim_trailing") the call compiles to;
    /// an omitted trim character string is distinguished from an explicit
    /// one by arg count (1 vs 2), letting the evaluator apply the correct
    /// default-whitespace vs. explicit-character-string semantics.
    ///
    /// Complexity: a cheap token-level gate (`trim_args_have_top_level_from`)
    /// decides up front whether a `FROM`-bearing spec form is even possible;
    /// without it the plain `trim(input)` form parses in a single pass. When
    /// the gate passes, the candidate trim-character-string expression is
    /// parsed exactly once and *committed to* — the old code restored the
    /// position and re-parsed the same tokens whenever no `FROM` followed,
    /// which made nested `trim(trim(...))` cost T(k) = 2·T(k-1) (k=28 took
    /// ~80 s). The only remaining backtrack is the error-only path where a
    /// leading BOTH/LEADING/TRAILING identifier was tentatively consumed as
    /// `spec` but turns out to be an ordinary variable (e.g. `trim(both)`
    /// inside a larger expression containing a top-level `FROM`).
    pub(super) fn parse_trim_call(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume (

        // The `[spec] [chars] FROM input` forms all require a `FROM` keyword
        // at this trim call's own paren depth. If none exists this is
        // necessarily the plain `trim(input)` form — parse it directly with
        // no speculation (this is what keeps deeply nested trim() linear).
        if !self.trim_args_have_top_level_from() {
            let first = self.parse_expression()?;
            if self.peek_type() != TokenType::Comma {
                self.expect(TokenType::RightParen)?;
                return Ok(Self::build_trim_call(None, vec![first]));
            }
            self.next_token(); // consume ,
            let second = self.parse_expression()?;
            let mut args = vec![first, second];
            if self.peek_type() == TokenType::Comma {
                self.next_token();
                args.push(self.parse_expression()?);
            }
            self.expect(TokenType::RightParen)?;
            return Ok(Self::build_trim_spec_call(args));
        }

        let start = self.save_pos();

        let mut spec: Option<&'static str> = None;
        let peek = self.peek().clone();
        if peek.ty == TokenType::Identifier {
            spec = match peek.literal.to_ascii_uppercase().as_str() {
                "BOTH" => Some("BOTH"),
                "LEADING" => Some("LEADING"),
                "TRAILING" => Some("TRAILING"),
                _ => None,
            };
            if spec.is_some() {
                self.next_token();
            }
        }

        // `[spec] FROM input` — no trim character string given.
        if self.peek_type() == TokenType::FROM {
            self.next_token(); // consume FROM
            let input = self.parse_expression()?;
            self.expect(TokenType::RightParen)?;
            return Ok(Self::build_trim_call(spec, vec![input]));
        }

        // `[spec] trimCharacterString FROM input` — or the plain form.
        match self.parse_expression() {
            Ok(chars_expr) if self.peek_type() == TokenType::FROM => {
                self.next_token(); // consume FROM
                let input = self.parse_expression()?;
                self.expect(TokenType::RightParen)?;
                Ok(Self::build_trim_call(spec, vec![input, chars_expr]))
            }
            Ok(chars_expr) if spec.is_none() => {
                // No spec word was consumed, so the already-parsed expression
                // *is* the plain trim(input) argument: a re-parse from
                // `start` would see the identical token stream, so reuse the
                // result instead of backtracking.
                self.expect(TokenType::RightParen)?;
                Ok(Self::build_trim_call(None, vec![chars_expr]))
            }
            Err(e) if spec.is_none() => {
                // Same reasoning: with nothing consumed since `start`, a
                // re-parse would fail identically — propagate directly.
                Err(e)
            }
            Ok(_) | Err(_) => {
                // A spec word (BOTH/LEADING/TRAILING) was tentatively
                // consumed but the spec forms didn't pan out: the word is an
                // ordinary variable (e.g. `trim(both)`), so backtrack and
                // parse the plain single-argument form including it. Only
                // reachable on invalid input — valid plain trims have no
                // top-level FROM and never enter the gated block — so this
                // re-parse is not on any well-formed hot path.
                self.restore_pos(start);
                let input = self.parse_expression()?;
                self.expect(TokenType::RightParen)?;
                Ok(Self::build_trim_call(None, vec![input]))
            }
        }
    }

    /// Lookahead from `self.pos` without consuming tokens: true when
    /// `target` appears at depth 0 before the closer that ends the
    /// construct opened just before `self.pos` (the caller has already
    /// consumed the opener). Only the bracket kinds in `brackets` count
    /// toward the depth, so a paren-only scan (inside a call's argument
    /// list) and an all-bracket scan (inside a comprehension brace, whose
    /// source expression can nest brackets and parens) are explicit
    /// per-site choices. The one scan behind
    /// [`Parser::trim_args_have_top_level_from`],
    /// [`Parser::pipe_before_closing_paren`], and
    /// [`Parser::has_pipe_before_matching_brace`].
    fn top_level_token_before_matching_close(
        &self,
        target: TokenType,
        brackets: BracketSet,
    ) -> bool {
        let mut depth = 0usize;
        let mut pos = self.pos;
        while pos < self.tokens.len() {
            let ty = self.tokens[pos].ty;
            if brackets.opens(ty) {
                depth += 1;
            } else if brackets.closes(ty) {
                if depth == 0 {
                    return false; // the construct's own closer
                }
                depth -= 1;
            } else if ty == TokenType::EOF {
                return false;
            } else if ty == target && depth == 0 {
                return true;
            }
            pos += 1;
        }
        false
    }

    /// Returns true if a `FROM` keyword token appears at this trim call's own
    /// paren depth before its closing `)` — i.e. whether the GQL
    /// `[spec] [chars] FROM input` forms are possible at all. Pure lookahead
    /// over the token stream (O(remaining tokens)); consumes nothing. A
    /// `FROM` nested inside a parenthesized sub-expression does not count;
    /// one inside brackets/braces at paren depth 0 may produce a harmless
    /// false positive (the caller then falls back to the speculative path,
    /// which behaves exactly as before) — never a false negative, since every
    /// real spec-form `FROM` sits at paren depth 0.
    pub(super) fn trim_args_have_top_level_from(&self) -> bool {
        self.top_level_token_before_matching_close(TokenType::FROM, BracketSet::Parens)
    }

    /// Parses `PROPERTY_EXISTS(<element variable reference>, <property name>)`
    /// (CIP-247). The GQL grammar restricts this to exactly two arguments: the
    /// first must be a variable (checked here, not a literal or compound
    /// expression), and the second is a bare property-name identifier — a
    /// distinct grammar slot, not an ordinary comma-separated expression, so a
    /// variable appearing there names the *literal* property (matching
    /// observed Neo4j behaviour) rather than being evaluated, and compound
    /// expressions (`a + b`, `toString(x)`) are rejected at parse time.
    /// Compiles down to a plain `property_exists(var, "propName")` call;
    /// evaluation lives in the engine (a generic property-access rewrite
    /// would wrongly accept maps, which this function must reject).
    pub(super) fn parse_property_exists_call(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume (
        let first = self.parse_expression()?;
        let var_name = match &first {
            Expr::Variable(v) => v.clone(),
            _ => {
                return Err(self.error(
                    "PROPERTY_EXISTS() first argument must be a variable referencing a node or relationship",
                ))
            }
        };
        self.expect(TokenType::Comma)?;
        let prop_tok = self.peek().clone();
        if !prop_tok.ty.is_ident_like() {
            return Err(self.error_at_token(
                &prop_tok,
                "PROPERTY_EXISTS() second argument must be a property name identifier",
            ));
        }
        self.next_token();
        if self.peek_type() != TokenType::RightParen {
            return Err(self.error(
                "PROPERTY_EXISTS() second argument must be a bare property name, not an expression",
            ));
        }
        self.next_token(); // consume )
        Ok(Expr::FunctionCall(FunctionCallExpr {
            name: SmallName::from_name("property_exists"),
            args: vec![
                Expr::Variable(var_name),
                Expr::Literal(LiteralValue::String(prop_tok.literal.into_owned())),
            ],
            distinct: false,
        }))
    }

    /// Parses `vector(list)` or `vector(list, dimension, coordType)`
    /// (CIP-214), already having consumed the `VECTOR` keyword and
    /// confirmed the next token is `(`. The optional third argument is a
    /// bare coordinate-type keyword (`INT32`, `FLOAT`, ...), not an
    /// ordinary expression -- like `normalize()`'s normal form and
    /// `PROPERTY_EXISTS()`'s property name, it needs dedicated parsing so
    /// the static variable-scope validator doesn't reject it as an
    /// undefined variable reference. Only this construction shape is
    /// supported (as CIP-216 eval-suite test-data setup); full CIP-214
    /// `vector()` semantics are otherwise out of scope.
    pub(super) fn parse_vector_call(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume (
        if self.peek_type() == TokenType::RightParen {
            return Err(self.error("vector() requires at least 1 argument"));
        }
        let mut args = vec![self.parse_expression()?];
        if self.peek_type() == TokenType::Comma {
            self.next_token();
            args.push(self.parse_expression()?);
            self.expect(TokenType::Comma)?;
            let coord_tok = self.peek().clone();
            if !coord_tok.ty.is_ident_like() {
                return Err(self.error_at_token(
                    &coord_tok,
                    "vector() third argument must be a coordinate type keyword",
                ));
            }
            self.next_token();
            // "SIGNED INTEGER" (CIP-200's two-word alias for INTEGER) is the
            // only multi-word coordinate type keyword.
            let mut coord_name = coord_tok.literal.to_ascii_uppercase();
            if coord_name == "SIGNED" && self.peek_is_ident("INTEGER") {
                self.next_token();
                coord_name.push_str(" INTEGER");
            }
            args.push(Expr::Literal(LiteralValue::String(coord_name)));
        }
        self.expect(TokenType::RightParen)?;
        Ok(Expr::FunctionCall(FunctionCallExpr {
            name: SmallName::from_name("vector"),
            args,
            distinct: false,
        }))
    }

    /// The comma spelling's lowered form: the specification is an ordinary
    /// expression, so the direction cannot be baked into the dispatch name
    /// at parse time — `trim_spec` carries it as the first argument and
    /// selects the direction (and the strict single-character rule of the
    /// direction-named entries) during evaluation.
    pub(super) fn build_trim_spec_call(args: Vec<Expr>) -> Expr {
        Expr::FunctionCall(FunctionCallExpr {
            name: SmallName::from_name("trim_spec"),
            args,
            distinct: false,
        })
    }

    pub(super) fn build_trim_call(spec: Option<&'static str>, args: Vec<Expr>) -> Expr {
        let name = match spec {
            Some("LEADING") => "trim_leading",
            Some("TRAILING") => "trim_trailing",
            _ => "trim",
        };
        Expr::FunctionCall(FunctionCallExpr {
            name: SmallName::from_name(name),
            args,
            distinct: false,
        })
    }

    pub(super) fn parse_add_sub(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_mul_div()?;
        loop {
            match self.peek_type() {
                TokenType::Plus => {
                    self.next_token();
                    let right = self.parse_mul_div()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: PLUS,
                        right,
                    }));
                }
                TokenType::Dash => {
                    self.next_token();
                    let right = self.parse_mul_div()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: MINUS,
                        right,
                    }));
                }
                TokenType::DoublePipe => {
                    self.next_token();
                    let right = self.parse_mul_div()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: CONCAT,
                        right,
                    }));
                }
                _ => break,
            }
        }
        Ok(left)
    }

    pub(super) fn parse_mul_div(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_exponentiation()?;
        loop {
            match self.peek_type() {
                TokenType::Star => {
                    self.next_token();
                    let right = self.parse_exponentiation()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: MUL,
                        right,
                    }));
                }
                TokenType::Slash => {
                    self.next_token();
                    let right = self.parse_exponentiation()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: DIV,
                        right,
                    }));
                }
                TokenType::Percent => {
                    self.next_token();
                    let right = self.parse_exponentiation()?;
                    left = Expr::Binary(Box::new(BinaryExpr {
                        left,
                        op: MOD,
                        right,
                    }));
                }
                _ => break,
            }
        }
        Ok(left)
    }

    pub(super) fn parse_exponentiation(&mut self) -> ParseResult<Expr> {
        let mut left = self.parse_unary()?;
        while self.peek_type() == TokenType::Caret {
            self.next_token();
            let right = self.parse_unary()?;
            left = Expr::Binary(Box::new(BinaryExpr {
                left,
                op: POW,
                right,
            }));
        }
        Ok(left)
    }

    pub(super) fn parse_unary(&mut self) -> ParseResult<Expr> {
        if self.peek_type() == TokenType::Plus {
            // ADR-0191 pins the operator spelling `RETURN NOT + 1` as a
            // syntax error (KeywordSymbolicNames [34]); keep that pin while
            // a unary plus elsewhere is accepted (Neo4j's `RETURN +1`).
            if self.pos > 0 && self.tokens[self.pos - 1].ty == TokenType::NOT {
                let tok = self.peek().clone();
                return Err(
                    self.error_at_token(&tok, format!("unexpected token \"{}\"", tok.literal))
                );
            }
            // Unary plus is the identity on numbers (Neo4j's `RETURN +1`),
            // but a directly nested unary plus (`+ +1`, and `++1`) is an
            // invalid expression start in the reference engine, so this is
            // the length-two prefix we do not accept.
            if self.peek_at(1).ty == TokenType::Plus {
                let bad = self.peek_at(1).clone();
                return Err(
                    self.error_at_token(&bad, format!("unexpected token \"{}\"", bad.literal))
                );
            }
            self.next_token();
            let expr = self.with_expr_depth(|p| p.parse_unary())?;
            return Ok(Expr::Unary(Box::new(UnaryExpr { op: PLUS, expr })));
        }
        if self.peek_type() == TokenType::Dash {
            // A double (or longer) unary minus applied directly to an
            // Infinity/Inf/NaN literal (no parens in between) is a compile-time
            // syntax error in Neo4j, even though `-Infinity` and
            // `-(-Infinity)` are both valid (CIP-55 deviation: `--Infinity` is
            // rejected while `--1` still parses). Detect a run of two or more
            // leading Dash tokens landing directly on such a literal.
            if self.pos + 1 < self.tokens.len() && self.tokens[self.pos + 1].ty == TokenType::Dash {
                let mut lookahead = self.pos + 1;
                while lookahead < self.tokens.len() && self.tokens[lookahead].ty == TokenType::Dash
                {
                    lookahead += 1;
                }
                if lookahead < self.tokens.len()
                    && matches!(
                        self.tokens[lookahead].ty,
                        TokenType::INFINITY | TokenType::NAN
                    )
                {
                    let bad_tok = self.tokens[lookahead].clone();
                    return Err(self.error_at_token(
                        &bad_tok,
                        format!("Invalid input '{}', expected: a number", bad_tok.literal),
                    ));
                }
            }
            self.next_token();
            // Special case: -<integer literal> for int64 min value
            if self.peek_type() == TokenType::Integer {
                let next = self.peek().clone();
                if parse_int_literal(&next.literal).is_err() {
                    let neg_literal = format!("-{}", next.literal);
                    if let Ok(val) = parse_int_literal(&neg_literal) {
                        self.next_token();
                        return Ok(Expr::Literal(LiteralValue::Integer(val)));
                    }
                }
            }
            // ADR-0257: unary `-` chains recurse here directly, bypassing
            // `parse_expression`, so each step must count separately
            // (LABS-69).
            let expr = self.with_expr_depth(|p| p.parse_unary())?;
            return Ok(Expr::Unary(Box::new(UnaryExpr { op: MINUS, expr })));
        }
        self.parse_postfix()
    }

    /// Walks the maximal `.ident` token chain starting at `from` (which must
    /// point at a `Dot`) and reports `(end, ends_in_call)`: `end` is the
    /// token index where the scan stopped — the `(` when the chain leads to
    /// a function call, otherwise the first token that broke the chain — and
    /// `ends_in_call` tells which. Pure lookahead over the token stream;
    /// consumes nothing. The result is constant for every dot position
    /// inside one maximal chain, which is what lets `parse_postfix` memoize
    /// it instead of rescanning the remaining tokens per dot.
    pub(super) fn scan_dot_chain_for_call(&self, from: usize) -> (usize, bool) {
        let mut pos = from;
        while pos < self.tokens.len() && self.tokens[pos].ty == TokenType::Dot {
            let ident = pos + 1;
            if ident >= self.tokens.len() || !self.tokens[ident].ty.is_schema_name() {
                return (ident, false);
            }
            let after = pos + 2;
            if after < self.tokens.len() && self.tokens[after].ty == TokenType::LeftParen {
                return (after, true);
            }
            if after >= self.tokens.len() || self.tokens[after].ty != TokenType::Dot {
                return (after, false);
            }
            pos = after;
        }
        (pos, false)
    }

    pub(super) fn parse_postfix(&mut self) -> ParseResult<Expr> {
        let primary = self.parse_primary()?;
        let ns = Self::extract_namespace(&primary);
        let mut base = PostfixBase::Built(primary, ns);
        // Memoized `scan_dot_chain_for_call` result: `(scan end, result)`.
        // Query positions (the dot after each consumed `.ident`) are strictly
        // increasing and the result is constant within one maximal chain, so
        // a cached `(end, res)` answers every later dot of the same chain
        // (`pos < end`) — each token is scanned at most once per
        // `parse_postfix` call rather than an O(remaining) lookahead per dot.
        let mut chain_scan: Option<(usize, bool)> = None;
        loop {
            match self.peek_type() {
                TokenType::Dot => {
                    self.next_token();
                    let prop_name = self.parse_schema_name("property name after '.'")?;
                    // Check for namespaced function call: expr.name(args) or expr.name.name(args)
                    if self.peek_type() == TokenType::LeftParen {
                        // Use the namespace path collected so far.
                        let path = match &mut base {
                            PostfixBase::Built(_, ns) => ns.take(),
                            PostfixBase::NsPath(path) => Some(std::mem::take(path)),
                        };
                        if let Some(mut func_name) = path {
                            func_name.push('.');
                            prop_name.with_str(|seg| func_name.push_str(seg));
                            self.next_token(); // consume (
                            let args = self.parse_arg_list()?;
                            base = PostfixBase::Built(
                                Expr::FunctionCall(FunctionCallExpr {
                                    name: SmallName::from_name(&func_name),
                                    args,
                                    distinct: false,
                                }),
                                None,
                            );
                            continue;
                        }
                    }
                    // Check for deeper nesting: if next is '.', this could be a longer namespace
                    // Only use namespace Variable if the chain eventually leads to a function call '('
                    if self.peek_type() == TokenType::Dot {
                        let carries_path = matches!(
                            &base,
                            PostfixBase::Built(_, Some(_)) | PostfixBase::NsPath(_)
                        );
                        if carries_path {
                            // Look ahead to see if this chain eventually leads to '('
                            let is_func_namespace = match chain_scan {
                                Some((end, res)) if self.pos < end => res,
                                _ => {
                                    let scanned = self.scan_dot_chain_for_call(self.pos);
                                    chain_scan = Some(scanned);
                                    scanned.1
                                }
                            };
                            if is_func_namespace {
                                // Accumulate the segment into the bare path,
                                // entering (or staying in) `NsPath`:
                                // materializing an `Expr` per segment cost
                                // Θ(n²) in string clones (a parse-time DoS on
                                // maximal inputs), and nothing can observe the
                                // intermediate value — the terminating `(` arm
                                // above rebuilds the callee name from the path.
                                match &mut base {
                                    PostfixBase::Built(_, ns) => {
                                        if let Some(mut path) = ns.take() {
                                            path.push('.');
                                            prop_name.with_str(|seg| path.push_str(seg));
                                            base = PostfixBase::NsPath(path);
                                            continue;
                                        }
                                    }
                                    PostfixBase::NsPath(path) => {
                                        path.push('.');
                                        prop_name.with_str(|seg| path.push_str(seg));
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    // Plain property access; extend the running namespace path
                    // to keep it in sync (`extract_namespace` of a Property is
                    // the base namespace plus `.` plus the property).
                    base = match base {
                        PostfixBase::Built(expr, mut ns) => {
                            if let Some(ns_str) = ns.as_mut() {
                                ns_str.push('.');
                                prop_name.with_str(|seg| ns_str.push_str(seg));
                            }
                            PostfixBase::Built(
                                Expr::Property(Box::new(PropertyAccess {
                                    expr,
                                    property: prop_name,
                                    key_expr: None,
                                })),
                                ns,
                            )
                        }
                        // Unreachable for valid input: the scan admitted
                        // `NsPath` only for a chain ending in `(`, so
                        // mid-chain the token after `.ident` is always `.`
                        // or `(` — never a plain property hop. A violation
                        // is a typed internal error, never a panic.
                        PostfixBase::NsPath(_) => {
                            return Err(self.internal_error(
                                "a call-bound dot-chain only continues at '.' or '('",
                            ));
                        }
                    };
                }
                TokenType::LeftBracket => {
                    // Subscript results are never namespace paths. `NsPath`
                    // is unreachable here for valid input by the same scan
                    // invariant as the plain-property arm above; a violation
                    // is a typed internal error, never a panic.
                    let PostfixBase::Built(expr, _) = base else {
                        return Err(self.internal_error(
                            "a call-bound dot-chain only continues at '.' or '('",
                        ));
                    };
                    self.next_token(); // consume [
                                       // Check for [..to]
                    if self.peek_type() == TokenType::DotDot {
                        self.next_token(); // consume ..
                        let to = self.parse_expression()?;
                        self.expect(TokenType::RightBracket)?;
                        base = PostfixBase::Built(
                            Expr::Subscript(Box::new(SubscriptExpr {
                                expr,
                                index: None,
                                from: None,
                                to: Some(to),
                                slice: true,
                            })),
                            None,
                        );
                        continue;
                    }
                    let first = self.parse_expression()?;
                    if self.peek_type() == TokenType::DotDot {
                        self.next_token(); // consume ..
                        let to = if self.peek_type() != TokenType::RightBracket {
                            Some(self.parse_expression()?)
                        } else {
                            None
                        };
                        self.expect(TokenType::RightBracket)?;
                        base = PostfixBase::Built(
                            Expr::Subscript(Box::new(SubscriptExpr {
                                expr,
                                index: None,
                                from: Some(first),
                                to,
                                slice: true,
                            })),
                            None,
                        );
                    } else {
                        self.expect(TokenType::RightBracket)?;
                        base = PostfixBase::Built(
                            Expr::Subscript(Box::new(SubscriptExpr {
                                expr,
                                index: Some(first),
                                from: None,
                                to: None,
                                slice: false,
                            })),
                            None,
                        );
                    }
                }
                // Note: the `variable:<label-expr>` predicate used to be
                // parsed here (in `<postfix operator>`, tighter than `+`).
                // CIP-190 moves it to `parse_string_null_check`'s `<advanced
                // comparison predicate part 2>` level (looser than `+`,
                // alongside the `IS <label-expr>` spelling) -- see
                // label-expression-precedence.feature. `parse_postfix` no
                // longer consumes a bare `:` at all, so it correctly stops
                // and lets the caller's `<advanced comparison predicate part
                // 2>` check see it.
                TokenType::LeftBrace
                    if matches!(&base, PostfixBase::Built(Expr::Variable(_), _))
                        && (self.peek_brace_is_map_projection()
                            // `n {}` is an empty map projection. The
                            // subquery-introducer primaries (EXISTS/COUNT/
                            // COLLECT/CASE) keep their own empty-brace
                            // rejection, so this arm is only reached for an
                            // ordinary bound variable.
                            || self.peek_at(1).ty == TokenType::RightBrace) =>
                {
                    // `<variable> <map projection>` (openCypher's map
                    // projection is always rooted at a plain variable).
                    // Also how CIP-190's near-ambiguities resolve
                    // `exists {name: exists.name}` / `case {name:
                    // case.name}` in favor of the ordinary-variable
                    // reading once the EXISTS/COUNT/COLLECT/CASE primary
                    // handling has already decided the keyword isn't
                    // introducing a subquery/CASE expression here.
                    //
                    // Gated on the same `peek_brace_is_map_projection`
                    // lookahead used for EXISTS/COUNT/COLLECT: without it,
                    // this would also fire for CIP-146's `USE <graph-expr>
                    // { <query> }` top-level brace body (whose graph-expr
                    // parsing runs through this same general expression
                    // grammar) and try to parse the query body as map
                    // projection items, hard-erroring instead of leaving
                    // the `{` for `parse_braced_single_query`.
                    //
                    // A map projection is never a namespace path. The
                    // non-`Built` case is unreachable for valid input (the
                    // match guard above only matches a built variable); a
                    // violation is a typed internal error, never a panic.
                    let PostfixBase::Built(expr, _) = base else {
                        return Err(self.internal_error("the guard only matches a built variable"));
                    };
                    let items = self.parse_map_projection_items()?;
                    base = PostfixBase::Built(
                        Expr::MapProjection(Box::new(MapProjectionExpr { expr, items })),
                        None,
                    );
                }
                _ => break,
            }
        }
        match base {
            PostfixBase::Built(expr, _) => Ok(expr),
            // A call-bound dot-chain is exited only through its terminating
            // `(` arm, which leaves a `Built` base — so `NsPath` here is
            // unreachable for valid input; a violation is a typed internal
            // error, never a panic.
            PostfixBase::NsPath(_) => {
                Err(self.internal_error("a call-bound dot-chain ends at its '(' arm"))
            }
        }
    }

    /// Builds the one-clause `MATCH` `Statement` wrapping a subquery
    /// expression's bare-pattern form (`EXISTS { pattern [WHERE expr] }` /
    /// `COUNT { pattern [WHERE expr] }`), shared by `parse_exists_subquery`
    /// and `parse_count_subquery`.
    fn bare_pattern_match_statement(
        pattern: Vec<PatternPath>,
        where_expr: Option<Expr>,
    ) -> Statement {
        Statement {
            clauses: vec![Clause::Match(MatchClause {
                optional: false,
                match_mode: MatchMode::DifferentRelationships,
                pattern,
                using_scan: Vec::new(),
                using_index: Vec::new(),
                using_join: Vec::new(),
                where_expr,
                search: None,
            })],
            ..Statement::default()
        }
    }

    /// `EXISTS { ... }` subquery expression -- the two grammar forms (bare
    /// pattern, or a full statement of one-or-more clauses), mirrored by
    /// `parse_count_subquery` with row counting instead of the existence
    /// test. Kept out-of-line (not inlined into `parse_primary`) so its
    /// locals don't inflate that function's stack frame, which is on the
    /// hot recursive path for deeply nested expressions (e.g. TCK's 40-deep
    /// nested list literals). The `{` is the current token; the caller has
    /// already ruled out a map projection (`peek_brace_is_map_projection`).
    #[inline(never)]
    pub(super) fn parse_exists_subquery(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume {
        self.exists_subquery_depth += 1;
        let result = self.parse_exists_subquery_body();
        self.exists_subquery_depth -= 1;
        result
    }

    /// The body of [`Parser::parse_exists_subquery`] (the `{` consumed and
    /// the existence-probe depth already counted).
    fn parse_exists_subquery_body(&mut self) -> ParseResult<Expr> {
        let peek = self.peek().clone();
        if peek.ty == TokenType::LeftParen {
            // Simple pattern: EXISTS { pattern }
            let pattern = self.parse_pattern()?;
            let where_expr = if self.peek_type() == TokenType::WHERE {
                self.next_token();
                Some(self.parse_expression()?)
            } else {
                None
            };
            self.expect(TokenType::RightBrace)?;
            let stmt = Self::bare_pattern_match_statement(pattern, where_expr);
            return Ok(Expr::ExistsSubquery(Box::new(ExistsSubqueryExpr {
                statement: stmt,
            })));
        }
        let stmt = self.parse_statement_block()?;
        self.expect(TokenType::RightBrace)?;
        // CIP-63: unlike COUNT, a distinct UNION inside EXISTS
        // may omit RETURN in every branch (see the shared
        // helper's doc comment).
        self.check_subquery_union_consistency(&stmt, false)?;
        Ok(Expr::ExistsSubquery(Box::new(ExistsSubqueryExpr {
            statement: stmt,
        })))
    }

    /// `COUNT { ... }` subquery expression -- mirrors `EXISTS { ... }`'s two
    /// grammar forms (bare pattern, or a full statement of one-or-more
    /// clauses), just counting rows instead of testing non-emptiness. Kept
    /// out-of-line (not inlined into `parse_primary`) so its locals don't
    /// inflate that function's stack frame, which is on the hot recursive
    /// path for deeply nested expressions (e.g. TCK's 40-deep nested list
    /// literals).
    #[inline(never)]
    pub(super) fn parse_count_subquery(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume {
        if self.peek_type() == TokenType::RightBrace {
            // CIP-31 count_standalone[6]: `COUNT { }` is a compile-time
            // syntax error, not a valid (empty) subquery -- unlike EXISTS
            // and COLLECT, which this batch leaves alone (out of scope).
            return Err(
                self.error("InvalidCountExpression: COUNT {} must contain a pattern or a query")
            );
        }
        let peek = self.peek().clone();
        if peek.ty == TokenType::LeftParen {
            let pattern = self.parse_pattern()?;
            let where_expr = if self.peek_type() == TokenType::WHERE {
                self.next_token();
                Some(self.parse_expression()?)
            } else {
                None
            };
            self.expect(TokenType::RightBrace)?;
            let stmt = Self::bare_pattern_match_statement(pattern, where_expr);
            return Ok(Expr::CountSubquery(Box::new(CountSubqueryExpr {
                statement: stmt,
            })));
        }
        let stmt = self.parse_statement_block()?;
        self.expect(TokenType::RightBrace)?;
        // CIP-66's own UNION rules (verified against Neo4j): a *distinct*
        // UNION inside COUNT can never omit RETURN in any branch (its
        // dedup needs comparable, named columns), unlike EXISTS below,
        // which only cares about row existence and has no such need.
        self.check_subquery_union_consistency(&stmt, true)?;
        Ok(Expr::CountSubquery(Box::new(CountSubqueryExpr {
            statement: stmt,
        })))
    }

    /// CIP-63 (EXISTS) / CIP-66 (COUNT): shared UNION-consistency check for
    /// a subquery body's `<RegularQuery>`. Now that `parse_regular_query`
    /// lets UNION parse inside these bodies at all, the semantic rules both
    /// CIPs spell out for RETURN omission across UNION branches need
    /// enforcing here, or a UNION that omission rules forbid would silently
    /// "succeed" instead of raising the compile-time error the doc requires:
    /// (1) if any branch has an explicit RETURN, every branch must have one
    /// -- RETURN omission is all-or-nothing "for consistency"; (2) when
    /// `reject_omitted_distinct` is set (COUNT, CIP-66: a distinct union
    /// needs named columns to compare rows for deduplication), a plain
    /// `UNION` (not `UNION ALL`) can never omit RETURN, even consistently
    /// -- CIP-63 verified against Neo4j that EXISTS has no such
    /// restriction, since existence doesn't care about column identity, so
    /// callers checking an EXISTS body pass `false`; (3) when every branch
    /// does have a RETURN, they must all project the same column names,
    /// compared as a name multiset (order is irrelevant: the executor
    /// reorders each branch's rows onto the head's columns) -- the general
    /// (pre-existing) `DifferentColumnsInUnion` rule, which a UNION that
    /// failed to parse at all inside these subqueries had been trivially
    /// "satisfying" before.
    pub(super) fn check_subquery_union_consistency(
        &self,
        stmt: &Statement,
        reject_omitted_distinct: bool,
    ) -> ParseResult<()> {
        use relate_model::name_list::same_name_multiset;

        if stmt.union.is_none() {
            return Ok(());
        }

        // The clause that decides a branch's columns. A NEXT chain hanging
        // off a UNION *head* belongs to the whole composite (CIP-213:
        // `A UNION B NEXT C` parses as `(A UNION B) NEXT C`), so that head
        // compares by its own final clause — otherwise its NEXT stage's
        // columns would be matched against the other arms' pre-NEXT columns
        // (`NextStatementAcceptance` "Should pass constant through NEXT 5").
        // Every other branch reads its own NEXT tail.
        fn branch_final(s: &Statement) -> &Statement {
            if s.union.is_some() {
                s
            } else {
                tail_stage(s)
            }
        }
        // A branch's result shape. CIP-135: a `{ WHEN ... }`/`{ WHEN ...
        // ELSE ... }` arm has no direct `Clause::Return` -- its shape is
        // whatever its branch bodies project (all branches agree, enforced
        // by the conditional's own rules), so recursing on the first one
        // stands in for the whole clause. Mirrors the front's
        // `union_branch_shape`, which owns the same classification for
        // statements the parser does not screen.
        enum BranchShape {
            Cols(Vec<String>),
            /// `RETURN *` -- columns unknowable until execution.
            Wildcard,
            /// No RETURN clause at all (FINISH / write-only arm).
            Omitted,
        }
        /// Whether a CALL subquery body projects columns: its final stage
        /// is a RETURN (or a conditional / nested CALL that projects). A
        /// unit subquery call with no RETURN makes the enclosing arm a
        /// no-column arm.
        fn call_projects(csq: &crate::ast::CallSubqueryClause) -> bool {
            fn stmt_projects(s: &Statement) -> bool {
                let body = if s.union.is_some() { s } else { tail_stage(s) };
                match body.clauses.last() {
                    Some(Clause::Return(_)) => true,
                    Some(Clause::Conditional(cc)) => cc
                        .branches
                        .first()
                        .map(|b| stmt_projects(&b.body))
                        .or_else(|| cc.else_body.as_ref().map(stmt_projects))
                        .unwrap_or(false),
                    Some(Clause::CallSubquery(inner)) => stmt_projects(&inner.statement),
                    _ => false,
                }
            }
            stmt_projects(&csq.statement)
        }
        fn branch_shape(s: &Statement) -> BranchShape {
            let body = branch_final(s);
            if let [Clause::Conditional(cc)] = body.clauses.as_slice() {
                let inner = cc
                    .branches
                    .first()
                    .map(|b| &b.body)
                    .or(cc.else_body.as_ref());
                return match inner {
                    Some(inner) => branch_shape(inner),
                    None => BranchShape::Omitted,
                };
            }
            let Some(Clause::Return(rc)) = body.clauses.last() else {
                // An arm whose final clause is a CALL subquery exports that
                // body's columns (plus the in-scope names before it), so the
                // column set is only known at execution: a wildcard. A unit
                // subquery call with no RETURN leaves the arm columnless.
                if let Some(Clause::CallSubquery(csq)) = body.clauses.last() {
                    if call_projects(csq) {
                        return BranchShape::Wildcard;
                    }
                }
                return BranchShape::Omitted;
            };
            let mut cols = Vec::with_capacity(rc.items.len());
            for item in &rc.items {
                if item.all {
                    return BranchShape::Wildcard;
                }
                if let Some(alias) = &item.alias {
                    cols.push(alias.to_string());
                } else if let Expr::Variable(v) = &item.expr {
                    cols.push(v.to_string());
                } else if let Some(src) = &item.source_text {
                    cols.push(src.clone());
                } else {
                    cols.push(String::new());
                }
            }
            BranchShape::Cols(cols)
        }

        let mut branches: Vec<&Statement> = vec![stmt];
        let mut distinct_link_seen = false;
        let mut current = &stmt.union;
        while let Some(u) = current {
            if !u.all {
                distinct_link_seen = true;
            }
            branches.push(&u.statement);
            current = &u.statement.union;
        }

        let shapes: Vec<BranchShape> = branches.iter().map(|s| branch_shape(s)).collect();
        let any_missing = shapes.iter().any(|s| matches!(s, BranchShape::Omitted));
        let any_present = shapes.iter().any(|s| !matches!(s, BranchShape::Omitted));

        if any_missing && any_present {
            return Err(self.error(
                "DifferentColumnsInUnion: all UNION branches must consistently include or omit RETURN",
            ));
        }
        if any_missing && distinct_link_seen && reject_omitted_distinct {
            return Err(self.error(
                "InvalidUnionOmittedReturn: a distinct UNION requires an explicit RETURN in every branch",
            ));
        }
        if !any_missing {
            let mut reference: Option<Vec<String>> = None;
            for shape in &shapes {
                if let BranchShape::Cols(cols) = shape {
                    match &reference {
                        None => reference = Some(cols.clone()),
                        Some(r) if !same_name_multiset(r, cols) => {
                            return Err(self.error(
                                "DifferentColumnsInUnion: all UNION branches must have the same column names",
                            ));
                        }
                        Some(_) => {}
                    }
                }
            }
        }
        Ok(())
    }

    /// `COLLECT { <RegularQuery> } (CIP-71): mirrors `parse_count_subquery`'s
    /// full-statement path (no bare-pattern shorthand -- COLLECT always
    /// requires a full `<RegularQuery>` ending in `RETURN`). Enforces the
    /// doc's syntactic restrictions that are checkable on the parsed shape
    /// alone: every branch of the (possibly UNION-chained) inner query must
    /// end with a `RETURN` clause projecting exactly one non-`*` item.
    /// Restrictions that require scope-aware analysis (no updating clauses,
    /// no shadowing outer variables, inner variables not leaking outward)
    /// are deferred to the eval/validation batch that adds COLLECT
    /// evaluation -- pure re-use of `EvalContext`/`validate.rs` machinery,
    /// not a parsing concern.
    #[inline(never)]
    pub(super) fn parse_collect_subquery(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume {
        if self.peek_type() == TokenType::RightBrace {
            return Err(self.error("A COLLECT subquery must end with a single return column"));
        }
        let stmt = self.parse_statement_block()?;
        self.expect(TokenType::RightBrace)?;
        self.check_collect_return_shape(&stmt)?;
        Ok(Expr::CollectSubquery(Box::new(CollectSubqueryExpr {
            statement: stmt,
        })))
    }

    /// Checks that `stmt` and every UNION-chained branch after it ends in a
    /// `RETURN` clause with exactly one item and that the item isn't `*`.
    pub(super) fn check_collect_return_shape(&self, stmt: &Statement) -> ParseResult<()> {
        let bad_shape = || self.error("A COLLECT subquery must end with a single return column");
        let mut current = stmt;
        loop {
            // CIP-213: the "must end with a single return column" rule
            // applies to this arm's *true* terminal stage -- see
            // [`tail_stage`].
            let tail = tail_stage(current);
            match tail.clauses.last() {
                Some(Clause::Return(rc)) if rc.items.len() == 1 && !rc.items[0].all => {}
                _ => return Err(bad_shape()),
            }
            match &current.union {
                Some(next) => current = &next.statement,
                None => return Ok(()),
            }
        }
    }

    pub(super) fn parse_primary(&mut self) -> ParseResult<Expr> {
        let tok = self.peek().clone();

        match tok.ty {
            TokenType::Integer => {
                self.next_token();
                let val = parse_int_literal(&tok.literal)
                    .map_err(|error| self.int_literal_error(&tok, error, IntLiteralSite::Expression))?;
                Ok(Expr::Literal(LiteralValue::Integer(val)))
            }
            TokenType::Float => {
                self.next_token();
                let val: f64 = tok.literal.parse().map_err(|_| {
                    self.error_at_token(&tok, format!("invalid float literal: {}", tok.literal))
                })?;
                // A numeric literal (as opposed to the Infinity/NaN keyword
                // literals, which are their own token types) that overflows
                // to +-infinity is a compile-time error, not a valid way to
                // spell Infinity (CIP-52 NOTES.md: `RETURN 1e400` is rejected
                // by live Neo4j with "numeric value out of range").
                if val.is_infinite() {
                    return Err(self
                        .error_at_token(
                            &tok,
                            "FloatingPointOverflow: float literal is too large".to_string(),
                        )
                        .with_detail("FloatingPointOverflow"));
                }
                Ok(Expr::Literal(LiteralValue::Float(val)))
            }
            TokenType::ObfuscatedLiteral => {
                // The Neo4j internal obfuscated literal (preview-gated at
                // the lexer): a dummy `false` that exists to pass semantic
                // analysis, never meant to execute.
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Bool(false)))
            }
            TokenType::String => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::String(tok.literal.into_owned())))
            }
            TokenType::InterpString => {
                self.next_token();
                let parts = parse_interp_body(&tok.literal, self.options)
                    .map_err(|e| self.error_at_token(&tok, e).with_detail("UnexpectedSyntax"))?;
                Ok(Expr::StringInterp(parts))
            }
            TokenType::TRUE => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Bool(true)))
            }
            TokenType::FALSE => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Bool(false)))
            }
            TokenType::NULL => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Null))
            }
            TokenType::INFINITY => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Float(f64::INFINITY)))
            }
            TokenType::NAN => {
                self.next_token();
                Ok(Expr::Literal(LiteralValue::Float(f64::NAN)))
            }
            TokenType::Parameter => {
                self.next_token();
                Ok(Expr::Parameter(tok.literal.into_owned()))
            }
            TokenType::LeftBracket => self.parse_list_literal(),
            TokenType::LeftBrace => {
                // CIP-272: `{k : v IN map [WHERE p] | k' : v'}` and
                // `{item IN list [WHERE p] | k' : v'}` are map comprehensions;
                // anything else (including `{k: v IN m}`, whose value is a
                // genuine IN expression) stays a map literal.
                if let Some(mc) = self.try_parse_map_comprehension()? {
                    return Ok(mc);
                }
                let pairs = self.parse_map_literal()?;
                Ok(Expr::Map(pairs))
            }
            TokenType::LeftParen => {
                if self.node_pattern_precedes_relationship() {
                    return self.parse_pattern_predicate();
                }
                self.next_token();
                // A parenthesized expression may carry a leading unary `+`:
                // the openCypher `oC_UnaryAddOrSubtractExpression` permits a
                // run of `PLUS`/`MINUS`, and the simple-CASE predicate
                // rendering spells the keyword reading `CONTAINS + 1` as
                // `CONTAINS (+1)` (Neo4j `KeywordPriority`). The bare form is
                // deliberately not accepted — ADR-0191's reference rows pin
                // `RETURN NOT + 1` and `RETURN DISTINCT + 1` as syntax errors.
                let expr = if self.peek_type() == TokenType::Plus {
                    self.next_token();
                    Expr::Unary(Box::new(UnaryExpr {
                        op: PLUS,
                        expr: self.parse_expression()?,
                    }))
                } else {
                    self.parse_expression()?
                };
                self.expect(TokenType::RightParen)?;
                Ok(Expr::Paren(Box::new(expr)))
            }
            TokenType::COUNT => {
                self.next_token();
                if self.peek_type() == TokenType::LeftBrace && !self.peek_brace_is_map_projection()
                {
                    return self.parse_count_subquery();
                }
                if self.peek_type() != TokenType::LeftParen {
                    return Ok(Expr::Variable(SmallName::from_name(&tok.literal)));
                }
                self.next_token(); // consume (
                if self.peek_type() == TokenType::Star {
                    self.next_token();
                    self.expect(TokenType::RightParen)?;
                    return Ok(Expr::CountStar);
                }
                let distinct = if self.peek_type() == TokenType::DISTINCT {
                    self.next_token();
                    true
                } else if self.all_is_set_quantifier() {
                    // ALL is the explicit (default) set-quantifier; semantically
                    // equivalent to omitting the quantifier entirely.
                    self.next_token();
                    false
                } else {
                    false
                };
                let arg = self.parse_expression()?;
                self.expect(TokenType::RightParen)?;
                Ok(Expr::FunctionCall(FunctionCallExpr {
                    name: SmallName::from_name("count"),
                    args: vec![arg],
                    distinct,
                }))
            }
            TokenType::COLLECT => {
                self.next_token();
                if self.peek_type() == TokenType::LeftBrace && !self.peek_brace_is_map_projection()
                {
                    return self.parse_collect_subquery();
                }
                if self.peek_type() != TokenType::LeftParen {
                    return Ok(Expr::Variable(SmallName::from_name(&tok.literal)));
                }
                self.next_token(); // consume (
                let distinct = if self.peek_type() == TokenType::DISTINCT {
                    self.next_token();
                    true
                } else if self.all_is_set_quantifier() {
                    self.next_token();
                    false
                } else {
                    false
                };
                let args = self.parse_arg_list()?;
                Ok(Expr::FunctionCall(FunctionCallExpr {
                    name: SmallName::from_name(&tok.literal),
                    args,
                    distinct,
                }))
            }
            TokenType::CASE => {
                // `case` can be an ordinary bound variable (CIP-190
                // near-ambiguities.feature [1]/[3]). The ambiguity is
                // resolved by the token after CASE, not by swallowing a
                // failure: when that token starts the CASE grammar (`WHEN`,
                // or a valid test-expression start for the simple form) an
                // error inside a recognised CASE is the real one and must
                // propagate (`IntegerOverflow` in `CASE WHEN …`, for
                // instance) instead of being replaced by a misleading
                // `unexpected token "WHEN"` from the identifier reading.
                // Only when the grammar was never entered (the token is a
                // terminator/postfix/clause keyword) is the identifier
                // reading taken, letting `parse_postfix` see any trailing
                // `<map projection>` (`case {name: case.name}`).
                if !self.case_grammar_entered() {
                    self.next_token(); // consume CASE as an identifier
                    return Ok(Expr::Variable(SmallName::from_name(&tok.literal)));
                }
                self.parse_case_expr()
            }
            TokenType::ALL => self.parse_quantifier_or_function(),
            TokenType::Identifier => {
                self.next_token();
                let name_lower = tok.literal.to_ascii_lowercase();

                // Quantifiers
                if (name_lower == "any" || name_lower == "none" || name_lower == "single")
                    && self.peek_type() == TokenType::LeftParen
                {
                    self.backup();
                    return self.parse_quantifier_or_function();
                }

                // allReduce(acc = init, x IN list | expr, predicate)
                if name_lower == "allreduce" && self.peek_type() == TokenType::LeftParen {
                    return self.parse_allreduce_expr();
                }

                // shortestPath / allShortestPaths
                if (name_lower == "shortestpath" || name_lower == "allshortestpaths")
                    && self.peek_type() == TokenType::LeftParen
                {
                    self.next_token(); // consume (
                    let pattern = self.parse_pattern_path()?;
                    self.expect(TokenType::RightParen)?;
                    return Ok(Expr::ShortestPath(Box::new(ShortestPathExpr {
                        pattern,
                        all: name_lower == "allshortestpaths",
                    })));
                }

                // normalize(input [, normalForm]) — the optional second argument
                // is a bare normal-form keyword (NFC/NFD/NFKC/NFKD), not an
                // ordinary expression (CIP-132), so it needs dedicated parsing.
                if name_lower == "normalize" && self.peek_type() == TokenType::LeftParen {
                    return self.parse_normalize_call();
                }

                // trim([[LEADING|TRAILING|BOTH] [trimCharacterString] FROM] input) —
                // the GQL TRIM special form (CIP-149) is a distinct grammar production
                // from an ordinary comma-separated argument list.
                if name_lower == "trim" && self.peek_type() == TokenType::LeftParen {
                    return self.parse_trim_call();
                }

                // PROPERTY_EXISTS(<element variable>, <property name>) (CIP-247) —
                // the second argument is a bare property-name identifier, not an
                // ordinary expression, so it needs dedicated parsing.
                if name_lower == "property_exists" && self.peek_type() == TokenType::LeftParen {
                    return self.parse_property_exists_call();
                }

                // Function call
                if self.peek_type() == TokenType::LeftParen {
                    self.next_token(); // consume (
                    let distinct = if self.peek_type() == TokenType::DISTINCT {
                        self.next_token();
                        true
                    } else if self.all_is_set_quantifier() {
                        // ALL is the explicit (default) set-quantifier; semantically
                        // equivalent to omitting the quantifier entirely.
                        self.next_token();
                        false
                    } else {
                        false
                    };
                    let args = self.parse_arg_list()?;
                    return Ok(Expr::FunctionCall(FunctionCallExpr {
                        name: SmallName::from_name(&tok.literal),
                        args,
                        distinct,
                    }));
                }

                Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
            }
            TokenType::VECTOR => {
                self.next_token();
                if self.peek_type() == TokenType::LeftParen {
                    return self.parse_vector_call();
                }
                Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
            }
            TokenType::NODE
            | TokenType::REL
            | TokenType::POINT
            | TokenType::INDEX
            | TokenType::SPATIAL
            | TokenType::FROM
            // CIP-187: `options` is a real SHOW INDEXES/SHOW CONSTRAINTS
            // YIELD column name (e.g. `SHOW CONSTRAINTS YIELD options
            // RETURN options`), so it must be usable as a bare variable
            // reference like the other non-reserved schema/DDL keywords
            // above, not just in alias/YIELD-name position.
            | TokenType::OPTIONS
            // CIP-123: `constraint` (and similarly-shaped schema keywords)
            // is a non-reserved word usable as an ordinary `YIELD ... AS
            // constraint` alias / variable reference, e.g. when composing
            // `SHOW CONSTRAINTS YIELD name AS constraint WHERE constraint
            // = ...` -- same treatment as `TokenType::INDEX` above.
            | TokenType::CONSTRAINT
            // CIP-150 NOTES.md Q2: `RETURN` is a non-reserved word usable
            // as an ordinary variable reference (e.g. `RETURN RETURN AS
            // r`, where the second token names the variable bound by an
            // earlier `WITH ... AS RETURN`) -- reached here only when a
            // primary expression was already expected, so a `RETURN`
            // starting a fresh top-level clause is never affected.
            | TokenType::RETURN => {
                self.next_token();
                if self.peek_type() == TokenType::LeftParen {
                    self.next_token(); // consume (
                    let args = self.parse_arg_list()?;
                    return Ok(Expr::FunctionCall(FunctionCallExpr {
                        name: SmallName::from_name(&tok.literal),
                        args,
                        distinct: false,
                    }));
                }
                Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
            }
            TokenType::EXISTS => {
                self.next_token();
                if self.peek_type() == TokenType::LeftBrace && !self.peek_brace_is_map_projection()
                {
                    return self.parse_exists_subquery();
                }
                if self.peek_type() == TokenType::LeftParen {
                    self.next_token();
                    let args = self.parse_arg_list()?;
                    return Ok(Expr::FunctionCall(FunctionCallExpr {
                        name: SmallName::from_name("exists"),
                        args,
                        distinct: false,
                    }));
                }
                Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
            }
            // ADR-0191: the reduce form only applies when `(` follows; a
            // bare `REDUCE` is a plain variable reference owned by the
            // schema-name fallthrough below. The form itself (and its
            // accumulator/loop variables) is parsed by `parse_reduce_expr`,
            // which consumes REDUCE.
            TokenType::REDUCE if self.peek_at(1).ty == TokenType::LeftParen => {
                self.parse_reduce_expr()
            }
            _ if tok.ty.is_schema_name() => {
                // ADR-0191: the primary-expression variable read -- any
                // keyword token that reached this fallthrough is a variable
                // reference, spelling kept as written. Every arm above has
                // priority: the TRUE/FALSE/NULL/INF/INFINITY/NAN literals,
                // prefix NOT, the CASE/COUNT/EXISTS/COLLECT/REDUCE/VECTOR
                // forms, the ALL quantifier/function, the contextual schema
                // words and the DISTINCT/ALL set quantifiers their callers
                // consume.
                self.next_token();
                Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
            }
            _ => Err(self.error_at_token(
                &tok,
                format!(
                    "unexpected token {:?} ({:?}) at line {}, col {}",
                    tok.literal, tok.ty, tok.line, tok.col
                ),
            )),
        }
    }

    pub(super) fn parse_quantifier_or_function(&mut self) -> ParseResult<Expr> {
        let tok = self.next_token();
        let name_lower = tok.literal.to_ascii_lowercase();

        if self.peek_type() == TokenType::LeftParen {
            self.next_token(); // consume (
            let var_tok = self.peek().clone();
            // The quantifier variable is a symbolic name, so any keyword
            // spelling works unquoted too (ADR-0191).
            if var_tok.ty.is_schema_name() {
                self.next_token(); // consume variable
                if self.peek_type() == TokenType::IN {
                    self.next_token(); // consume IN
                    let list_expr = self.parse_expression()?;
                    // LABS-201: the GQL pipe spelling `any(x IN list | pred)`
                    // -- openCypher binds the predicate with WHERE. The pipe
                    // used to fall through to `expect(RightParen)` below and
                    // surface as a bare `expected RightParen, got |`; name
                    // the fix instead.
                    if self.peek_type() == TokenType::Pipe {
                        return Err(self.error(format!(
                            "a list predicate introduces its predicate with WHERE, not '|': \
                             write {name_lower}(x IN list WHERE predicate)"
                        )));
                    }
                    let predicate = if self.peek_type() == TokenType::WHERE {
                        self.next_token();
                        Some(self.parse_expression()?)
                    } else {
                        None
                    };
                    self.expect(TokenType::RightParen)?;
                    return Ok(Expr::Quantifier(Box::new(QuantifierExpr {
                        quantifier: name_lower,
                        variable: SmallName::from_name(&var_tok.literal),
                        list: list_expr,
                        predicate,
                    })));
                }
                // Not IN - backup variable
                self.backup();
            }
            // Not a quantifier shape (no `var IN <list>` prefix): parse as a
            // regular function call. The cursor sits after `(` at the first
            // argument on this path, whichever backup ran above.
            // LABS-201: `any((a)-[:R]->(b) | pred)` -- a pattern used
            // directly inside a list predicate. The pattern argument parses
            // as a pattern predicate and then the pipe fails
            // `expect(RightParen)` with the bare `expected RightParen, got |`
            // and no guidance. Detect the shape up front (the argument starts
            // with a node pattern and a pipe follows before the closing
            // paren) and point at the EXISTS requirement. Without the pipe
            // (e.g. `any((a)-[:R]->(b))`) the argument parses on and the
            // validator already reports `pattern predicates are only valid
            // in WHERE`, so this lookahead must not hijack it.
            if self.peek_type() == TokenType::LeftParen
                && self.node_pattern_precedes_relationship()
                && self.pipe_before_closing_paren()
            {
                return Err(self.error(
                    "a pattern cannot be used directly inside a list predicate: wrap it in \
                     EXISTS { ... } (e.g. EXISTS { (a)-[:R]->(b) }) or bind a pattern \
                     comprehension first (any(x IN [(a)-[:R]->(b) | b.prop] WHERE predicate))",
                ));
            }
            let distinct = if self.peek_type() == TokenType::DISTINCT {
                self.next_token();
                true
            } else {
                false
            };
            let args = self.parse_arg_list()?;
            return Ok(Expr::FunctionCall(FunctionCallExpr {
                name: SmallName::from_name(&tok.literal),
                args,
                distinct,
            }));
        }
        Ok(Expr::Variable(SmallName::from_name(&tok.literal)))
    }

    pub(super) fn parse_arg_list(&mut self) -> ParseResult<Vec<Expr>> {
        let mut args = Vec::new();
        if self.peek_type() == TokenType::RightParen {
            self.next_token();
            return Ok(args);
        }
        loop {
            args.push(self.parse_expression()?);
            if self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        self.expect(TokenType::RightParen)?;
        Ok(args)
    }

    pub(super) fn parse_list_literal(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume [

        if self.peek_type() == TokenType::RightBracket {
            self.next_token();
            return Ok(Expr::List(Vec::new()));
        }

        let first = self.peek().clone();
        // A list/pattern comprehension's own loop/path variable is a
        // symbolic name (ADR-0191), so any keyword spelling works unquoted
        // too. This resolves `[true IN [1]]` in favour of the comprehension
        // (it returns `[1]`, matching Neo4j), not a one-element list
        // literal holding a boolean `IN` expression.
        if first.ty.is_schema_name() {
            let first_pos = self.save_pos();
            self.next_token(); // consume identifier
            if self.peek_type() == TokenType::IN {
                // List comprehension
                let variable = SmallName::from_name(&first.literal);
                self.next_token(); // consume IN
                let list_expr = self.parse_expression()?;

                // A comma can never appear inside a comprehension, so
                // `[true IN [true], false]` is a *list literal* whose first
                // element is a boolean `IN` expression -- Neo4j prefers the
                // literal reading there. Restore and parse it as a literal
                // below instead of failing on the `,`.
                if self.peek_type() == TokenType::Comma {
                    self.restore_pos(first_pos);
                } else {
                    let where_expr = if self.peek_type() == TokenType::WHERE {
                        self.next_token();
                        // A list comprehension may omit its map expression, so
                        // a trailing `]` does not disambiguate a `|`.
                        Some(self.parse_comprehension_where_expr(false)?)
                    } else {
                        None
                    };

                    let map_expr = if self.peek_type() == TokenType::Pipe {
                        self.next_token();
                        Some(self.parse_expression()?)
                    } else {
                        None
                    };

                    self.expect(TokenType::RightBracket)?;
                    return Ok(Expr::ListComprehension(Box::new(ListComprehensionExpr {
                        variable,
                        list_expr,
                        where_expr,
                        map_expr,
                    })));
                }
            } else {
                // Pattern comprehension with path variable: [p = (n)-->() | expr].
                // ADR-0191: a keyword spelling is a path variable too (`[MATCH =
                // (n)-->() | n]`). The pattern-comprehension reading only applies
                // when a pattern path really follows the `=` -- decided by
                // speculatively running the real `parse_pattern_path` reader and
                // keeping the reading only when a `|` or `WHERE` follows the
                // pattern (`pattern_comprehension_follows_equals`); otherwise the
                // list-literal reading wins, so `[true = x]`, `[null = x]`,
                // `[true = (1 = 1)]` and `[x = 1]` stay list literals (matching
                // Neo4j, where a pattern never follows a literal).
                if self.peek_type() == TokenType::Equals
                    && self.pattern_comprehension_follows_equals()
                {
                    let path_var = SmallName::from_name(&first.literal);
                    self.next_token(); // consume =
                    return self.parse_pattern_comprehension_body(Some(path_var));
                }

                // Not a list comprehension, backup and parse as regular list
                self.backup();
            }
        }

        // Pattern comprehension without path variable: [(n)-->() | expr]
        if first.ty == TokenType::LeftParen {
            // Use lookahead to check if this looks like a pattern comprehension.
            // A pattern comprehension starts with a node pattern (a) followed by a relationship.
            if self.node_pattern_precedes_relationship() {
                return self.parse_pattern_comprehension_body(None);
            }
        }

        // Regular list literal
        let mut elements = Vec::new();
        loop {
            elements.push(self.parse_expression()?);
            if self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        self.expect(TokenType::RightBracket)?;
        Ok(Expr::List(elements))
    }

    /// Speculative gate for the `=` of a would-be pattern comprehension
    /// (`[pathVar = <pattern> | expr]`, ADR-0191): true when the tokens
    /// after the `=` (the current token must be that `=`) parse as a
    /// complete pattern path through the real `parse_pattern_path` reader
    /// AND the token after the pattern is `|` or `WHERE` (the
    /// comprehension's own grammar). Because the gate runs the real reader,
    /// everything `parse_pattern_path` accepts is recognized here -- label
    /// expressions and GPM forms (`(n:A|B)-->()`, `(IS A&B)-->()`), bare
    /// node or juxtaposed bodies (`(n)`, `(a)(b)`), parenthesized subpaths
    /// (`((q = (a)-->(b)))`) and the `shortestPath(...)` wrapper alike.
    ///
    /// The probe is invisible when it does not commit: the token position
    /// and every clause-level side-effect flag the parse can set (the
    /// `label_saw_*`/`quantifier_saw_*` mixing flags) are restored before
    /// returning, so a negative verdict leaves the list-literal reading to
    /// run exactly as if the probe never happened. A positive verdict is
    /// re-parsed for real by the caller (`parse_pattern_comprehension_body`),
    /// which re-applies those side effects.
    ///
    /// The verdict is memoized per `=` token position
    /// (`Parser::pattern_comprehension_probe_memo`): it depends only on
    /// that position, and without the memo a nested
    /// `[v = (n {p: ...}) | ...]` shape re-probes the whole nested term at
    /// every level -- 2^k parse cost on a sub-KB query (LABS-183).
    fn pattern_comprehension_follows_equals(&mut self) -> bool {
        debug_assert_eq!(self.peek_type(), TokenType::Equals);
        let key = self.pos;
        if let Some(&verdict) = self.pattern_comprehension_probe_memo.get(&key) {
            return verdict;
        }
        let saved_pos = self.save_pos();
        let saved_flags = self.side_effects;
        self.next_token(); // consume =
        let probe = self.parse_pattern_path();
        let is_comprehension =
            probe.is_ok() && matches!(self.peek_type(), TokenType::Pipe | TokenType::WHERE);
        self.restore_pos(saved_pos);
        self.side_effects = saved_flags;
        self.pattern_comprehension_probe_memo
            .insert(key, is_comprehension);
        is_comprehension
    }

    /// Lookahead from a `(` without consuming tokens: true when the tokens at
    /// the current position form a node pattern `( var? (:label)* {…}? )`
    /// followed by `-` or `<-`. That relationship start is what tells a
    /// pattern (a pattern comprehension after `[`, a pattern predicate such
    /// as `WHERE (n)-->()`) apart from a bracketed or parenthesized
    /// expression.
    pub(super) fn node_pattern_precedes_relationship(&self) -> bool {
        self.node_pattern_precedes_relationship_at(0)
    }

    /// [`node_pattern_precedes_relationship`] starting `offset` tokens ahead
    /// of the current position (0 == the current token).
    fn node_pattern_precedes_relationship_at(&self, offset: usize) -> bool {
        let mut pos = self.pos + offset;

        // Must start with (
        if pos >= self.tokens.len() || self.tokens[pos].ty != TokenType::LeftParen {
            return false;
        }
        pos += 1;

        // Skip optional variable. ADR-0191: a keyword spelling is a node
        // variable too, so this mirrors the reader (`parse_node_pattern`),
        // including the `WHERE`/`IS` one-token lookahead that keeps their
        // inline-predicate / label-introducer meanings.
        // (`peek_pattern_name_is_variable` folds in the symbolic-name check.)
        if self.peek_pattern_name_is_variable(pos - self.pos) {
            pos += 1;
        }

        // Skip labels (a keyword is a label name too, ADR-0169)
        while pos < self.tokens.len() && self.tokens[pos].ty == TokenType::Colon {
            pos += 1;
            if pos < self.tokens.len() && self.tokens[pos].ty.is_schema_name() {
                pos += 1;
            } else {
                return false;
            }
        }

        // Skip optional properties { ... }
        if pos < self.tokens.len() && self.tokens[pos].ty == TokenType::LeftBrace {
            let mut depth = 1;
            pos += 1;
            while depth > 0 && pos < self.tokens.len() {
                match self.tokens[pos].ty {
                    TokenType::LeftBrace => depth += 1,
                    TokenType::RightBrace => depth -= 1,
                    TokenType::EOF => return false,
                    _ => {}
                }
                pos += 1;
            }
        }

        // Skip an optional inline WHERE predicate (CIP-17/CIP-18), e.g.
        // `(a:A WHERE a.prop > x)`. The predicate runs to the node
        // pattern's own closing `)`, so scan there while balancing every
        // nested bracket kind; a `)` at depth zero ends the node pattern.
        if pos < self.tokens.len() && self.tokens[pos].ty == TokenType::WHERE {
            pos += 1;
            let mut depth = 0usize;
            loop {
                match self.tokens.get(pos).map(|t| t.ty) {
                    Some(TokenType::LeftParen | TokenType::LeftBracket | TokenType::LeftBrace) => {
                        depth += 1
                    }
                    Some(TokenType::RightParen) if depth == 0 => break,
                    Some(
                        TokenType::RightParen | TokenType::RightBracket | TokenType::RightBrace,
                    ) => {
                        if depth == 0 {
                            return false;
                        }
                        depth -= 1;
                    }
                    Some(TokenType::EOF) | None => return false,
                    Some(_) => {}
                }
                pos += 1;
            }
        }

        // Must see )
        if pos >= self.tokens.len() || self.tokens[pos].ty != TokenType::RightParen {
            return false;
        }
        pos += 1;

        // After ), must see - or <- (indicating a relationship/pattern)
        if pos < self.tokens.len() {
            matches!(self.tokens[pos].ty, TokenType::Dash | TokenType::ArrowLeft)
        } else {
            false
        }
    }

    /// Lookahead from the argument-start position without consuming tokens:
    /// true when a `|` appears at the argument's own paren depth before the
    /// paren that closes the current argument list. That pipe is the tail of
    /// the agent form `any((a)-[:R]->(b) | pred)` (LABS-201) -- a
    /// comprehension's map-expression separator misplaced outside any
    /// `[...]`, where no valid parse ever has one.
    fn pipe_before_closing_paren(&self) -> bool {
        self.top_level_token_before_matching_close(TokenType::Pipe, BracketSet::Parens)
    }

    pub(super) fn parse_pattern_comprehension_body(
        &mut self,
        path_var: Option<SmallName>,
    ) -> ParseResult<Expr> {
        // A pattern comprehension's inner pattern is its own pattern
        // context for the quantifier-mixing check: its quantifier forms
        // accumulate into the clause's comprehension-scoped flags instead
        // of combining with the clause's own forms (a legacy `[:R*1..2]`
        // inside a comprehension nested in a quantified path pattern's
        // WHERE is legal -- Neo4j QuantifiedPathPatternAcceptance -- while
        // two comprehensions' forms still combine with each other through
        // the shared accumulators). See
        // `quantifier_comprehension_saw_legacy_bracket`.
        let saved_legacy = self.side_effects.quantifier_saw_legacy_bracket;
        let saved_gpm = self.side_effects.quantifier_saw_gpm_form;
        self.side_effects.quantifier_saw_legacy_bracket = false;
        self.side_effects.quantifier_saw_gpm_form = false;
        let pattern = self.parse_pattern_path();
        let inner_legacy = self.side_effects.quantifier_saw_legacy_bracket;
        let inner_gpm = self.side_effects.quantifier_saw_gpm_form;
        self.side_effects.quantifier_saw_legacy_bracket = saved_legacy;
        self.side_effects.quantifier_saw_gpm_form = saved_gpm;
        self.side_effects
            .quantifier_comprehension_saw_legacy_bracket |= inner_legacy;
        self.side_effects.quantifier_comprehension_saw_gpm_form |= inner_gpm;
        let pattern = pattern?;

        let where_expr = if self.peek_type() == TokenType::WHERE {
            self.next_token();
            // A pattern comprehension always needs `| <map>`, so a `]` right
            // after the scanned label chain proves `|` was the separator.
            Some(self.parse_comprehension_where_expr(true)?)
        } else {
            None
        };

        self.expect(TokenType::Pipe)?;
        let map_expr = self.parse_expression()?;
        self.expect(TokenType::RightBracket)?;

        Ok(Expr::PatternComprehension(Box::new(
            PatternComprehensionExpr {
                path_variable: path_var,
                pattern,
                where_expr,
                map_expr,
            },
        )))
    }

    /// Parses the `WHERE`-part expression of a list/pattern comprehension
    /// with `comprehension_where_ambiguous_pipe` set, so a trailing `|` that
    /// can't validly continue a label-expression disjunction is left for the
    /// comprehension's own map-separator grammar instead of being consumed
    /// as part of the expression. See `label_or_pipe_is_ambiguous`.
    pub(super) fn parse_comprehension_where_expr(
        &mut self,
        map_required: bool,
    ) -> ParseResult<Expr> {
        let saved_flag = self.comprehension_where_ambiguous_pipe;
        let saved_map = self.comprehension_where_map_required;
        self.comprehension_where_ambiguous_pipe = true;
        self.comprehension_where_map_required = map_required;
        let result = self.parse_expression();
        self.comprehension_where_ambiguous_pipe = saved_flag;
        self.comprehension_where_map_required = saved_map;
        result
    }

    /// CIP-272 map comprehension, attempted from the `{` of a primary
    /// expression. Returns `Ok(None)` (position restored) when the tokens do
    /// not form one, so the caller falls back to the map-literal parse.
    /// Shapes: `{ident IN <src> [WHERE p] | <key> : <value>}` (list source)
    /// and `{ident : ident IN <src> [WHERE p] | <key> : <value>}` (map
    /// source, distinguished by the second ident before `IN`).
    pub(super) fn try_parse_map_comprehension(&mut self) -> ParseResult<Option<Expr>> {
        let start = self.save_pos();
        self.next_token(); // consume '{'

        let first = self.peek().clone();
        // The binding variable(s) are symbolic names, so any keyword
        // spelling works unquoted too (ADR-0191).
        if !first.ty.is_schema_name() {
            self.restore_pos(start);
            return Ok(None);
        }
        self.next_token(); // consume the binding identifier

        // List source: {item IN ...}
        if self.peek_type() == TokenType::IN {
            self.next_token();
            return self.finish_map_comprehension(
                start,
                None,
                SmallName::from_name(&first.literal),
            );
        }

        // Map source: {k : v IN ...}
        if self.peek_type() == TokenType::Colon {
            self.next_token();
            let second = self.peek().clone();
            if second.ty.is_schema_name() {
                self.next_token();
                if self.peek_type() == TokenType::IN {
                    self.next_token();
                    return self.finish_map_comprehension(
                        start,
                        Some(SmallName::from_name(&first.literal)),
                        SmallName::from_name(&second.literal),
                    );
                }
            }
        }

        self.restore_pos(start);
        Ok(None)
    }

    /// True when a `|` at the current brace nesting depth appears before the
    /// `}` that closes the comprehension `{`. Called with the current token
    /// immediately after the `IN` of a map comprehension (both CIP-272
    /// shapes), so `false` means no token run inside this brace can be the
    /// projection separator and the speculation is pointless. All bracket
    /// kinds nest (unlike the paren-only scans): the source expression
    /// inside the brace can itself contain brackets and parens.
    pub(super) fn has_pipe_before_matching_brace(&self) -> bool {
        self.top_level_token_before_matching_close(TokenType::Pipe, BracketSet::AllBrackets)
    }

    /// Shared tail of both CIP-272 shapes: the binding variable(s) and `IN`
    /// are consumed; parse source, optional WHERE, the `| key : value`
    /// projection, and the closing brace. Any structural mismatch restores
    /// the start position and yields `None` (the map-literal parse then
    /// reports its own error for genuinely malformed input).
    pub(super) fn finish_map_comprehension(
        &mut self,
        start: usize,
        key_var: Option<SmallName>,
        value_var: SmallName,
    ) -> ParseResult<Option<Expr>> {
        // Fail fast before the speculative parse below. The whole shape hinges on
        // a top-level `|` separating the source from the projection; when no such
        // token exists the speculative parse can only rewind and let the
        // map-literal fallback re-parse the same tokens, doubling the work per
        // nesting level for input such as `{a: b IN {a: b IN { ... }}}` -- i.e.
        // exponential parse time on untrusted input. One brace-depth-aware scan
        // rejects that shape up front, in O(tokens); a genuine comprehension
        // scans once and then parses once, exactly as before. A brace that does
        // carry a top-level `|` still takes the speculative path: the scan cannot
        // tell a well-formed projection from one with a malformed tail.
        if !self.has_pipe_before_matching_brace() {
            self.restore_pos(start);
            return Ok(None);
        }
        #[cfg(test)]
        SPECULATIVE_COMPREHENSION_PARSES.with(|c| c.set(c.get() + 1));

        // The source expression must stop at the comprehension's `|`: the
        // flag-guarded parse (same as a comprehension WHERE) refuses an
        // ambiguous trailing pipe, so `{k : v IN m | k : v}` does not try
        // to read `m | k` as a label disjunction.
        let source_expr = match self.parse_comprehension_where_expr(false) {
            Ok(e) => e,
            Err(_) => {
                self.restore_pos(start);
                return Ok(None);
            }
        };

        let where_expr = if self.peek_type() == TokenType::WHERE {
            self.next_token();
            match self.parse_comprehension_where_expr(false) {
                Ok(e) => Some(e),
                Err(_) => {
                    self.restore_pos(start);
                    return Ok(None);
                }
            }
        } else {
            None
        };

        if self.peek_type() != TokenType::Pipe {
            self.restore_pos(start);
            return Ok(None);
        }
        self.next_token();

        // The key expression is parsed at the arithmetic level
        // (`<arithmetic value expression>` in the CIP-272 grammar): a full
        // expression would swallow the `:` as the CIP-14 label predicate
        // (`'k': i` = HasLabel), which is exactly the ambiguity the CIP
        // resolves by restricting the key grammar.
        let key_expr = match self.parse_add_sub() {
            Ok(e) => e,
            Err(_) => {
                self.restore_pos(start);
                return Ok(None);
            }
        };
        if self.peek_type() != TokenType::Colon {
            self.restore_pos(start);
            return Ok(None);
        }
        self.next_token();
        let value_expr = match self.parse_expression() {
            Ok(e) => e,
            Err(_) => {
                self.restore_pos(start);
                return Ok(None);
            }
        };
        if self.peek_type() != TokenType::RightBrace {
            self.restore_pos(start);
            return Ok(None);
        }
        self.next_token();

        Ok(Some(Expr::MapComprehension(Box::new(
            MapComprehensionExpr {
                key_var,
                value_var,
                source_expr,
                where_expr,
                key_expr,
                value_expr,
            },
        ))))
    }

    pub(super) fn parse_map_literal(&mut self) -> ParseResult<Vec<MapPair>> {
        self.expect(TokenType::LeftBrace)?;
        let mut pairs = Vec::new();
        if self.peek_type() == TokenType::RightBrace {
            self.next_token();
            return Ok(pairs);
        }
        loop {
            let key_tok = self.next_token();
            // ADR-0191 point 5: an unquoted keyword is a map key too
            // (`{match: 1}`), so this reads through `is_schema_name()` --
            // the same predicate ADR-0169 uses for label/type names.
            if !key_tok.ty.is_schema_name() && key_tok.ty != TokenType::String {
                // A digit-leading key (`{1B2c3e67: 1}`) lexes as an
                // `InvalidNumberLiteral` error token, but in *map-key* position
                // the openCypher TCK classifies every invalid key as the generic
                // `UnexpectedSyntax` detail (Literals8 [19]–[27], SyntaxError
                // class), not `InvalidNumberLiteral`. Override the propagated
                // token detail with `UnexpectedSyntax` here; the same malformed
                // token in *expression* position (`RETURN 1B2c3e67`) keeps its
                // `InvalidNumberLiteral` detail because it never reaches this
                // key-parsing path.
                return Err(self
                    .error_at_token(
                        &key_tok,
                        format!(
                            "expected map key (identifier or string), got {:?}",
                            key_tok.literal
                        ),
                    )
                    .with_detail("UnexpectedSyntax"));
            }
            self.expect(TokenType::Colon)?;
            let val = self.parse_expression()?;
            pairs.push(MapPair {
                key: SmallName::from_name(&key_tok.literal),
                value: val,
            });
            if self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        self.expect(TokenType::RightBrace)?;
        Ok(pairs)
    }

    /// Parses a `<map projection>` filler (the current token must be `{`):
    /// `{ .*, .prop, variable, key: expr, ... }`.
    pub(super) fn parse_map_projection_items(&mut self) -> ParseResult<Vec<MapProjectionItem>> {
        self.expect(TokenType::LeftBrace)?;
        let mut items = Vec::new();
        if self.peek_type() == TokenType::RightBrace {
            self.next_token();
            return Ok(items);
        }
        loop {
            if self.peek_type() == TokenType::Dot {
                self.next_token(); // consume .
                if self.peek_type() == TokenType::Star {
                    self.next_token();
                    items.push(MapProjectionItem::AllProperties);
                } else {
                    // ADR-0191 point 5: keywords are map-projection
                    // selectors too (`n{.match}`, `n{match}`).
                    let prop =
                        self.parse_schema_name("a property name after '.' in map projection")?;
                    items.push(MapProjectionItem::Property(prop));
                }
            } else {
                let name = self.parse_schema_name("a map projection item")?;
                if self.peek_type() == TokenType::Colon {
                    self.next_token();
                    let value = self.parse_expression()?;
                    items.push(MapProjectionItem::KeyValue(name, value));
                } else {
                    items.push(MapProjectionItem::Variable(name));
                }
            }
            if self.peek_type() != TokenType::Comma {
                break;
            }
            self.next_token();
        }
        self.expect(TokenType::RightBrace)?;
        Ok(items)
    }

    /// Called with `{` as the current token, immediately after a
    /// subquery-introducing keyword (`EXISTS`/`COUNT`/`COLLECT`). Returns
    /// true if the filler looks like a `<map projection>` (the keyword
    /// being used as an ordinary bound variable) rather than subquery
    /// content: a subquery's `{...}` must start with `(` (a bare pattern)
    /// or a clause keyword (MATCH/WITH/RETURN/...), neither of which a map
    /// projection filler (`.prop`, `.*`, a bare selector variable, or
    /// `key: expr`) can also start with, so one token of extra lookahead
    /// past that disambiguates with no backtracking (CIP-190
    /// near-ambiguities.feature [2]).
    ///
    /// ADR-0191 point 5: the item read through `is_schema_name()`, so a
    /// keyword spelling is a map-projection item too (`n {match: 1}`,
    /// `n {match}`, `n {.match}`). A subquery body starting with a clause
    /// keyword (`EXISTS { MATCH ... }`, `COUNT { DELETE n }`) still fails
    /// the two-token lookahead (`(`/an operand after the keyword, not
    /// `:`/`,`/`}`), so subquery classification is unchanged.
    pub(super) fn peek_brace_is_map_projection(&self) -> bool {
        match self.peek_at(1).ty {
            TokenType::Dot => true,
            ty if ty.is_schema_name() => matches!(
                self.peek_at(2).ty,
                TokenType::Colon | TokenType::Comma | TokenType::RightBrace
            ),
            _ => false,
        }
    }

    /// Shared head of `reduce` and `allReduce`: parses
    /// `( acc = init, var IN list | expr` with the function-name token
    /// already consumed by the caller, leaving the cursor just after the
    /// per-element expression. `function_name` only shapes the error text;
    /// the two forms differ solely in their tail after `| expr`.
    fn parse_reduce_head(&mut self, function_name: &str) -> ParseResult<ReduceHead> {
        self.expect(TokenType::LeftParen)?;

        // The accumulator and loop variables are symbolic names, so any
        // keyword spelling works unquoted too (ADR-0191).
        let accumulator =
            self.parse_schema_name(&format!("accumulator variable in {function_name}()"))?;
        self.expect(TokenType::Equals)?;
        let init_expr = self.parse_expression()?;
        self.expect(TokenType::Comma)?;

        let variable = self.parse_schema_name(&format!("variable in {function_name}()"))?;
        self.expect(TokenType::IN)?;
        let list_expr = self.parse_expression()?;
        self.expect(TokenType::Pipe)?;
        let expression = self.parse_expression()?;

        Ok(ReduceHead {
            accumulator,
            init_expr,
            variable,
            list_expr,
            expression,
        })
    }

    pub(super) fn parse_reduce_expr(&mut self) -> ParseResult<Expr> {
        self.next_token(); // consume REDUCE
        let ReduceHead {
            accumulator,
            init_expr,
            variable,
            list_expr,
            expression,
        } = self.parse_reduce_head("reduce")?;
        self.expect(TokenType::RightParen)?;

        Ok(Expr::Reduce(Box::new(ReduceExpr {
            accumulator,
            init_expr,
            variable,
            list_expr,
            expression,
        })))
    }

    pub(super) fn parse_allreduce_expr(&mut self) -> ParseResult<Expr> {
        // The 'allReduce' identifier token has already been consumed by the caller.
        let ReduceHead {
            accumulator,
            init_expr,
            variable,
            list_expr,
            expression,
        } = self.parse_reduce_head("allReduce")?;
        self.expect(TokenType::Comma)?;
        let predicate = self.parse_expression()?;
        self.expect(TokenType::RightParen)?;

        Ok(Expr::AllReduce(Box::new(AllReduceExpr {
            accumulator,
            init_expr,
            variable,
            list_expr,
            expression,
            predicate,
        })))
    }

    pub(super) fn parse_pattern_predicate(&mut self) -> ParseResult<Expr> {
        let path = self.parse_pattern_path()?;
        Ok(Expr::PatternPredicate(Box::new(PatternPredicateExpr {
            pattern: path,
        })))
    }
}

/// CIP-213: an arm's true terminal stage is the end of its own NEXT
/// chain, if any — not its own first stage's clause list. Shared by the
/// UNION-arm shape checks (`has_return`, `return_columns`) and the
/// COLLECT-subquery single-return-column check.
fn tail_stage(s: &Statement) -> &Statement {
    let mut t = s;
    while let Some(next) = &t.next {
        t = next;
    }
    t
}

/// The bracket kinds that count toward nesting in
/// [`Parser::top_level_token_before_matching_close`] — an explicit,
/// per-site choice, so a paren-only scan (a call's argument list) and an
/// all-bracket scan (a comprehension brace) cannot be silently confused.
#[derive(Clone, Copy)]
pub(super) enum BracketSet {
    /// Only `(` / `)` nest: the scan runs inside a call's argument list.
    Parens,
    /// `{`, `[`, and `(` all nest: the scan runs inside a comprehension
    /// brace, whose source expression can contain brackets and parens.
    AllBrackets,
}

impl BracketSet {
    /// True when `ty` is an opening bracket of one of this set's kinds.
    pub(super) fn opens(self, ty: TokenType) -> bool {
        match self {
            BracketSet::Parens => ty == TokenType::LeftParen,
            BracketSet::AllBrackets => matches!(
                ty,
                TokenType::LeftBrace | TokenType::LeftBracket | TokenType::LeftParen
            ),
        }
    }

    /// True when `ty` is a closing bracket of one of this set's kinds.
    pub(super) fn closes(self, ty: TokenType) -> bool {
        match self {
            BracketSet::Parens => ty == TokenType::RightParen,
            BracketSet::AllBrackets => matches!(
                ty,
                TokenType::RightBrace | TokenType::RightBracket | TokenType::RightParen
            ),
        }
    }
}