qusql-parse 0.4.0

Parser for sql
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
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{
    DataType, Identifier, QualifiedName, SString, Span, Spanned, Statement,
    data_type::{DataTypeContext, parse_data_type},
    function_expression::{
        AggregateFunctionCallExpression, CharFunctionExpression, Function, FunctionCallExpression,
        WindowFunctionCallExpression, is_aggregate_function_ident, parse_aggregate_function,
        parse_char_function, parse_function, parse_function_call,
    },
    keywords::{Keyword, Restrict},
    lexer::Token,
    operator::parse_operator_name,
    parser::{ParseError, Parser},
    span::OptSpanned,
    statement::parse_compound_query,
};
use alloc::string::ToString;
use alloc::vec;
use alloc::{boxed::Box, vec::Vec};

/// Function to execute
#[derive(Debug, Clone)]
pub enum Variable<'a> {
    TimeZone,
    Other(&'a str),
}

/// Binary operator to apply
#[derive(Debug, Clone)]
pub enum BinaryOperator<'a> {
    Or(Span),
    Xor(Span),
    And(Span),
    Eq(Span),
    NullSafeEq(Span),
    GtEq(Span),
    Gt(Span),
    LtEq(Span),
    Lt(Span),
    Neq(Span),
    ShiftLeft(Span),
    ShiftRight(Span),
    BitAnd(Span),
    BitOr(Span),
    BitXor(Span),
    Add(Span),
    Subtract(Span),
    Divide(Span),
    Div(Span),
    Mod(Span),
    Mult(Span),
    Like(Span),
    NotLike(Span),
    Regexp(Span),
    NotRegexp(Span),
    Rlike(Span),
    NotRlike(Span),
    Collate(Span),
    JsonExtract(Span),
    JsonExtractUnquote(Span),
    Assignment(Span),
    /// String/array concatenation `||`
    Concat(Span),
    // PostgreSQL-specific binary operators
    /// @>
    Contains(Span),
    /// <@
    ContainedBy(Span),
    /// @@ (full-text / jsonpath match)
    JsonPathMatch(Span),
    /// @?
    JsonPathExists(Span),
    /// ? (jsonb key exists)
    JsonbKeyExists(Span),
    /// ?|
    JsonbAnyKeyExists(Span),
    /// ?&
    JsonbAllKeyExists(Span),
    /// #>
    JsonGetPath(Span),
    /// #>>
    JsonGetPathText(Span),
    /// #-
    JsonDeletePath(Span),
    /// ~ (regex match)
    RegexMatch(Span),
    /// ~* (case-insensitive regex match)
    RegexIMatch(Span),
    /// !~ (regex not match)
    NotRegexMatch(Span),
    /// !~* (case-insensitive regex not match)
    NotRegexIMatch(Span),
    /// User-defined / unrecognised PostgreSQL operator
    User(&'a str, Span),
    /// PostgreSQL OPERATOR(schema.op) expression
    Operator(QualifiedName<'a>, Span),
}

impl<'a> Spanned for BinaryOperator<'a> {
    fn span(&self) -> Span {
        match self {
            BinaryOperator::Or(s)
            | BinaryOperator::Xor(s)
            | BinaryOperator::And(s)
            | BinaryOperator::Eq(s)
            | BinaryOperator::NullSafeEq(s)
            | BinaryOperator::GtEq(s)
            | BinaryOperator::Gt(s)
            | BinaryOperator::LtEq(s)
            | BinaryOperator::Lt(s)
            | BinaryOperator::Neq(s)
            | BinaryOperator::ShiftLeft(s)
            | BinaryOperator::ShiftRight(s)
            | BinaryOperator::BitAnd(s)
            | BinaryOperator::BitOr(s)
            | BinaryOperator::BitXor(s)
            | BinaryOperator::Add(s)
            | BinaryOperator::Subtract(s)
            | BinaryOperator::Divide(s)
            | BinaryOperator::Div(s)
            | BinaryOperator::Mod(s)
            | BinaryOperator::Mult(s)
            | BinaryOperator::Like(s)
            | BinaryOperator::NotLike(s)
            | BinaryOperator::Regexp(s)
            | BinaryOperator::NotRegexp(s)
            | BinaryOperator::Rlike(s)
            | BinaryOperator::NotRlike(s)
            | BinaryOperator::Collate(s)
            | BinaryOperator::JsonExtract(s)
            | BinaryOperator::JsonExtractUnquote(s)
            | BinaryOperator::Assignment(s)
            | BinaryOperator::Concat(s)
            | BinaryOperator::Contains(s)
            | BinaryOperator::ContainedBy(s)
            | BinaryOperator::JsonPathMatch(s)
            | BinaryOperator::JsonPathExists(s)
            | BinaryOperator::JsonbKeyExists(s)
            | BinaryOperator::JsonbAnyKeyExists(s)
            | BinaryOperator::JsonbAllKeyExists(s)
            | BinaryOperator::JsonGetPath(s)
            | BinaryOperator::JsonGetPathText(s)
            | BinaryOperator::JsonDeletePath(s)
            | BinaryOperator::RegexMatch(s)
            | BinaryOperator::RegexIMatch(s)
            | BinaryOperator::NotRegexMatch(s)
            | BinaryOperator::NotRegexIMatch(s) => s.clone(),
            BinaryOperator::User(_, s) => s.clone(),
            BinaryOperator::Operator(_, s) => s.clone(),
        }
    }
}

/// Mode for MATCH ... AGAINST
#[derive(Debug, Clone)]
pub enum MatchMode {
    InBoolean(Span),
    InNaturalLanguage(Span),
    InNaturalLanguageWithQueryExpansion(Span),
    WithQueryExpansion(Span),
}

impl Spanned for MatchMode {
    fn span(&self) -> Span {
        match self {
            MatchMode::InBoolean(s) => s.clone(),
            MatchMode::InNaturalLanguage(s) => s.clone(),
            MatchMode::InNaturalLanguageWithQueryExpansion(s) => s.clone(),
            MatchMode::WithQueryExpansion(s) => s.clone(),
        }
    }
}

/// Type of is expression
#[derive(Debug, Clone)]
pub enum Is<'a> {
    Null,
    NotNull,
    True,
    NotTrue,
    False,
    NotFalse,
    Unknown,
    NotUnknown,
    DistinctFrom(Expression<'a>),
    NotDistinctFrom(Expression<'a>),
}

/// Unary operator to apply
#[derive(Debug, Clone)]
pub enum UnaryOperator {
    Binary(Span),
    LogicalNot(Span),
    Minus(Span),
    Not(Span),
}

impl Spanned for UnaryOperator {
    fn span(&self) -> Span {
        match self {
            UnaryOperator::Binary(s)
            | UnaryOperator::LogicalNot(s)
            | UnaryOperator::Minus(s)
            | UnaryOperator::Not(s) => s.clone(),
        }
    }
}

/// Part of a full identifier
#[derive(Debug, Clone)]
pub enum IdentifierPart<'a> {
    Name(Identifier<'a>),
    Star(Span),
}

impl<'a> Spanned for IdentifierPart<'a> {
    fn span(&self) -> Span {
        match &self {
            IdentifierPart::Name(v) => v.span(),
            IdentifierPart::Star(v) => v.span(),
        }
    }
}

/// When part of CASE
#[derive(Debug, Clone)]
pub struct When<'a> {
    /// Span of WHEN
    pub when_span: Span,
    /// When to return then
    pub when: Expression<'a>,
    /// Span of THEN
    pub then_span: Span,
    /// What to return when when applyes
    pub then: Expression<'a>,
}

impl<'a> Spanned for When<'a> {
    fn span(&self) -> Span {
        self.when_span
            .join_span(&self.when)
            .join_span(&self.then_span)
            .join_span(&self.then)
    }
}

/// Units of time
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimeUnit {
    /// Microseconds
    Microsecond,
    /// Seconds
    Second,
    /// Minutes
    Minute,
    /// Hours
    Hour,
    /// Days
    Day,
    /// Weeks
    Week,
    /// Months
    Month,
    /// Quarters
    Quarter,
    /// Years
    Year,
    /// Seconds.Microseconds
    SecondMicrosecond,
    /// Minutes.Seconds.Microseconds
    MinuteMicrosecond,
    /// Minutes.Seconds
    MinuteSecond,
    /// Hours.Minutes.Seconds.Microseconds
    HourMicrosecond,
    /// Hours.Minutes.Seconds
    HourSecond,
    /// Hours.Minutes
    HourMinute,
    /// Days Hours.Minutes.Seconds.Microseconds
    DayMicrosecond,
    /// Days Hours.Minutes.Seconds
    DaySecond,
    /// Days Hours.Minutes
    DayMinute,
    /// Days Hours
    DayHour,
    /// Years-Months
    YearMonth,
    /// PostgreSQL: epoch (seconds since 1970-01-01)
    Epoch,
    /// PostgreSQL: day of week (0=Sunday)
    Dow,
    /// PostgreSQL: day of year
    Doy,
    /// PostgreSQL: century
    Century,
    /// PostgreSQL: decade
    Decade,
    /// PostgreSQL: ISO day of week (1=Monday)
    IsoDow,
    /// PostgreSQL: ISO year
    IsoYear,
    /// PostgreSQL: Julian day
    Julian,
    /// PostgreSQL: millennium
    Millennium,
    /// PostgreSQL: timezone offset in seconds
    Timezone,
    /// PostgreSQL: timezone hours component
    TimezoneHour,
    /// PostgreSQL: timezone minutes component
    TimezoneMinute,
}

fn parse_time_unit_from_str(s: &str) -> Option<TimeUnit> {
    match s.to_ascii_lowercase().trim_end_matches('s') {
        "microsecond" => Some(TimeUnit::Microsecond),
        "second" => Some(TimeUnit::Second),
        "minute" => Some(TimeUnit::Minute),
        "hour" => Some(TimeUnit::Hour),
        "day" => Some(TimeUnit::Day),
        "week" => Some(TimeUnit::Week),
        "month" => Some(TimeUnit::Month),
        "quarter" => Some(TimeUnit::Quarter),
        "year" => Some(TimeUnit::Year),
        "epoch" => Some(TimeUnit::Epoch),
        "dow" => Some(TimeUnit::Dow),
        "doy" => Some(TimeUnit::Doy),
        "century" | "centurie" => Some(TimeUnit::Century),
        "decade" => Some(TimeUnit::Decade),
        "isodow" => Some(TimeUnit::IsoDow),
        "isoyear" => Some(TimeUnit::IsoYear),
        "julian" => Some(TimeUnit::Julian),
        "millennium" | "millennia" | "millenniu" => Some(TimeUnit::Millennium),
        "timezone" => Some(TimeUnit::Timezone),
        "timezone_hour" => Some(TimeUnit::TimezoneHour),
        "timezone_minute" => Some(TimeUnit::TimezoneMinute),
        _ => None,
    }
}

fn parse_time_unit(t: &Token<'_>) -> Option<TimeUnit> {
    match t {
        Token::Ident(_, Keyword::MICROSECOND) => Some(TimeUnit::Microsecond),
        Token::Ident(_, Keyword::SECOND) => Some(TimeUnit::Second),
        Token::Ident(_, Keyword::MINUTE) => Some(TimeUnit::Minute),
        Token::Ident(_, Keyword::HOUR) => Some(TimeUnit::Hour),
        Token::Ident(_, Keyword::DAY) => Some(TimeUnit::Day),
        Token::Ident(_, Keyword::WEEK) => Some(TimeUnit::Week),
        Token::Ident(_, Keyword::MONTH) => Some(TimeUnit::Month),
        Token::Ident(_, Keyword::QUARTER) => Some(TimeUnit::Quarter),
        Token::Ident(_, Keyword::YEAR) => Some(TimeUnit::Year),
        Token::Ident(_, Keyword::SECOND_MICROSECOND) => Some(TimeUnit::SecondMicrosecond),
        Token::Ident(_, Keyword::MINUTE_MICROSECOND) => Some(TimeUnit::MinuteMicrosecond),
        Token::Ident(_, Keyword::MINUTE_SECOND) => Some(TimeUnit::MinuteSecond),
        Token::Ident(_, Keyword::HOUR_MICROSECOND) => Some(TimeUnit::HourMicrosecond),
        Token::Ident(_, Keyword::HOUR_SECOND) => Some(TimeUnit::HourSecond),
        Token::Ident(_, Keyword::HOUR_MINUTE) => Some(TimeUnit::HourMinute),
        Token::Ident(_, Keyword::DAY_MICROSECOND) => Some(TimeUnit::DayMicrosecond),
        Token::Ident(_, Keyword::DAY_SECOND) => Some(TimeUnit::DaySecond),
        Token::Ident(_, Keyword::DAY_MINUTE) => Some(TimeUnit::DayMinute),
        Token::Ident(_, Keyword::DAY_HOUR) => Some(TimeUnit::DayHour),
        Token::Ident(_, Keyword::YEAR_MONTH) => Some(TimeUnit::YearMonth),
        Token::Ident(s, Keyword::NOT_A_KEYWORD) => parse_time_unit_from_str(s),
        _ => None,
    }
}

/// Expression with binary operator
#[derive(Debug, Clone)]
pub struct BinaryExpression<'a> {
    pub op: BinaryOperator<'a>,
    pub lhs: Expression<'a>,
    pub rhs: Expression<'a>,
}

impl Spanned for BinaryExpression<'_> {
    fn span(&self) -> Span {
        self.op.span().join_span(&self.lhs).join_span(&self.rhs)
    }
}

/// Expression with a unary (prefix) operator
#[derive(Debug, Clone)]
pub struct UnaryExpression<'a> {
    pub op: UnaryOperator,
    pub operand: Expression<'a>,
}

impl Spanned for UnaryExpression<'_> {
    fn span(&self) -> Span {
        self.op.span().join_span(&self.operand)
    }
}
/// Time Interval
#[derive(Debug, Clone)]
pub struct IntervalExpression {
    /// Span of "INTERVAL"
    pub interval_span: Span,
    /// Time internal
    pub time_interval: (Vec<i64>, Span),
    /// Unit of the time interval
    pub time_unit: (TimeUnit, Span),
}

impl Spanned for IntervalExpression {
    fn span(&self) -> Span {
        self.interval_span
            .join_span(&self.time_interval.1)
            .join_span(&self.time_unit.1)
    }
}

/// Extract expression
#[derive(Debug, Clone)]
pub struct ExtractExpression<'a> {
    /// Span of "EXTRACT"
    pub extract_span: Span,
    /// Unit of the time interval
    pub time_unit: (TimeUnit, Span),
    /// Span of "FROM"
    pub from_span: Span,
    /// Date expression
    pub date: Expression<'a>,
}

impl Spanned for ExtractExpression<'_> {
    fn span(&self) -> Span {
        self.extract_span
            .join_span(&self.time_unit.1)
            .join_span(&self.from_span)
            .join_span(&self.date)
    }
}

/// Direction for TRIM()
#[derive(Debug, Clone)]
pub enum TrimDirection {
    Both(Span),
    Leading(Span),
    Trailing(Span),
}

impl Spanned for TrimDirection {
    fn span(&self) -> Span {
        match self {
            TrimDirection::Both(s) | TrimDirection::Leading(s) | TrimDirection::Trailing(s) => {
                s.clone()
            }
        }
    }
}

/// TRIM([{BOTH|LEADING|TRAILING} [remstr] FROM] str) expression
#[derive(Debug, Clone)]
pub struct TrimExpression<'a> {
    /// Span of "TRIM"
    pub trim_span: Span,
    /// Optional BOTH / LEADING / TRAILING direction
    pub direction: Option<TrimDirection>,
    /// Optional removal string (remstr)
    pub what: Option<Expression<'a>>,
    /// Span of "FROM" when present
    pub from_span: Option<Span>,
    /// The string to trim
    pub value: Expression<'a>,
}

impl Spanned for TrimExpression<'_> {
    fn span(&self) -> Span {
        self.trim_span
            .join_span(&self.direction)
            .join_span(&self.what)
            .join_span(&self.from_span)
            .join_span(&self.value)
    }
}

/// In expression
#[derive(Debug, Clone)]
pub struct InExpression<'a> {
    /// Left hand side expression
    pub lhs: Expression<'a>,
    /// Right hand side expression
    pub rhs: Vec<Expression<'a>>,
    /// Span of "IN" or "NOT IN"
    pub in_span: Span,
    /// True if not in
    pub not_in: bool,
}

impl Spanned for InExpression<'_> {
    fn span(&self) -> Span {
        self.in_span.join_span(&self.lhs).join_span(&self.rhs)
    }
}

/// Between expression (expr BETWEEN low AND high)
#[derive(Debug, Clone)]
pub struct BetweenExpression<'a> {
    /// The value being tested
    pub lhs: Expression<'a>,
    /// Lower bound
    pub low: Expression<'a>,
    /// Upper bound
    pub high: Expression<'a>,
    /// Span covering "BETWEEN ... AND"
    pub between_span: Span,
    /// True if NOT BETWEEN
    pub not_between: bool,
}

impl Spanned for BetweenExpression<'_> {
    fn span(&self) -> Span {
        self.between_span
            .join_span(&self.lhs)
            .join_span(&self.low)
            .join_span(&self.high)
    }
}

/// Member of expression
#[derive(Debug, Clone)]
pub struct MemberOfExpression<'a> {
    /// Left hand side expression
    pub lhs: Expression<'a>,
    /// Right hand side expression
    pub rhs: Expression<'a>,
    /// Span of "MEMBER OF"
    pub member_of_span: Span,
}

impl Spanned for MemberOfExpression<'_> {
    fn span(&self) -> Span {
        self.member_of_span
            .join_span(&self.lhs)
            .join_span(&self.rhs)
    }
}

/// Case expression
#[derive(Debug, Clone)]
pub struct CaseExpression<'a> {
    /// Span of "CASE"
    pub case_span: Span,
    /// Optional value to switch over
    pub value: Option<Expression<'a>>,
    /// When parts
    pub whens: Vec<When<'a>>,
    /// Span of "ELSE" and else value if specified
    pub else_: Option<(Span, Expression<'a>)>,
    /// Span of "END"
    pub end_span: Span,
}

impl Spanned for CaseExpression<'_> {
    fn span(&self) -> Span {
        self.case_span
            .join_span(&self.value)
            .join_span(&self.whens)
            .join_span(&self.else_)
            .join_span(&self.end_span)
    }
}

/// Cast expression
#[derive(Debug, Clone)]
pub struct CastExpression<'a> {
    /// Span of "CAST"
    pub cast_span: Span,
    /// Value to cast
    pub expr: Expression<'a>,
    /// Span of "AS"
    pub as_span: Span,
    /// Type to cast to
    pub type_: DataType<'a>,
}

impl Spanned for CastExpression<'_> {
    fn span(&self) -> Span {
        self.cast_span
            .join_span(&self.expr)
            .join_span(&self.as_span)
            .join_span(&self.type_)
    }
}

/// Convert expression (CONVERT(expr, type) or CONVERT(expr USING charset))
#[derive(Debug, Clone)]
pub struct ConvertExpression<'a> {
    /// Span of "CONVERT"
    pub convert_span: Span,
    /// Value to convert
    pub expr: Expression<'a>,
    /// Type to convert to (for CONVERT(expr, type))
    pub type_: Option<DataType<'a>>,
    /// Charset (for CONVERT(expr USING charset))
    pub using_charset: Option<(Span, Identifier<'a>)>,
}

impl Spanned for ConvertExpression<'_> {
    fn span(&self) -> Span {
        self.convert_span
            .join_span(&self.expr)
            .join_span(&self.type_)
            .join_span(&self.using_charset)
    }
}

/// PostgreSQL-style typecast expression (expr::type)
#[derive(Debug, Clone)]
pub struct TypeCastExpression<'a> {
    /// The expression being cast
    pub expr: Expression<'a>,
    /// Span of "::"
    pub doublecolon_span: Span,
    /// Type to cast to
    pub type_: DataType<'a>,
}

impl Spanned for TypeCastExpression<'_> {
    fn span(&self) -> Span {
        self.expr
            .span()
            .join_span(&self.doublecolon_span)
            .join_span(&self.type_)
    }
}

/// PostgreSQL ARRAY[...] literal expression
#[derive(Debug, Clone)]
pub struct ArrayExpression<'a> {
    /// Span of the "ARRAY" keyword
    pub array_span: Span,
    /// Span of the bracket region "[...]"
    pub bracket_span: Span,
    /// The element expressions
    pub elements: Vec<Expression<'a>>,
}

impl Spanned for ArrayExpression<'_> {
    fn span(&self) -> Span {
        self.array_span.join_span(&self.bracket_span)
    }
}

/// Array subscript or slice expression: expr[idx] or expr[lower:upper]
#[derive(Debug, Clone)]
pub struct ArraySubscriptExpression<'a> {
    /// The array expression being subscripted
    pub expr: Expression<'a>,
    /// Span of the "[...]" bracket region
    pub bracket_span: Span,
    /// The lower bound / index
    pub lower: Expression<'a>,
    /// The upper bound for slice notation (expr[lower:upper])
    pub upper: Option<Expression<'a>>,
}

impl Spanned for ArraySubscriptExpression<'_> {
    fn span(&self) -> Span {
        self.expr.span().join_span(&self.bracket_span)
    }
}

/// PostgreSQL composite type field access: (expr).field
#[derive(Debug, Clone)]
pub struct FieldAccessExpression<'a> {
    /// The expression whose field is accessed
    pub expr: Expression<'a>,
    /// Span of the "."
    pub dot_span: Span,
    /// The field name
    pub field: Identifier<'a>,
}

impl Spanned for FieldAccessExpression<'_> {
    fn span(&self) -> Span {
        self.expr
            .span()
            .join_span(&self.dot_span)
            .join_span(&self.field)
    }
}

/// Group contat expression
#[derive(Debug, Clone)]
pub struct GroupConcatExpression<'a> {
    /// Span of "GROUP_CONCAT"
    pub group_concat_span: Span,
    /// Span of "DISTINCT" if specified
    pub distinct_span: Option<Span>,
    /// Expression to count
    pub expr: Expression<'a>,
}

impl Spanned for GroupConcatExpression<'_> {
    fn span(&self) -> Span {
        self.group_concat_span
            .join_span(&self.distinct_span)
            .join_span(&self.expr)
    }
}

/// Variable expression
#[derive(Debug, Clone)]
pub struct VariableExpression<'a> {
    /// Span of "@@GLOBAL"
    pub global: Option<Span>,
    /// Span of "@@SESSION"
    pub session: Option<Span>,
    /// Span of '.'
    pub dot: Option<Span>,
    /// variable
    pub variable: Variable<'a>,
    // Span of variable
    pub variable_span: Span,
}

impl Spanned for VariableExpression<'_> {
    fn span(&self) -> Span {
        self.variable_span
            .join_span(&self.global)
            .join_span(&self.session)
            .join_span(&self.dot)
    }
}

/// User variable expression (@variable_name)
#[derive(Debug, Clone)]
pub struct UserVariableExpression<'a> {
    /// The variable name
    pub name: Identifier<'a>,
    /// Span of '@'
    pub at_span: Span,
}

impl Spanned for UserVariableExpression<'_> {
    fn span(&self) -> Span {
        self.at_span.join_span(&self.name)
    }
}

/// Timestampadd call
#[derive(Debug, Clone)]
pub struct TimestampAddExpression<'a> {
    /// Span of "TIMESTAMPADD"
    pub timestamp_add_span: Span,
    /// Unit of the interval
    pub unit: (TimeUnit, Span),
    /// Interval expression
    pub interval: Expression<'a>,
    /// Datetime expression
    pub datetime: Expression<'a>,
}

impl Spanned for TimestampAddExpression<'_> {
    fn span(&self) -> Span {
        self.timestamp_add_span
            .join_span(&self.unit.1)
            .join_span(&self.interval)
            .join_span(&self.datetime)
    }
}

/// Timestampdiff call
#[derive(Debug, Clone)]
pub struct TimestampDiffExpression<'a> {
    /// Span of "TIMESTAMPDIFF"
    pub timestamp_diff_span: Span,
    /// Unit of the interval
    pub unit: (TimeUnit, Span),
    /// First expression
    pub e1: Expression<'a>,
    /// Second expression
    pub e2: Expression<'a>,
}

impl Spanned for TimestampDiffExpression<'_> {
    fn span(&self) -> Span {
        self.timestamp_diff_span
            .join_span(&self.unit.1)
            .join_span(&self.e1)
            .join_span(&self.e2)
    }
}

/// Full-text MATCH ... AGAINST expression
#[derive(Debug, Clone)]
pub struct MatchAgainstExpression<'a> {
    /// Span of "MATCH"
    pub match_span: Span,
    /// Columns to match against
    pub columns: Vec<Expression<'a>>,
    /// Span of "AGAINST"
    pub against_span: Span,
    /// Expression to match against
    pub expr: Expression<'a>,
    /// Match mode
    pub mode: Option<MatchMode>,
}

impl Spanned for MatchAgainstExpression<'_> {
    fn span(&self) -> Span {
        self.match_span
            .join_span(&self.columns)
            .join_span(&self.against_span)
            .join_span(&self.expr)
            .join_span(&self.mode)
    }
}

/// Is expression
#[derive(Debug, Clone)]
pub struct IsExpression<'a> {
    /// Left hand side expression
    pub lhs: Expression<'a>,
    /// Type of is expression
    pub is: Is<'a>,
    /// Span of "IS" and "NOT"
    pub is_span: Span,
}

impl<'a> Spanned for IsExpression<'a> {
    fn span(&self) -> Span {
        match &self.is {
            Is::DistinctFrom(rhs) | Is::NotDistinctFrom(rhs) => {
                self.lhs.span().join_span(&self.is_span).join_span(rhs)
            }
            _ => self.lhs.span().join_span(&self.is_span),
        }
    }
}

/// Literal NULL expression
#[derive(Debug, Clone)]
pub struct NullExpression {
    /// Span of "NULL"
    pub span: Span,
}

impl Spanned for NullExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Literal DEFAULT expression
#[derive(Debug, Clone)]
pub struct DefaultExpression {
    /// Span of "DEFAULT"
    pub span: Span,
}

impl Spanned for DefaultExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Literal bool expression "TRUE" or "FALSE"
#[derive(Debug, Clone)]
pub struct BoolExpression {
    /// The boolean value
    pub value: bool,
    /// Span of "TRUE" or "FALSE"
    pub span: Span,
}

impl Spanned for BoolExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Literal integer expression
#[derive(Debug, Clone)]
pub struct IntegerExpression {
    /// The integer value
    pub value: u64,
    /// Span of the integer
    pub span: Span,
}

impl Spanned for IntegerExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Literal _LIST_ expression
#[derive(Debug, Clone)]
pub struct ListHackExpression {
    /// The index of the list
    pub index: usize,
    /// Span of the list
    pub span: Span,
}

impl Spanned for ListHackExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Literal floating point expression
#[derive(Debug, Clone)]
pub struct FloatExpression {
    /// The floating point value
    pub value: f64,
    /// Span of the floating point
    pub span: Span,
}

impl Spanned for FloatExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Input argument to query, the first argument is the occurrence number of the argument
#[derive(Debug, Clone)]
pub struct ArgExpression {
    /// The occurrence number of the argument
    pub index: usize,
    /// Span of the argument
    pub span: Span,
}

impl Spanned for ArgExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Invalid expression, returned on recovery of a parse error
#[derive(Debug, Clone)]
pub struct InvalidExpression {
    /// Span of the invalid expression
    pub span: Span,
}

impl Spanned for InvalidExpression {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

/// Identifier pointing to column
#[derive(Debug, Clone)]
pub struct IdentifierExpression<'a> {
    /// The identifier  parts, for example in "a.b.*" the parts are "a", "b" and "*"
    pub parts: Vec<IdentifierPart<'a>>,
}

impl<'a> Spanned for IdentifierExpression<'a> {
    fn span(&self) -> Span {
        self.parts.opt_span().expect("Span of identifier parts")
    }
}

/// Subquery expression
#[derive(Debug, Clone)]
pub struct SubqueryExpression<'a> {
    /// The subquery
    pub expression: Statement<'a>,
}

impl Spanned for SubqueryExpression<'_> {
    fn span(&self) -> Span {
        self.expression.span()
    }
}

/// Exists expression
#[derive(Debug, Clone)]
pub struct ExistsExpression<'a> {
    /// Span of "EXISTS"
    pub exists_span: Span,
    /// The subquery
    pub subquery: Statement<'a>,
}

impl Spanned for ExistsExpression<'_> {
    fn span(&self) -> Span {
        self.exists_span.join_span(&self.subquery)
    }
}

/// Which row quantifier keyword was used
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Quantifier {
    /// ANY(subquery_or_array)
    Any(Span),
    /// SOME(subquery_or_array) — synonym for ANY in PostgreSQL
    Some(Span),
    /// ALL(subquery_or_array)
    All(Span),
}

impl Spanned for Quantifier {
    fn span(&self) -> Span {
        match self {
            Quantifier::Any(s) | Quantifier::Some(s) | Quantifier::All(s) => s.clone(),
        }
    }
}

/// PostgreSQL ANY / SOME / ALL quantifier expression.
///
/// Appears as the right-hand operand of a comparison:
/// `expr op ANY (subquery_or_array)`
#[derive(Debug, Clone)]
pub struct QuantifierExpression<'a> {
    /// Which quantifier keyword was written
    pub quantifier: Quantifier,
    /// The operand — either a subquery expression or an array expression
    pub operand: Expression<'a>,
}

impl Spanned for QuantifierExpression<'_> {
    fn span(&self) -> Span {
        self.quantifier.join_span(&self.operand)
    }
}

/// A row/tuple constructor expression: `(expr1, expr2, ...)`
#[derive(Debug, Clone)]
pub struct RowExpression<'a> {
    /// Span of the surrounding parentheses
    pub paren_span: Span,
    /// Elements of the tuple
    pub elements: Vec<Expression<'a>>,
}

impl Spanned for RowExpression<'_> {
    fn span(&self) -> Span {
        self.paren_span.clone()
    }
}

/// Representation of an expression
#[derive(Debug, Clone)]
pub enum Expression<'a> {
    /// Expression with binary operator
    Binary(Box<BinaryExpression<'a>>),
    /// Expression with a unary (prefix) operator
    Unary(Box<UnaryExpression<'a>>),
    /// Subquery expression
    Subquery(Box<SubqueryExpression<'a>>),
    /// Literal NULL expression
    Null(Box<NullExpression>),
    /// Literal DEFAULT expression
    Default(Box<DefaultExpression>),
    /// Literal bool expression "TRUE" or "FALSE"
    Bool(Box<BoolExpression>),
    /// Literal string expression, the SString contains the represented string
    /// with escaping removed
    String(Box<SString<'a>>),
    /// Literal integer expression
    Integer(Box<IntegerExpression>),
    /// Literal _LIST_
    ListHack(Box<ListHackExpression>),
    /// Literal floating point expression
    Float(Box<FloatExpression>),
    /// Function call expression,
    Function(Box<FunctionCallExpression<'a>>),
    /// A window function call expression
    WindowFunction(Box<WindowFunctionCallExpression<'a>>),
    /// Aggregate function call expression with optional DISTINCT/FILTER/OVER
    AggregateFunction(Box<AggregateFunctionCallExpression<'a>>),
    /// Identifier pointing to column
    Identifier(Box<IdentifierExpression<'a>>),
    /// Time Interval
    Interval(Box<IntervalExpression>),
    /// Input argument to query, the first argument is the occurrence number of the argument
    Arg(Box<ArgExpression>),
    /// Exists expression
    Exists(Box<ExistsExpression<'a>>),
    /// Extract expression
    Extract(Box<ExtractExpression<'a>>),
    /// Trim expression
    Trim(Box<TrimExpression<'a>>),
    /// In expression
    In(Box<InExpression<'a>>),
    /// Between expression
    Between(Box<BetweenExpression<'a>>),
    /// Member of expression
    MemberOf(Box<MemberOfExpression<'a>>),
    /// Is expression
    Is(Box<IsExpression<'a>>),
    /// Invalid expression, returned on recovery of a parse error
    Invalid(Box<InvalidExpression>),
    /// Case expression
    Case(Box<CaseExpression<'a>>),
    /// Cast expression
    Cast(Box<CastExpression<'a>>),
    /// Convert expression (CONVERT(expr, type) or CONVERT(expr USING charset))
    Convert(Box<ConvertExpression<'a>>),
    /// Group contat expression
    GroupConcat(Box<GroupConcatExpression<'a>>),
    /// Variable expression
    Variable(Box<VariableExpression<'a>>),
    /// User variable expression (@variable_name)
    UserVariable(Box<UserVariableExpression<'a>>),
    /// Timestampadd call
    TimestampAdd(Box<TimestampAddExpression<'a>>),
    /// Timestampdiff call
    TimestampDiff(Box<TimestampDiffExpression<'a>>),
    /// PostgreSQL-style typecast expression (expr::type)
    TypeCast(Box<TypeCastExpression<'a>>),
    /// Full-text MATCH ... AGAINST expression
    MatchAgainst(Box<MatchAgainstExpression<'a>>),
    /// PostgreSQL ARRAY[...] literal expression
    Array(Box<ArrayExpression<'a>>),
    /// Array subscript / slice expression: expr[idx] or expr[lower:upper]
    ArraySubscript(Box<ArraySubscriptExpression<'a>>),
    /// PostgreSQL ANY / SOME / ALL quantifier: ANY(subquery_or_array)
    Quantifier(Box<QuantifierExpression<'a>>),
    /// PostgreSQL composite type field access: (expr).field
    FieldAccess(Box<FieldAccessExpression<'a>>),
    /// CHAR(N,... [USING charset_name]) expression
    Char(Box<CharFunctionExpression<'a>>),
    /// Row / tuple constructor: `(expr1, expr2, ...)`
    Row(Box<RowExpression<'a>>),
}

impl<'a> Spanned for Expression<'a> {
    fn span(&self) -> Span {
        match &self {
            Expression::Binary(e) => e.span(),
            Expression::Unary(e) => e.span(),
            Expression::Subquery(v) => v.span(),
            Expression::Null(v) => v.span(),
            Expression::Default(v) => v.span(),
            Expression::Bool(v) => v.span(),
            Expression::String(v) => v.span(),
            Expression::Integer(v) => v.span(),
            Expression::Float(v) => v.span(),
            Expression::ListHack(v) => v.span(),
            Expression::Function(e) => e.span(),
            Expression::AggregateFunction(e) => e.span(),
            Expression::Identifier(e) => e.span(),
            Expression::Arg(v) => v.span(),
            Expression::Exists(v) => v.span(),
            Expression::In(e) => e.span(),
            Expression::Between(e) => e.span(),
            Expression::MemberOf(e) => e.span(),
            Expression::Is(e) => e.span(),
            Expression::Invalid(s) => s.span(),
            Expression::Case(e) => e.span(),
            Expression::Cast(e) => e.span(),
            Expression::Convert(e) => e.span(),
            Expression::TypeCast(e) => e.span(),
            Expression::GroupConcat(e) => e.span(),
            Expression::Variable(e) => e.span(),
            Expression::UserVariable(e) => e.span(),
            Expression::WindowFunction(e) => e.span(),
            Expression::Interval(e) => e.span(),
            Expression::Extract(e) => e.span(),
            Expression::Trim(e) => e.span(),
            Expression::TimestampAdd(e) => e.span(),
            Expression::TimestampDiff(e) => e.span(),
            Expression::MatchAgainst(e) => e.span(),
            Expression::Array(e) => e.span(),
            Expression::ArraySubscript(e) => e.span(),
            Expression::Quantifier(e) => e.span(),
            Expression::FieldAccess(e) => e.span(),
            Expression::Char(e) => e.span(),
            Expression::Row(e) => e.span(),
        }
    }
}

// Operator parsing priority table.
// Lower number = tighter binding (reduced later, applied first).
// An operator is only parsed when its priority < max_priority passed to the parser.
pub(crate) const PRIORITY_TYPECAST: usize = 10; // ::
pub(crate) const PRIORITY_JSON_EXTRACT: usize = 30; // -> ->>
pub(crate) const PRIORITY_BITXOR: usize = 50; // ^ (XOR bitwise)
pub(crate) const PRIORITY_MULT: usize = 60; // * / % DIV MOD
pub(crate) const PRIORITY_ADD: usize = 70; // + -
pub(crate) const PRIORITY_PG_CUSTOM: usize = 75; // PostgreSQL custom / user-defined operators
pub(crate) const PRIORITY_SHIFT: usize = 80; // << >>
pub(crate) const PRIORITY_BITAND: usize = 90; // &
pub(crate) const PRIORITY_BITOR: usize = 100; // |
pub(crate) const PRIORITY_CMP: usize = 110; // = != < > <= >= IS IN LIKE BETWEEN SIMILAR TO ...
pub(crate) const PRIORITY_AND: usize = 140; // AND  (tighter than OR)
pub(crate) const PRIORITY_XOR: usize = 150; // XOR (keyword logical XOR)
pub(crate) const PRIORITY_OR: usize = 160; // OR   (loosest binary operator)
pub(crate) const PRIORITY_ASSIGN: usize = 200; // :=

/// Parse all operators (no restriction).
pub(crate) const PRIORITY_MAX: usize = usize::MAX;

trait Priority {
    fn priority(&self) -> usize;
}

impl<'a> Priority for BinaryOperator<'a> {
    fn priority(&self) -> usize {
        match self {
            BinaryOperator::Assignment(_) => PRIORITY_ASSIGN,
            BinaryOperator::Or(_) => PRIORITY_OR,
            BinaryOperator::Concat(_) => PRIORITY_ADD,
            BinaryOperator::Xor(_) => PRIORITY_XOR,
            BinaryOperator::And(_) => PRIORITY_AND,
            BinaryOperator::Eq(_) => PRIORITY_CMP,
            BinaryOperator::NullSafeEq(_) => PRIORITY_CMP,
            BinaryOperator::GtEq(_) => PRIORITY_CMP,
            BinaryOperator::Gt(_) => PRIORITY_CMP,
            BinaryOperator::LtEq(_) => PRIORITY_CMP,
            BinaryOperator::Lt(_) => PRIORITY_CMP,
            BinaryOperator::Neq(_) => PRIORITY_CMP,
            BinaryOperator::Like(_) => PRIORITY_CMP,
            BinaryOperator::NotLike(_) => PRIORITY_CMP,
            BinaryOperator::Regexp(_) => PRIORITY_CMP,
            BinaryOperator::NotRegexp(_) => PRIORITY_CMP,
            BinaryOperator::Rlike(_) => PRIORITY_CMP,
            BinaryOperator::NotRlike(_) => PRIORITY_CMP,
            BinaryOperator::ShiftLeft(_) => PRIORITY_SHIFT,
            BinaryOperator::ShiftRight(_) => PRIORITY_SHIFT,
            BinaryOperator::BitAnd(_) => PRIORITY_BITAND,
            BinaryOperator::BitOr(_) => PRIORITY_BITOR,
            BinaryOperator::BitXor(_) => PRIORITY_BITXOR,
            BinaryOperator::Add(_) => PRIORITY_ADD,
            BinaryOperator::Subtract(_) => PRIORITY_ADD,
            BinaryOperator::Divide(_) => PRIORITY_MULT,
            BinaryOperator::Div(_) => PRIORITY_MULT,
            BinaryOperator::Mod(_) => PRIORITY_MULT,
            BinaryOperator::Mult(_) => PRIORITY_MULT,
            BinaryOperator::Collate(_) => 20,
            BinaryOperator::JsonExtract(_) => PRIORITY_JSON_EXTRACT,
            BinaryOperator::JsonExtractUnquote(_) => PRIORITY_JSON_EXTRACT,
            BinaryOperator::Contains(_)
            | BinaryOperator::ContainedBy(_)
            | BinaryOperator::JsonPathMatch(_)
            | BinaryOperator::JsonPathExists(_)
            | BinaryOperator::JsonbKeyExists(_)
            | BinaryOperator::JsonbAnyKeyExists(_)
            | BinaryOperator::JsonbAllKeyExists(_)
            | BinaryOperator::JsonGetPath(_)
            | BinaryOperator::JsonGetPathText(_)
            | BinaryOperator::JsonDeletePath(_)
            | BinaryOperator::RegexMatch(_)
            | BinaryOperator::RegexIMatch(_)
            | BinaryOperator::NotRegexMatch(_)
            | BinaryOperator::NotRegexIMatch(_)
            | BinaryOperator::User(_, _)
            | BinaryOperator::Operator(_, _) => PRIORITY_PG_CUSTOM,
        }
    }
}

impl Priority for UnaryOperator {
    fn priority(&self) -> usize {
        match self {
            UnaryOperator::Binary(_) => 20,
            UnaryOperator::LogicalNot(_) => 30,
            UnaryOperator::Minus(_) => 40,
            UnaryOperator::Not(_) => 130,
        }
    }
}

#[derive(Debug)]
enum ReduceMember<'a> {
    Expression(Expression<'a>),
    Binary(BinaryOperator<'a>),
    Unary(UnaryOperator),
}

struct Reducer<'a> {
    stack: Vec<ReduceMember<'a>>,
}

impl<'a> Reducer<'a> {
    fn reduce(&mut self, priority: usize) -> Result<(), &'static str> {
        let mut e = match self.stack.pop() {
            Some(ReduceMember::Expression(e)) => e,
            _ => {
                return Err("Expected expression before here");
            }
        };
        loop {
            let v = self.stack.pop();
            match v {
                None => break,
                Some(ReduceMember::Expression(_)) => return Err("ICE Reduce stack error 1"),
                Some(ReduceMember::Unary(op)) if op.priority() > priority => {
                    self.stack.push(ReduceMember::Unary(op));
                    break;
                }
                Some(ReduceMember::Binary(op)) if op.priority() > priority => {
                    self.stack.push(ReduceMember::Binary(op));
                    break;
                }
                Some(ReduceMember::Unary(op)) => {
                    e = Expression::Unary(Box::new(UnaryExpression { op, operand: e }));
                }
                Some(ReduceMember::Binary(op)) => {
                    let lhs = match self.stack.pop() {
                        Some(ReduceMember::Expression(e)) => e,
                        _ => return Err("ICE Reduce stack error 2"),
                    };
                    e = Expression::Binary(Box::new(BinaryExpression { op, lhs, rhs: e }));
                }
            }
        }
        self.stack.push(ReduceMember::Expression(e));
        Ok(())
    }

    fn shift_binop(&mut self, op: BinaryOperator<'a>) -> Result<(), &'static str> {
        self.reduce(op.priority())?;
        self.stack.push(ReduceMember::Binary(op));
        Ok(())
    }

    fn shift_unary(&mut self, op: UnaryOperator) -> Result<(), &'static str> {
        if matches!(self.stack.last(), Some(ReduceMember::Expression(_))) {
            return Err("Unary operator cannot come before expression");
        }
        self.stack.push(ReduceMember::Unary(op));
        Ok(())
    }

    fn shift_expr(&mut self, e: Expression<'a>) -> Result<(), &'static str> {
        if matches!(self.stack.last(), Some(ReduceMember::Expression(_))) {
            //panic!();
            return Err("Expression should not follow expression");
        }
        self.stack.push(ReduceMember::Expression(e));
        Ok(())
    }
}

/// Parse a single element inside an ARRAY[...] literal.
/// If the current token is `[`, parses a nested sub-array `[elem, ...]` recursively.
/// Otherwise delegates to `parse_expression_unreserved`.
fn parse_array_element<'a>(parser: &mut Parser<'a, '_>) -> Result<Expression<'a>, ParseError> {
    if matches!(parser.token, Token::LBracket) {
        let lbracket = parser.consume_token(Token::LBracket)?;
        let mut elements = Vec::new();
        if !matches!(parser.token, Token::RBracket) {
            loop {
                parser.recovered(
                    "']' or ','",
                    &|t| matches!(t, Token::RBracket | Token::Comma),
                    |parser| {
                        elements.push(parse_array_element(parser)?);
                        Ok(())
                    },
                )?;
                if parser.skip_token(Token::Comma).is_none() {
                    break;
                }
            }
        }
        let rbracket = parser.consume_token(Token::RBracket)?;
        let bracket_span = lbracket.join_span(&rbracket);
        Ok(Expression::Array(Box::new(ArrayExpression {
            array_span: bracket_span.clone(),
            bracket_span,
            elements,
        })))
    } else {
        parse_expression_unreserved(parser, PRIORITY_MAX)
    }
}

pub(crate) fn parse_expression_restricted<'a>(
    parser: &mut Parser<'a, '_>,
    max_priority: usize,
    restrict: Restrict,
) -> Result<Expression<'a>, ParseError> {
    let mut r = Reducer { stack: Vec::new() };
    loop {
        if matches!(r.stack.last(), Some(ReduceMember::Expression(_)))
            && matches!(
                parser.token,
                Token::Ident(
                    _,
                    Keyword::NULLS
                        | Keyword::FIRST
                        | Keyword::LAST
                        | Keyword::ROW
                        | Keyword::ROWS
                        | Keyword::RANGE
                        | Keyword::ONLY
                        | Keyword::FILTER
                        | Keyword::PRECEDING
                        | Keyword::FOLLOWING
                )
            )
        {
            break;
        }
        // `NOT NULL` is a column constraint, not an expression operator
        // (e.g. `DEFAULT (foo())::TEXT NOT NULL`).  Break before consuming
        // the NOT so the caller can handle NOT NULL as a constraint.
        if matches!(r.stack.last(), Some(ReduceMember::Expression(_)))
            && matches!(parser.token, Token::Ident(_, Keyword::NOT))
            && matches!(parser.peek(), Token::Ident(_, Keyword::NULL))
        {
            break;
        }
        let e = match parser.token.clone() {
            Token::ColonEq if PRIORITY_ASSIGN < max_priority => {
                r.shift_binop(BinaryOperator::Assignment(parser.consume()))
            }
            Token::Ident(_, Keyword::OR) if PRIORITY_OR < max_priority => {
                r.shift_binop(BinaryOperator::Or(parser.consume()))
            }
            Token::DoublePipe if PRIORITY_ADD < max_priority => {
                r.shift_binop(BinaryOperator::Concat(parser.consume()))
            }
            Token::Ident(_, Keyword::XOR) if PRIORITY_XOR < max_priority => {
                r.shift_binop(BinaryOperator::Xor(parser.consume()))
            }
            Token::Ident(_, Keyword::AND) | Token::DoubleAmpersand
                if PRIORITY_AND < max_priority =>
            {
                r.shift_binop(BinaryOperator::And(parser.consume()))
            }
            Token::Eq if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Eq(parser.consume()))
            }
            Token::Spaceship if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::NullSafeEq(parser.consume()))
            }
            Token::GtEq if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::GtEq(parser.consume()))
            }
            Token::Gt if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Gt(parser.consume()))
            }
            Token::LtEq if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::LtEq(parser.consume()))
            }
            Token::Lt if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Lt(parser.consume()))
            }
            Token::Neq if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Neq(parser.consume()))
            }
            Token::ShiftLeft if PRIORITY_SHIFT < max_priority => {
                r.shift_binop(BinaryOperator::ShiftLeft(parser.consume()))
            }
            Token::ShiftRight if PRIORITY_SHIFT < max_priority => {
                r.shift_binop(BinaryOperator::ShiftRight(parser.consume()))
            }
            Token::Ampersand => r.shift_binop(BinaryOperator::BitAnd(parser.consume())),
            Token::Pipe if PRIORITY_BITOR < max_priority => {
                r.shift_binop(BinaryOperator::BitOr(parser.consume()))
            }
            Token::Ident(_, Keyword::BINARY) if PRIORITY_JSON_EXTRACT < max_priority => {
                r.shift_unary(UnaryOperator::Binary(parser.consume()))
            }
            Token::Ident(_, Keyword::COLLATE)
                if 20 < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                // COLLATE is a binary operator: expr COLLATE collation_name
                let collate_span = parser.consume_keyword(Keyword::COLLATE)?;
                let collation = parser.consume_plain_identifier_unreserved()?;
                if let Err(e) = r.shift_binop(BinaryOperator::Collate(collate_span)) {
                    parser.err_here(e)?;
                }
                r.shift_expr(Expression::Identifier(Box::new(IdentifierExpression {
                    parts: vec![IdentifierPart::Name(collation)],
                })))
            }
            Token::ExclamationMark if PRIORITY_JSON_EXTRACT < max_priority => {
                r.shift_unary(UnaryOperator::LogicalNot(parser.consume()))
            }
            Token::Minus if !matches!(r.stack.last(), Some(ReduceMember::Expression(_))) => {
                r.shift_unary(UnaryOperator::Minus(parser.consume()))
            }
            Token::Minus
                if PRIORITY_ADD < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::Subtract(parser.consume()))
            }
            Token::Ident(_, Keyword::IN) if PRIORITY_CMP < max_priority => {
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before here 3")?,
                };
                let op = parser.consume_keyword(Keyword::IN)?;
                parser.consume_token(Token::LParen)?;
                let mut rhs = Vec::new();
                loop {
                    parser.recovered(
                        "')' or ','",
                        &|t| matches!(t, Token::RParen | Token::Comma),
                        |parser| {
                            rhs.push(parse_expression_paren(parser)?);
                            Ok(())
                        },
                    )?;
                    if parser.skip_token(Token::Comma).is_none() {
                        break;
                    }
                }
                parser.consume_token(Token::RParen)?;
                r.shift_expr(Expression::In(Box::new(InExpression {
                    lhs,
                    rhs,
                    in_span: op,
                    not_in: false,
                })))
            }
            Token::Ident(_, Keyword::IS) if PRIORITY_CMP < max_priority => {
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before here 4")?,
                };
                let op = parser.consume_keyword(Keyword::IS)?;
                let (is, op) = match &parser.token {
                    Token::Ident(_, Keyword::NOT) => {
                        parser.consume();
                        match &parser.token {
                            Token::Ident(_, Keyword::TRUE) => {
                                (Is::NotTrue, parser.consume().join_span(&op))
                            }
                            Token::Ident(_, Keyword::FALSE) => {
                                (Is::NotFalse, parser.consume().join_span(&op))
                            }
                            Token::Ident(_, Keyword::NULL) => {
                                (Is::NotNull, parser.consume().join_span(&op))
                            }
                            Token::Ident(_, Keyword::UNKNOWN) => {
                                (Is::NotUnknown, parser.consume().join_span(&op))
                            }
                            Token::Ident(_, Keyword::DISTINCT) => {
                                let op_span = parser
                                    .consume_keywords(&[Keyword::DISTINCT, Keyword::FROM])?
                                    .join_span(&op);
                                parser.postgres_only(&op_span);
                                let rhs = parse_expression_unreserved(parser, PRIORITY_AND)?;
                                (Is::NotDistinctFrom(rhs), op_span)
                            }
                            _ => parser.expected_failure(
                                "'TRUE', 'FALSE', 'UNKNOWN', 'NULL' or 'DISTINCT'",
                            )?,
                        }
                    }
                    Token::Ident(_, Keyword::TRUE) => (Is::True, parser.consume().join_span(&op)),
                    Token::Ident(_, Keyword::FALSE) => (Is::False, parser.consume().join_span(&op)),
                    Token::Ident(_, Keyword::NULL) => (Is::Null, parser.consume().join_span(&op)),
                    Token::Ident(_, Keyword::DISTINCT) => {
                        let op_span = parser
                            .consume_keywords(&[Keyword::DISTINCT, Keyword::FROM])?
                            .join_span(&op);
                        parser.postgres_only(&op_span);
                        let rhs = parse_expression_unreserved(parser, PRIORITY_AND)?;
                        (Is::DistinctFrom(rhs), op_span)
                    }
                    Token::Ident(_, Keyword::UNKNOWN) => {
                        (Is::Unknown, parser.consume().join_span(&op))
                    }
                    _ => parser.expected_failure(
                        "'NOT', 'TRUE', 'FALSE', 'UNKNOWN', 'NULL' or 'DISTINCT'",
                    )?,
                };
                r.shift_expr(Expression::Is(Box::new(IsExpression {
                    lhs,
                    is,
                    is_span: op,
                })))
            }
            Token::DoubleColon
                if parser.options.dialect.is_postgresql()
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                // PostgreSQL typecast operator: expr::type
                // Reduce with very high priority (binds tighter than most operators)
                if let Err(e) = r.reduce(PRIORITY_TYPECAST) {
                    parser.err_here(e)?;
                }
                let expr = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before '::'")?,
                };
                let doublecolon_span = parser.consume_token(Token::DoubleColon)?;
                let type_ = parse_data_type(parser, DataTypeContext::TypeRef)?;
                r.shift_expr(Expression::TypeCast(Box::new(TypeCastExpression {
                    expr,
                    doublecolon_span,
                    type_,
                })))
            }
            Token::LBracket
                if parser.options.dialect.is_postgresql()
                    && PRIORITY_TYPECAST < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                // Array subscript / slice: expr[idx] or expr[lower:upper]
                if let Err(e) = r.reduce(PRIORITY_TYPECAST) {
                    parser.err_here(e)?;
                }
                let expr = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before '['")?,
                };
                let lbracket = parser.consume_token(Token::LBracket)?;
                let lower = parse_expression_unreserved(parser, PRIORITY_MAX)?;
                let upper = if parser.skip_token(Token::Colon).is_some() {
                    Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
                } else {
                    None
                };
                let rbracket = parser.consume_token(Token::RBracket)?;
                let bracket_span = lbracket.join_span(&rbracket);
                r.shift_expr(Expression::ArraySubscript(Box::new(
                    ArraySubscriptExpression {
                        expr,
                        bracket_span,
                        lower,
                        upper,
                    },
                )))
            }
            Token::Period
                if parser.options.dialect.is_postgresql()
                    && PRIORITY_TYPECAST < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                // PostgreSQL composite type field access: (expr).field
                if let Err(e) = r.reduce(PRIORITY_TYPECAST) {
                    parser.err_here(e)?;
                }
                let expr = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before '.'")?,
                };
                let dot_span = parser.consume_token(Token::Period)?;
                let field = parser.consume_plain_identifier_unreserved()?;
                r.shift_expr(Expression::FieldAccess(Box::new(FieldAccessExpression {
                    expr,
                    dot_span,
                    field,
                })))
            }
            Token::Ident(_, Keyword::NOT)
                if !matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_unary(UnaryOperator::Not(parser.consume()))
            }
            Token::Ident(_, Keyword::NOT)
                if PRIORITY_CMP < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before here 2")?,
                };
                let op = parser.consume_keyword(Keyword::NOT)?;
                match &parser.token {
                    Token::Ident(_, Keyword::IN) => {
                        let op = parser.consume_keyword(Keyword::IN)?.join_span(&op);
                        parser.consume_token(Token::LParen)?;
                        let mut rhs = Vec::new();
                        loop {
                            parser.recovered(
                                "')' or ','",
                                &|t| matches!(t, Token::RParen | Token::Comma),
                                |parser| {
                                    rhs.push(parse_expression_paren(parser)?);
                                    Ok(())
                                },
                            )?;
                            if parser.skip_token(Token::Comma).is_none() {
                                break;
                            }
                        }
                        parser.consume_token(Token::RParen)?;
                        r.shift_expr(Expression::In(Box::new(InExpression {
                            lhs,
                            rhs,
                            in_span: op,
                            not_in: true,
                        })))
                    }
                    Token::Ident(_, Keyword::LIKE) => {
                        r.stack.push(ReduceMember::Expression(lhs));
                        r.shift_binop(BinaryOperator::NotLike(parser.consume().join_span(&op)))
                    }
                    Token::Ident(_, Keyword::REGEXP) if parser.options.dialect.is_maria() => {
                        r.stack.push(ReduceMember::Expression(lhs));
                        r.shift_binop(BinaryOperator::NotRegexp(parser.consume().join_span(&op)))
                    }
                    Token::Ident(_, Keyword::RLIKE) if parser.options.dialect.is_maria() => {
                        r.stack.push(ReduceMember::Expression(lhs));
                        r.shift_binop(BinaryOperator::NotRlike(parser.consume().join_span(&op)))
                    }
                    Token::Ident(_, Keyword::BETWEEN) => {
                        let between_span = parser.consume_keyword(Keyword::BETWEEN)?.join_span(&op);
                        let low = parse_expression_unreserved(parser, PRIORITY_AND)?;
                        let and_span = parser.consume_keyword(Keyword::AND)?;
                        let high = parse_expression_unreserved(parser, PRIORITY_AND)?;
                        r.shift_expr(Expression::Between(Box::new(BetweenExpression {
                            lhs,
                            low,
                            high,
                            between_span: between_span.join_span(&and_span),
                            not_between: true,
                        })))
                    }
                    _ => parser.expected_failure("'IN', 'LIKE', 'REGEXP', 'RLIKE' or 'BETWEEN'")?,
                }
            }
            Token::Ident(_, Keyword::BETWEEN)
                if PRIORITY_CMP < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before BETWEEN")?,
                };
                let between_span = parser.consume_keyword(Keyword::BETWEEN)?;
                let low = parse_expression_unreserved(parser, PRIORITY_AND)?;
                let and_span = parser.consume_keyword(Keyword::AND)?;
                let high = parse_expression_unreserved(parser, PRIORITY_AND)?;
                r.shift_expr(Expression::Between(Box::new(BetweenExpression {
                    lhs,
                    low,
                    high,
                    between_span: between_span.join_span(&and_span),
                    not_between: false,
                })))
            }
            Token::Ident(_, Keyword::LIKE) if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Like(parser.consume()))
            }
            Token::Ident(_, Keyword::SIMILAR)
                if PRIORITY_CMP < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                // SIMILAR TO expr (PostgreSQL)
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before SIMILAR")?,
                };
                let op_span = parser.consume_keywords(&[Keyword::SIMILAR, Keyword::TO])?;
                parser.postgres_only(&op_span);
                r.stack.push(ReduceMember::Expression(lhs));
                r.shift_binop(BinaryOperator::Like(op_span))
            }
            Token::Ident(_, Keyword::REGEXP)
                if PRIORITY_CMP < max_priority && parser.options.dialect.is_maria() =>
            {
                r.shift_binop(BinaryOperator::Regexp(parser.consume()))
            }
            Token::Ident(_, Keyword::RLIKE)
                if PRIORITY_CMP < max_priority && parser.options.dialect.is_maria() =>
            {
                r.shift_binop(BinaryOperator::Rlike(parser.consume()))
            }
            Token::RArrowJson if PRIORITY_JSON_EXTRACT < max_priority => {
                r.shift_binop(BinaryOperator::JsonExtract(parser.consume()))
            }
            Token::RDoubleArrowJson if PRIORITY_JSON_EXTRACT < max_priority => {
                r.shift_binop(BinaryOperator::JsonExtractUnquote(parser.consume()))
            }
            // PostgreSQL built-in operator tokens
            Token::Contains if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::Contains(parser.consume()))
            }
            Token::ContainedBy if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::ContainedBy(parser.consume()))
            }
            Token::AtQuestion if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonPathExists(parser.consume()))
            }
            Token::QuestionPipe if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonbAnyKeyExists(parser.consume()))
            }
            Token::QuestionAmpersand if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonbAllKeyExists(parser.consume()))
            }
            Token::HashArrow if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonGetPath(parser.consume()))
            }
            Token::HashDoubleArrow if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonGetPathText(parser.consume()))
            }
            Token::HashMinus if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::JsonDeletePath(parser.consume()))
            }
            Token::TildeStar if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::RegexIMatch(parser.consume()))
            }
            Token::NotTilde if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::NotRegexMatch(parser.consume()))
            }
            Token::NotTildeStar if PRIORITY_PG_CUSTOM < max_priority => {
                r.shift_binop(BinaryOperator::NotRegexIMatch(parser.consume()))
            }
            Token::LikeTilde if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Like(parser.consume()))
            }
            Token::NotLikeTilde if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::NotLike(parser.consume()))
            }
            // @@ as binary (full-text / jsonpath match)
            Token::AtAt
                if PRIORITY_PG_CUSTOM < max_priority
                    && parser.options.dialect.is_postgresql()
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::JsonPathMatch(parser.consume()))
            }
            // ~ as binary regex match (only when expression already on left)
            Token::Tilde
                if PRIORITY_PG_CUSTOM < max_priority
                    && parser.options.dialect.is_postgresql()
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::RegexMatch(parser.consume()))
            }
            // ? as jsonb key-exists binary operator (PG, non-argument mode)
            Token::QuestionMark
                if PRIORITY_PG_CUSTOM < max_priority
                    && parser.options.dialect.is_postgresql()
                    && !matches!(parser.options.arguments, crate::SQLArguments::QuestionMark)
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::JsonbKeyExists(parser.consume()))
            }
            // Remaining user-defined PostgreSQL operators
            Token::PostgresOperator(op)
                if PRIORITY_PG_CUSTOM < max_priority
                    && parser.options.dialect.is_postgresql()
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::User(op, parser.consume()))
            }
            Token::Ident(_, Keyword::OPERATOR)
                if PRIORITY_PG_CUSTOM < max_priority
                    && parser.options.dialect.is_postgresql()
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                let operator_span = parser.consume_keyword(Keyword::OPERATOR)?;
                parser.consume_token(Token::LParen)?;
                let op_name = parse_operator_name(parser)?;
                let rparen_span = parser.consume_token(Token::RParen)?;
                let full_span = operator_span.join_span(&rparen_span);
                r.shift_binop(BinaryOperator::Operator(op_name, full_span))
            }
            Token::Ident(_, Keyword::MEMBER)
                if PRIORITY_CMP < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                if let Err(e) = r.reduce(PRIORITY_CMP) {
                    parser.err_here(e)?;
                }
                let lhs = match r.stack.pop() {
                    Some(ReduceMember::Expression(e)) => e,
                    _ => parser.err_here("Expected expression before here")?,
                };
                let member_span = parser.consume_keyword(Keyword::MEMBER)?;
                let of_span = parser.consume_keyword(Keyword::OF)?;
                parser.consume_token(Token::LParen)?;
                let rhs = parse_expression_paren(parser)?;
                parser.consume_token(Token::RParen)?;
                r.shift_expr(Expression::MemberOf(Box::new(MemberOfExpression {
                    lhs,
                    rhs,
                    member_of_span: member_span.join_span(&of_span),
                })))
            }
            Token::Ident(_, Keyword::INTERVAL) => {
                let interval_span = parser.consume();
                let (time_interval, embedded_unit) = match parser.token {
                    Token::String(..) => {
                        let v = parser.consume_string()?;
                        let str_span = v.span();
                        let mut nums = Vec::new();
                        let mut embedded: Option<TimeUnit> = None;
                        for part in v.split([':', '!', ',', '.', '-', ' ']) {
                            if let Ok(n) = part.parse::<i64>() {
                                nums.push(n);
                            } else if !part.is_empty() {
                                embedded = parse_time_unit_from_str(part);
                            }
                        }
                        ((nums, str_span), embedded)
                    }
                    Token::Integer(_) => {
                        let (v, s) = parser.consume_int()?;
                        ((vec![v], s), None)
                    }
                    _ => parser.err_here("Expected integer or string")?,
                };
                let time_unit = if let Some(u) = parse_time_unit(&parser.token) {
                    (u, parser.consume())
                } else if let Some(u) = embedded_unit {
                    (u, time_interval.1.clone())
                } else {
                    parser.err_here("Expected time unit")?
                };
                let e = Expression::Interval(Box::new(IntervalExpression {
                    interval_span,
                    time_interval,
                    time_unit,
                }));
                r.shift_expr(e)
            }
            Token::Ident(_, Keyword::TIMESTAMPADD) => {
                let timestamp_add_span = parser.consume();
                parser.consume_token(Token::LParen)?;
                let parts = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    let Some(u) = parse_time_unit(&parser.token) else {
                        parser.err_here("Expected time unit")?
                    };
                    let unit = (u, parser.consume());
                    parser.consume_token(Token::Comma)?;
                    let interval = parse_expression_outer(parser)?;
                    parser.consume_token(Token::Comma)?;
                    let datetime = parse_expression_outer(parser)?;
                    Ok(Some((unit, interval, datetime)))
                })?;
                parser.consume_token(Token::RParen)?;
                if let Some((unit, interval, datetime)) = parts {
                    r.shift_expr(Expression::TimestampAdd(Box::new(TimestampAddExpression {
                        timestamp_add_span,
                        unit,
                        interval,
                        datetime,
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: timestamp_add_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::TIMESTAMPDIFF) => {
                let timestamp_diff_span = parser.consume();
                parser.consume_token(Token::LParen)?;
                let parts = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    let Some(u) = parse_time_unit(&parser.token) else {
                        parser.err_here("Expected time unit")?
                    };
                    let unit = (u, parser.consume());
                    parser.consume_token(Token::Comma)?;
                    let e1 = parse_expression_outer(parser)?;
                    parser.consume_token(Token::Comma)?;
                    let e2 = parse_expression_outer(parser)?;
                    Ok(Some((unit, e1, e2)))
                })?;
                parser.consume_token(Token::RParen)?;
                if let Some((unit, e1, e2)) = parts {
                    r.shift_expr(Expression::TimestampDiff(Box::new(
                        TimestampDiffExpression {
                            timestamp_diff_span,
                            unit,
                            e1,
                            e2,
                        },
                    )))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: timestamp_diff_span,
                    })))
                }
            }
            Token::Plus if PRIORITY_ADD < max_priority => {
                r.shift_binop(BinaryOperator::Add(parser.consume()))
            }
            Token::Div if PRIORITY_MULT < max_priority => {
                r.shift_binop(BinaryOperator::Divide(parser.consume()))
            }
            Token::Ident(_, Keyword::DIV) if PRIORITY_MULT < max_priority => {
                r.shift_binop(BinaryOperator::Div(parser.consume()))
            }
            Token::Minus if PRIORITY_ADD < max_priority => {
                r.shift_binop(BinaryOperator::Subtract(parser.consume()))
            }
            Token::Ident(_, Keyword::LIKE) if PRIORITY_CMP < max_priority => {
                r.shift_binop(BinaryOperator::Like(parser.consume()))
            }
            Token::Mul if !matches!(r.stack.last(), Some(ReduceMember::Expression(_))) => r
                .shift_expr(Expression::Identifier(Box::new(IdentifierExpression {
                    parts: vec![IdentifierPart::Star(parser.consume_token(Token::Mul)?)],
                }))),
            Token::Mul
                if PRIORITY_MULT < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::Mult(parser.consume()))
            }
            Token::Mod if PRIORITY_MULT < max_priority => {
                r.shift_binop(BinaryOperator::Mod(parser.consume()))
            }
            Token::Ident(_, Keyword::MOD)
                if PRIORITY_MULT < max_priority
                    && matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                r.shift_binop(BinaryOperator::Mod(parser.consume()))
            }
            Token::Ident(_, Keyword::TRUE) => {
                r.shift_expr(Expression::Bool(Box::new(BoolExpression {
                    value: true,
                    span: parser.consume_keyword(Keyword::TRUE)?,
                })))
            }
            Token::Ident(_, Keyword::FALSE) => {
                r.shift_expr(Expression::Bool(Box::new(BoolExpression {
                    value: false,
                    span: parser.consume_keyword(Keyword::FALSE)?,
                })))
            }
            Token::Ident(_, Keyword::NULL) => {
                r.shift_expr(Expression::Null(Box::new(NullExpression {
                    span: parser.consume_keyword(Keyword::NULL)?,
                })))
            }
            Token::Ident(_, Keyword::_LIST_) if parser.options.list_hack => {
                let arg = parser.arg;
                parser.arg += 1;
                r.shift_expr(Expression::ListHack(Box::new(ListHackExpression {
                    index: arg,
                    span: parser.consume_keyword(Keyword::_LIST_)?,
                })))
            }
            Token::String(..) => {
                r.shift_expr(Expression::String(Box::new(parser.consume_string()?)))
            }
            Token::Integer(_) => {
                let (value, span) = parser.consume_int()?;
                r.shift_expr(Expression::Integer(Box::new(IntegerExpression {
                    value,
                    span,
                })))
            }
            Token::Float(_) => {
                let (value, span) = parser.consume_float()?;
                r.shift_expr(Expression::Float(Box::new(FloatExpression { value, span })))
            }
            Token::Ident(_, Keyword::CAST) => {
                let cast_span = parser.consume_keyword(Keyword::CAST)?;
                parser.consume_token(Token::LParen)?;
                let cast = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    let expr = parse_expression_outer(parser)?;
                    let as_span = parser.consume_keyword(Keyword::AS)?;
                    let type_ = parse_data_type(parser, DataTypeContext::TypeRef)?;
                    Ok(Some((expr, as_span, type_)))
                })?;
                parser.consume_token(Token::RParen)?;
                if let Some((expr, as_span, type_)) = cast {
                    r.shift_expr(Expression::Cast(Box::new(CastExpression {
                        cast_span,
                        expr,
                        as_span,
                        type_,
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: cast_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::CONVERT) => {
                let convert_span = parser.consume_keyword(Keyword::CONVERT)?;
                parser.consume_token(Token::LParen)?;
                let convert =
                    parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                        let expr = parse_expression_outer(parser)?;
                        // Check if it's CONVERT(expr, type) or CONVERT(expr USING charset)
                        if parser.skip_keyword(Keyword::USING).is_some() {
                            // CONVERT(expr USING charset)
                            let charset = parser.consume_plain_identifier_unreserved()?;
                            Ok(Some((expr, None, Some(charset))))
                        } else {
                            // CONVERT(expr, type)
                            parser.consume_token(Token::Comma)?;
                            let type_ = parse_data_type(parser, DataTypeContext::TypeRef)?;
                            Ok(Some((expr, Some(type_), None)))
                        }
                    })?;
                parser.consume_token(Token::RParen)?;
                if let Some((expr, type_, charset)) = convert {
                    r.shift_expr(Expression::Convert(Box::new(ConvertExpression {
                        convert_span,
                        expr,
                        type_,
                        using_charset: charset.map(|c| (c.span(), c)),
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: convert_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::GROUP_CONCAT) => {
                let group_concat_span: core::ops::Range<usize> =
                    parser.consume_keyword(Keyword::GROUP_CONCAT)?;
                parser.consume_token(Token::LParen)?;
                let distinct_span: Option<core::ops::Range<usize>> =
                    parser.skip_keyword(Keyword::DISTINCT);
                let expr = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    let expr = parse_expression_outer(parser)?;
                    Ok(Some(expr))
                })?;
                // TODO
                // [ORDER BY {unsigned_integer | col_name | expr}
                //     [ASC | DESC] [,col_name ...]]
                // [SEPARATOR str_val]
                // [LIMIT {[offset,] row_count | row_count OFFSET offset}])
                parser.consume_token(Token::RParen)?;
                if let Some(expr) = expr {
                    r.shift_expr(Expression::GroupConcat(Box::new(GroupConcatExpression {
                        group_concat_span,
                        distinct_span,
                        expr,
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: group_concat_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::TRIM) if matches!(parser.peek(), Token::LParen) => {
                let trim_span = parser.consume_keyword(Keyword::TRIM)?;
                parser.consume_token(Token::LParen)?;
                let parts = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    // Optional BOTH / LEADING / TRAILING
                    let direction = match &parser.token {
                        Token::Ident(_, Keyword::BOTH) => {
                            Some(TrimDirection::Both(parser.consume()))
                        }
                        Token::Ident(_, Keyword::LEADING) => {
                            Some(TrimDirection::Leading(parser.consume()))
                        }
                        Token::Ident(_, Keyword::TRAILING) => {
                            Some(TrimDirection::Trailing(parser.consume()))
                        }
                        _ => None,
                    };

                    let (what, from_span, value) = if direction.is_some() {
                        // After direction: optionally [remstr] FROM value
                        if let Some(from_s) = parser.skip_keyword(Keyword::FROM) {
                            // No remstr: TRIM(BOTH FROM str)
                            let value = parse_expression_outer(parser)?;
                            (None, Some(from_s), value)
                        } else {
                            // Has remstr: TRIM(BOTH remstr FROM str)
                            let what = parse_expression_outer(parser)?;
                            let from_s = parser.consume_keyword(Keyword::FROM)?;
                            let value = parse_expression_outer(parser)?;
                            (Some(what), Some(from_s), value)
                        }
                    } else {
                        // No direction: TRIM(str) or TRIM(remstr FROM str)
                        let first = parse_expression_outer(parser)?;
                        if let Some(from_s) = parser.skip_keyword(Keyword::FROM) {
                            // first is remstr
                            let value = parse_expression_outer(parser)?;
                            (Some(first), Some(from_s), value)
                        } else {
                            // first is the value itself
                            (None, None, first)
                        }
                    };
                    Ok(Some((direction, what, from_span, value)))
                })?;
                parser.consume_token(Token::RParen)?;
                if let Some((direction, what, from_span, value)) = parts {
                    r.shift_expr(Expression::Trim(Box::new(TrimExpression {
                        trim_span,
                        direction,
                        what,
                        from_span,
                        value,
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: trim_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::EXTRACT) => {
                let extract_span = parser.consume_keyword(Keyword::EXTRACT)?;
                parser.consume_token(Token::LParen)?;
                let parts = parser.recovered("')'", &|t| matches!(t, Token::RParen), |parser| {
                    let Some(u) = parse_time_unit(&parser.token) else {
                        parser.err_here("Expected time unit")?
                    };
                    let time_unit = (u, parser.consume());
                    let from_span = parser.consume_keyword(Keyword::FROM)?;
                    let date = parse_expression_outer(parser)?;
                    Ok(Some((time_unit, from_span, date)))
                })?;
                parser.consume_token(Token::RParen)?;
                if let Some((time_unit, from_span, date)) = parts {
                    r.shift_expr(Expression::Extract(Box::new(ExtractExpression {
                        extract_span,
                        time_unit,
                        from_span,
                        date,
                    })))
                } else {
                    r.shift_expr(Expression::Invalid(Box::new(InvalidExpression {
                        span: extract_span,
                    })))
                }
            }
            Token::Ident(_, Keyword::MATCH) => {
                let match_span = parser.consume_keyword(Keyword::MATCH)?;
                parser.consume_token(Token::LParen)?;
                let mut cols = Vec::new();
                loop {
                    parser.recovered(
                        "')' or ','",
                        &|t| matches!(t, Token::RParen | Token::Comma),
                        |parser| {
                            cols.push(parse_expression_paren(parser)?);
                            Ok(())
                        },
                    )?;
                    if parser.skip_token(Token::Comma).is_none() {
                        break;
                    }
                }
                parser.consume_token(Token::RParen)?;
                let against_span = parser.consume_keyword(Keyword::AGAINST)?;
                parser.consume_token(Token::LParen)?;

                // Parse the search expression but don't treat `IN`/`WITH` as binary
                // operators here — they are MATCH modes and may appear inside the
                // AGAINST(...) parentheses (MySQL allows both inside and outside).
                // PRIORITY_CMP stops before IN/WITH so they remain available as MATCH mode keywords
                let expr = parse_expression_unreserved(parser, PRIORITY_CMP)?;

                // optional mode that may appear inside the AGAINST(...) parentheses
                let mut mode: Option<MatchMode> = None;
                if parser.skip_keyword(Keyword::IN).is_some() {
                    if let Some(boolean_span) = parser.skip_keyword(Keyword::BOOLEAN) {
                        let mode_span = parser.consume_keyword(Keyword::MODE)?;
                        mode = Some(MatchMode::InBoolean(boolean_span.join_span(&mode_span)));
                    } else if let Some(natural_span) = parser.skip_keyword(Keyword::NATURAL) {
                        // optional LANGUAGE after NATURAL
                        let _language_span = parser.skip_keyword(Keyword::LANGUAGE);
                        let mode_span = parser.consume_keyword(Keyword::MODE)?;
                        let natural_total = natural_span.join_span(&mode_span);
                        // optional WITH QUERY EXPANSION following NATURAL MODE inside parens
                        if let Some(with_span) = parser.skip_keyword(Keyword::WITH) {
                            let expansion_total = with_span.join_span(
                                &parser.consume_keywords(&[Keyword::QUERY, Keyword::EXPANSION])?,
                            );
                            mode = Some(MatchMode::InNaturalLanguageWithQueryExpansion(
                                natural_total.join_span(&expansion_total),
                            ));
                        } else {
                            mode = Some(MatchMode::InNaturalLanguage(natural_total));
                        }
                    }
                } else if let Some(with_span) = parser.skip_keyword(Keyword::WITH) {
                    mode = Some(MatchMode::WithQueryExpansion(with_span.join_span(
                        &parser.consume_keywords(&[Keyword::QUERY, Keyword::EXPANSION])?,
                    )));
                }

                parser.consume_token(Token::RParen)?;

                // If no mode was found inside the parens, allow it after the closing
                // parenthesis as well (some dialects/placeholders may put it there).
                if mode.is_none() {
                    if parser.skip_keyword(Keyword::IN).is_some() {
                        if let Some(boolean_span) = parser.skip_keyword(Keyword::BOOLEAN) {
                            let mode_span = parser.consume_keyword(Keyword::MODE)?;
                            mode = Some(MatchMode::InBoolean(boolean_span.join_span(&mode_span)));
                        } else if let Some(natural_span) = parser.skip_keyword(Keyword::NATURAL) {
                            let _language_span = parser.skip_keyword(Keyword::LANGUAGE);
                            let mode_span = parser.consume_keyword(Keyword::MODE)?;
                            let natural_total = natural_span.join_span(&mode_span);
                            // optional WITH QUERY EXPANSION following NATURAL MODE after paren
                            if let Some(with_span) = parser.skip_keyword(Keyword::WITH) {
                                let expansion_total = with_span.join_span(
                                    &parser
                                        .consume_keywords(&[Keyword::QUERY, Keyword::EXPANSION])?,
                                );
                                mode = Some(MatchMode::InNaturalLanguageWithQueryExpansion(
                                    natural_total.join_span(&expansion_total),
                                ));
                            } else {
                                mode = Some(MatchMode::InNaturalLanguage(natural_total));
                            }
                        }
                    } else if let Some(with_span) = parser.skip_keyword(Keyword::WITH) {
                        mode = Some(MatchMode::WithQueryExpansion(with_span.join_span(
                            &parser.consume_keywords(&[Keyword::QUERY, Keyword::EXPANSION])?,
                        )));
                    }
                }

                r.shift_expr(Expression::MatchAgainst(Box::new(MatchAgainstExpression {
                    match_span,
                    columns: cols,
                    against_span,
                    expr,
                    mode,
                })))
            }
            Token::Ident(_, Keyword::LEFT) if matches!(parser.peek(), Token::LParen) => {
                let i = parser.token.clone();
                let s = parser.span.clone();
                parser.consume();
                r.shift_expr(parse_function(parser, i, s)?)
            }
            Token::Ident(_, Keyword::CHAR) if matches!(parser.peek(), Token::LParen) => {
                let s = parser.span.clone();
                parser.consume();
                r.shift_expr(parse_char_function(parser, s)?)
            }
            Token::Ident(_, keyword)
                if matches!(parser.peek(), Token::LParen)
                    && is_aggregate_function_ident(&keyword) =>
            {
                let i = parser.token.clone();
                let s = parser.span.clone();
                parser.consume();
                r.shift_expr(parse_aggregate_function(parser, i, s)?)
            }
            // Handle charset-prefixed strings like _utf8mb4 'abc' or _binary 'data'
            Token::Ident(charset, _)
                if charset.starts_with('_') && matches!(parser.peek(), Token::String(..)) =>
            {
                // Consume the charset prefix
                parser.consume();
                // Parse the string literal
                r.shift_expr(Expression::String(Box::new(parser.consume_string()?)))
            }
            // PostgreSQL ARRAY[...] literal
            Token::Ident(_, Keyword::ARRAY) if matches!(parser.peek(), Token::LBracket) => {
                let array_span = parser.consume_keyword(Keyword::ARRAY)?;
                parser.postgres_only(&array_span);
                let lbracket = parser.consume_token(Token::LBracket)?;
                let mut elements = Vec::new();
                if !matches!(parser.token, Token::RBracket) {
                    loop {
                        parser.recovered(
                            "']' or ','",
                            &|t| matches!(t, Token::RBracket | Token::Comma),
                            |parser| {
                                elements.push(parse_array_element(parser)?);
                                Ok(())
                            },
                        )?;
                        if parser.skip_token(Token::Comma).is_none() {
                            break;
                        }
                    }
                }
                let rbracket = parser.consume_token(Token::RBracket)?;
                let bracket_span = lbracket.join_span(&rbracket);
                r.shift_expr(Expression::Array(Box::new(ArrayExpression {
                    array_span,
                    bracket_span,
                    elements,
                })))
            }
            Token::Ident(_, k)
                if (k.expr_ident() || !k.restricted(restrict))
                    && !matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                let i = parser.token.clone();
                let s = parser.span.clone();
                parser.consume();
                if matches!(parser.token, Token::LParen) {
                    r.shift_expr(parse_function(parser, i, s)?)
                } else {
                    let f = match i {
                        Token::Ident(_, Keyword::CURRENT_TIMESTAMP) => {
                            Some(Function::CurrentTimestamp)
                        }
                        Token::Ident(_, Keyword::LOCALTIME | Keyword::LOCALTIMESTAMP) => {
                            Some(Function::Now)
                        }
                        Token::Ident(_, Keyword::UTC_TIMESTAMP) => Some(Function::UtcTimeStamp),
                        Token::Ident(_, Keyword::UTC_DATE) => Some(Function::UtcDate),
                        Token::Ident(_, Keyword::UTC_TIME) => Some(Function::UtcTime),
                        Token::Ident(_, Keyword::CURRENT_DATE) => Some(Function::CurDate),
                        Token::Ident(_, Keyword::CURRENT_TIME) => Some(Function::CurTime),
                        Token::Ident(_, Keyword::CURRENT_USER) => Some(Function::CurrentUser),
                        Token::Ident(_, Keyword::CURRENT_ROLE) => Some(Function::CurrentRole),
                        Token::Ident(_, Keyword::CURRENT_CATALOG) => Some(Function::CurrentCatalog),
                        Token::Ident(_, Keyword::SESSION_USER) => Some(Function::SessionUser),
                        Token::Ident(_, Keyword::USER)
                            if parser.options.dialect.is_postgresql() =>
                        {
                            Some(Function::CurrentUser)
                        }
                        _ => None,
                    };
                    if let Some(f) = f {
                        r.shift_expr(Expression::Function(Box::new(FunctionCallExpression {
                            function: f,
                            args: Vec::new(),
                            function_span: s,
                        })))
                    } else {
                        let mut parts = vec![IdentifierPart::Name(
                            parser.token_to_plain_identifier(&i, s)?,
                        )];
                        // Save the last identifier token so we can call parse_function if
                        // the chain is followed by `(` (schema-qualified function call).
                        let mut last_ident_tok: Option<(Token<'a>, Span)> = None;
                        loop {
                            if parser.skip_token(Token::Period).is_none() {
                                break;
                            }
                            match &parser.token {
                                Token::Mul => {
                                    last_ident_tok = None;
                                    parts.push(IdentifierPart::Star(
                                        parser.consume_token(Token::Mul)?,
                                    ));
                                }
                                Token::Ident(_, _) => {
                                    let fn_tok = parser.token.clone();
                                    let fn_span = parser.span.clone();
                                    last_ident_tok = Some((fn_tok, fn_span));
                                    parts.push(IdentifierPart::Name(
                                        parser.consume_plain_identifier_unreserved()?,
                                    ));
                                }
                                _ => parser.expected_failure("Identifier or '*'")?,
                            }
                        }
                        // Schema-qualified function call: schema.func(args)
                        if matches!(parser.token, Token::LParen) {
                            if let Some((fn_tok, fn_span)) = last_ident_tok {
                                // All parts form the qualified name; last part is function name
                                let mut all_idents: Vec<Identifier<'a>> = parts[..parts.len() - 1]
                                    .iter()
                                    .filter_map(|p| match p {
                                        IdentifierPart::Name(id) => Some(id.clone()),
                                        _ => None,
                                    })
                                    .collect();
                                let fn_ident = Identifier {
                                    value: match &fn_tok {
                                        Token::Ident(v, _) => v,
                                        _ => "",
                                    },
                                    span: fn_span.clone(),
                                };
                                all_idents.push(fn_ident);
                                // function_span covers from first qualifier to function name
                                let function_span = if all_idents.len() > 1 {
                                    all_idents[0].span.join_span(&fn_span)
                                } else {
                                    fn_span
                                };
                                r.shift_expr(parse_function_call(
                                    parser,
                                    Function::Other(all_idents),
                                    function_span,
                                )?)
                            } else {
                                r.shift_expr(Expression::Identifier(Box::new(
                                    IdentifierExpression { parts },
                                )))
                            }
                        } else {
                            r.shift_expr(Expression::Identifier(Box::new(IdentifierExpression {
                                parts,
                            })))
                        }
                    }
                }
            }
            Token::QuestionMark
                if matches!(parser.options.arguments, crate::SQLArguments::QuestionMark) =>
            {
                let arg = parser.arg;
                parser.arg += 1;
                r.shift_expr(Expression::Arg(Box::new(ArgExpression {
                    index: arg,
                    span: parser.consume_token(Token::QuestionMark)?,
                })))
            }
            Token::PercentS if matches!(parser.options.arguments, crate::SQLArguments::Percent) => {
                let arg = parser.arg;
                parser.arg += 1;
                r.shift_expr(Expression::Arg(Box::new(ArgExpression {
                    index: arg,
                    span: parser.consume_token(Token::PercentS)?,
                })))
            }
            Token::DollarArg(arg)
                if matches!(parser.options.arguments, crate::SQLArguments::Dollar) =>
            {
                r.shift_expr(Expression::Arg(Box::new(ArgExpression {
                    index: arg - 1,
                    span: parser.consume(),
                })))
            }
            Token::LParen => {
                let paren_start = parser.consume_token(Token::LParen)?;
                let first = parse_expression_paren(parser)?;
                if parser.skip_token(Token::Comma).is_some() {
                    // Row / tuple constructor: (expr1, expr2, ...)
                    let mut elements = vec![first];
                    loop {
                        if matches!(parser.token, Token::RParen) {
                            break;
                        }
                        parser.recovered(
                            "')' or ','",
                            &|t| matches!(t, Token::RParen | Token::Comma),
                            |parser| {
                                elements.push(parse_expression_paren(parser)?);
                                Ok(())
                            },
                        )?;
                        if parser.skip_token(Token::Comma).is_none() {
                            break;
                        }
                    }
                    let paren_end = parser.consume_token(Token::RParen)?;
                    r.shift_expr(Expression::Row(Box::new(RowExpression {
                        paren_span: paren_start.join_span(&paren_end),
                        elements,
                    })))
                } else {
                    parser.consume_token(Token::RParen)?;
                    r.shift_expr(first)
                }
            }
            Token::Ident(_, Keyword::EXISTS) => {
                let exists_span = parser.consume_keyword(Keyword::EXISTS)?;
                parser.consume_token(Token::LParen)?;
                let subquery = parse_compound_query(parser)?;
                parser.consume_token(Token::RParen)?;
                let ans = Expression::Exists(Box::new(ExistsExpression {
                    exists_span,
                    subquery,
                }));
                r.shift_expr(ans)
            }
            Token::Ident(_, Keyword::ANY | Keyword::SOME | Keyword::ALL)
                if parser.options.dialect.is_postgresql()
                    && !matches!(r.stack.last(), Some(ReduceMember::Expression(_))) =>
            {
                let quantifier = match &parser.token {
                    Token::Ident(_, Keyword::ANY) => {
                        Quantifier::Any(parser.consume_keyword(Keyword::ANY)?)
                    }
                    Token::Ident(_, Keyword::SOME) => {
                        Quantifier::Some(parser.consume_keyword(Keyword::SOME)?)
                    }
                    _ => Quantifier::All(parser.consume_keyword(Keyword::ALL)?),
                };
                parser.consume_token(Token::LParen)?;
                let operand = parse_expression_paren(parser)?;
                parser.consume_token(Token::RParen)?;
                r.shift_expr(Expression::Quantifier(Box::new(QuantifierExpression {
                    quantifier,
                    operand,
                })))
            }
            Token::Ident(_, Keyword::CASE) => {
                let case_span = parser.consume_keyword(Keyword::CASE)?;
                let value = if !matches!(parser.token, Token::Ident(_, Keyword::WHEN)) {
                    Some(parse_expression_unreserved(parser, PRIORITY_MAX)?)
                } else {
                    None
                };
                let mut whens = Vec::new();
                let mut else_ = None;
                parser.recovered(
                    "'END'",
                    &|t| matches!(t, Token::Ident(_, Keyword::END)),
                    |parser| {
                        loop {
                            let when_span = parser.consume_keyword(Keyword::WHEN)?;
                            let when = parse_expression_unreserved(parser, PRIORITY_MAX)?;
                            let then_span = parser.consume_keyword(Keyword::THEN)?;
                            let then = parse_expression_unreserved(parser, PRIORITY_MAX)?;
                            whens.push(When {
                                when_span,
                                when,
                                then_span,
                                then,
                            });
                            if !matches!(parser.token, Token::Ident(_, Keyword::WHEN)) {
                                break;
                            }
                        }
                        if let Some(span) = parser.skip_keyword(Keyword::ELSE) {
                            else_ = Some((span, parse_expression_unreserved(parser, PRIORITY_MAX)?))
                        };
                        Ok(())
                    },
                )?;
                let end_span = parser.consume_keyword(Keyword::END)?;
                r.shift_expr(Expression::Case(Box::new(CaseExpression {
                    case_span,
                    value,
                    whens,
                    else_,
                    end_span,
                })))
            }
            Token::AtAtGlobal | Token::AtAtSession => {
                let global = parser.skip_token(Token::AtAtGlobal);
                let session = if global.is_none() {
                    Some(parser.consume_token(Token::AtAtSession)?)
                } else {
                    None
                };
                let dot = Some(parser.consume_token(Token::Period)?);
                let variable = match &parser.token {
                    Token::Ident(_, Keyword::TIME_ZONE) => Variable::TimeZone,
                    Token::Ident(t, _) => Variable::Other(t),
                    _ => parser.expected_failure("Identifier")?,
                };
                let variable_span = parser.consume();
                r.shift_expr(Expression::Variable(Box::new(VariableExpression {
                    global,
                    session,
                    dot,
                    variable,
                    variable_span,
                })))
            }
            Token::At => {
                // User variable: @variable_name
                let at_span = parser.consume_token(Token::At)?;
                let name = parser.consume_plain_identifier_unreserved()?;
                r.shift_expr(Expression::UserVariable(Box::new(UserVariableExpression {
                    name,
                    at_span,
                })))
            }
            _ => break,
        };
        if let Err(e) = e {
            parser.err_here(e.to_string())?;
        }
    }
    if r.reduce(99999).is_err() {
        parser.err_here("Expected expression")
    } else if r.stack.len() != 1 {
        parser.ice(file!(), line!())
    } else if let Some(ReduceMember::Expression(e)) = r.stack.pop() {
        Ok(e)
    } else {
        parser.ice(file!(), line!())
    }
}

pub(crate) fn parse_expression_unreserved<'a>(
    parser: &mut Parser<'a, '_>,
    max_priority: usize,
) -> Result<Expression<'a>, ParseError> {
    parse_expression_restricted(parser, max_priority, parser.reserved())
}

/// Parse an expression that may be DEFAULT (for INSERT VALUES, INSERT SET, UPDATE SET contexts)
pub(crate) fn parse_expression_or_default<'a>(
    parser: &mut Parser<'a, '_>,
    max_priority: usize,
) -> Result<Expression<'a>, ParseError> {
    if matches!(parser.token, Token::Ident(_, Keyword::DEFAULT)) {
        Ok(Expression::Default(Box::new(DefaultExpression {
            span: parser.consume_keyword(Keyword::DEFAULT)?,
        })))
    } else {
        parse_expression_unreserved(parser, max_priority)
    }
}

pub(crate) fn parse_expression_outer<'a>(
    parser: &mut Parser<'a, '_>,
) -> Result<Expression<'a>, ParseError> {
    if matches!(parser.token, Token::Ident(_, Keyword::SELECT)) {
        Ok(Expression::Subquery(Box::new(SubqueryExpression {
            expression: parse_compound_query(parser)?,
        })))
    } else {
        parse_expression_unreserved(parser, PRIORITY_MAX)
    }
}

pub(crate) fn parse_expression_paren<'a>(
    parser: &mut Parser<'a, '_>,
) -> Result<Expression<'a>, ParseError> {
    if matches!(parser.token, Token::Ident(_, Keyword::SELECT)) {
        Ok(Expression::Subquery(Box::new(SubqueryExpression {
            expression: parse_compound_query(parser)?,
        })))
    } else {
        parse_expression_unreserved(parser, PRIORITY_MAX)
    }
}

#[cfg(test)]
mod tests {
    use core::ops::Deref;

    use alloc::{
        format,
        string::{String, ToString},
    };

    use crate::{
        BinaryExpression, ParseOptions, SQLDialect,
        expression::{BinaryOperator, Expression, PRIORITY_MAX, Quantifier},
        issue::Issues,
        parser::Parser,
    };

    use super::{IdentifierPart, parse_expression_unreserved};

    fn test_ident<'a>(e: &Expression<'a>, v: &str) -> Result<(), String> {
        let v = match e {
            Expression::Identifier(a) => match a.parts.as_slice() {
                [IdentifierPart::Name(vv)] => vv.deref() == v,
                _ => false,
            },
            _ => false,
        };
        if !v {
            Err(format!("Expected identifier {} found {:?}", v, e))
        } else {
            Ok(())
        }
    }

    fn test_expr(src: &'static str, f: impl FnOnce(&Expression<'_>) -> Result<(), String>) {
        let mut issues = Issues::new(src);
        let options = ParseOptions::new().dialect(SQLDialect::MariaDB);
        let mut parser = Parser::new(src, &mut issues, &options);
        let res = parse_expression_unreserved(&mut parser, PRIORITY_MAX)
            .expect("Expression in test expr");
        if let Err(e) = f(&res) {
            panic!("Error parsing {}: {}\nGot {:#?}", src, e, res);
        }
    }

    #[test]
    fn expressions() {
        test_expr("`a` + `b` * `c` + `d`", |e| {
            match e {
                Expression::Binary(b) => {
                    let BinaryExpression {
                        op: BinaryOperator::Add(_),
                        lhs,
                        rhs,
                        ..
                    } = b.as_ref()
                    else {
                        return Err("Expected outer +".to_string());
                    };
                    match lhs {
                        Expression::Binary(b) => {
                            let BinaryExpression {
                                op: BinaryOperator::Add(_),
                                lhs,
                                rhs,
                                ..
                            } = b.as_ref()
                            else {
                                return Err("Expected inner +".to_string());
                            };
                            test_ident(lhs, "a")?;
                            match rhs {
                                Expression::Binary(b) => {
                                    let BinaryExpression {
                                        op: BinaryOperator::Mult(_),
                                        lhs,
                                        rhs,
                                        ..
                                    } = b.as_ref()
                                    else {
                                        return Err("Expected *".to_string());
                                    };
                                    test_ident(lhs, "b")?;
                                    test_ident(rhs, "c")?;
                                }
                                _ => return Err("Lhs.Rhs".to_string()),
                            }
                        }
                        _ => return Err("Lhs".to_string()),
                    }
                    test_ident(rhs, "d")?;
                }
                _ => return Err("Outer".to_string()),
            }
            Ok(())
        });
    }

    fn test_expr_pg(src: &'static str, f: impl FnOnce(&Expression<'_>) -> Result<(), String>) {
        let mut issues = Issues::new(src);
        let options = ParseOptions::new().dialect(SQLDialect::PostgreSQL);
        let mut parser = Parser::new(src, &mut issues, &options);
        let res = parse_expression_unreserved(&mut parser, PRIORITY_MAX)
            .expect("Expression in test_expr_pg");
        if let Err(e) = f(&res) {
            panic!("Error parsing {}: {}\nGot {:#?}", src, e, res);
        }
    }

    #[test]
    fn quantifier_any() {
        test_expr_pg(
            "salary > ANY (SELECT max_salary FROM departments)",
            |e| match e {
                Expression::Binary(b) => match &b.rhs {
                    Expression::Quantifier(q) => {
                        assert!(matches!(q.quantifier, Quantifier::Any(_)));
                        Ok(())
                    }
                    _ => Err(format!("Expected Quantifier RHS, got {:?}", b.rhs)),
                },
                _ => Err(format!("Expected Binary expression, got {:?}", e)),
            },
        );
    }

    #[test]
    fn quantifier_some() {
        test_expr_pg("x = SOME (ARRAY[1, 2, 3])", |e| match e {
            Expression::Binary(b) => match &b.rhs {
                Expression::Quantifier(q) => {
                    assert!(matches!(q.quantifier, Quantifier::Some(_)));
                    Ok(())
                }
                _ => Err(format!("Expected Quantifier RHS, got {:?}", b.rhs)),
            },
            _ => Err(format!("Expected Binary expression, got {:?}", e)),
        });
    }

    #[test]
    fn quantifier_all() {
        test_expr_pg("price <= ALL (SELECT price FROM products)", |e| match e {
            Expression::Binary(b) => match &b.rhs {
                Expression::Quantifier(q) => {
                    assert!(matches!(q.quantifier, Quantifier::All(_)));
                    Ok(())
                }
                _ => Err(format!("Expected Quantifier RHS, got {:?}", b.rhs)),
            },
            _ => Err(format!("Expected Binary expression, got {:?}", e)),
        });
    }
}