libtmux 0.1.0-alpha.5

Async typed tmux client and object model (alpha)
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
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
//! Predicates and cardinality helpers for borrowed iterators.
//!
//! Start with a replayable collection, borrow it with `.iter()`, and keep
//! inline closures on native [`Iterator::filter`]. Use
//! [`QueryIteratorExt::matching`] for a named [`Matcher`] or typed
//! [`FilterExpr`], then apply exact cardinality without collecting or
//! exhausting more than two items:
//!
//! ```
//! use libtmux::query::{Matcher, QueryIteratorExt};
//!
//! struct IsPending;
//!
//! impl Matcher<(&'static str, bool)> for IsPending {
//!     fn matches(&self, candidate: &(&'static str, bool)) -> bool {
//!         !candidate.1
//!     }
//! }
//!
//! let tasks = vec![("build", false), ("test", true)];
//! let visible = tasks.iter().filter(|task| task.0.starts_with('b'));
//! assert_eq!(visible.collect::<Vec<_>>(), vec![&tasks[0]]);
//! assert_eq!(tasks.iter().matching(IsPending).exactly_one(), Ok(&tasks[0]));
//! ```
//!
//! [`QueryIteratorExt::exactly_one`] distinguishes zero from multiple items;
//! [`QueryIteratorExt::one_or_none`] permits zero but rejects multiple items.
//! Both return borrowed values and pull at most two items.
//!
//! Portable expressions are owned, inert local values. With `derive`, typed
//! handles can be generated for downstream data without exposing the hidden
//! expansion constructors:
//!
//! ```
//! # #[cfg(feature = "derive")]
//! # {
//! use libtmux::query::{Filterable as _, QueryIteratorExt as _};
//!
//! #[derive(libtmux::Filterable)]
//! #[filterable(target = "task")]
//! # #[filterable(crate = "libtmux")]
//! struct Task {
//!     name: String,
//!     done: bool,
//! }
//!
//! let tasks = vec![Task { name: "build".into(), done: false }];
//! let fields = Task::filter_fields();
//! let expression = fields.name.eq("build").and(fields.done.eq(false));
//! assert_eq!(tasks.iter().matching(&expression).count(), 1);
//! # }
//! ```
//!
//! Local matching is synchronous, ordered, and never performs tmux I/O or
//! native pushdown. Text predicates require strict candidate UTF-8, so every
//! text predicate returns false for invalid bytes, including `not_in([])`;
//! an outer [`FilterExpr::not`] may invert that result. Relations inspect only
//! already-hydrated candidate data: empty to-many data makes `any` false and
//! `all` and `none` true, while absent to-one data makes `is` false.
//!
//! The optional `derive` and `serde` features are independent. Serde uses the
//! closed version 1 grammar, whose membership values are arrays even though
//! Rust authoring accepts any `IntoIterator`. Regex operators use Rust syntax
//! and reject Python-only look-around and backreferences with source-less,
//! value-free errors. Dynamic `field__operator` parsing and remote pushdown
//! belong to later ingress and execution layers.
//!
//! Scalar field handles expose only operators valid for their field type. A
//! boolean field rejects string equality and membership:
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.eq("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.is_in(["true"]);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.not_in(["true"]);
//! ```
//!
//! Boolean fields also have none of the text-only operators:
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.eq_ignore_case("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.contains("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.contains_ignore_case("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.starts_with("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.starts_with_ignore_case("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.ends_with("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.ends_with_ignore_case("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.regex("true");
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::bool_field::<Row>("row", "done");
//! let _ = field.regex_ignore_case("true");
//! ```
//!
//! Platform-width integers are intentionally outside the portable grammar:
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, isize>("row", "count");
//! let _ = field.eq(0_isize);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, isize>("row", "count");
//! let _ = field.is_in([0_isize]);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, isize>("row", "count");
//! let _ = field.not_in([0_isize]);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, usize>("row", "count");
//! let _ = field.eq(0_usize);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, usize>("row", "count");
//! let _ = field.is_in([0_usize]);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Row;
//! let field = __private::integer_field::<Row, usize>("row", "count");
//! let _ = field.not_in([0_usize]);
//! ```
//!
//! Relation handles accept only portable expressions for their related type,
//! never closures or arbitrary matchers:
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! let relation = __private::many_relation::<Parent, Child>("parent", "children");
//! let _ = relation.any(|_: &Child| true);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::{Matcher, OneRelation};
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! struct ChildMatcher;
//! impl Matcher<Child> for ChildMatcher {
//!     fn matches(&self, _: &Child) -> bool { true }
//! }
//! let relation: OneRelation<Parent, Child> =
//!     __private::one_relation("parent", "child");
//! let _ = relation.is(ChildMatcher);
//! ```
//!
//! A relation expression cannot cross related schemas:
//!
//! ```compile_fail
//! use libtmux::query::{FilterExpressionError, Filterable};
//! use libtmux::query::__private::{self, Predicate};
//!
//! struct Parent;
//! struct Child;
//! struct Other;
//! macro_rules! filterable {
//!     ($type:ty, $target:literal) => {
//!         impl Filterable for $type {
//!             type Fields = ();
//!             const FILTER_TARGET: &'static str = $target;
//!             fn filter_fields() {}
//!             fn __filter_matches(&self, _: &Predicate) -> bool { false }
//!             fn __filter_validate(_: &Predicate) -> Result<(), FilterExpressionError> {
//!                 Ok(())
//!             }
//!         }
//!     };
//! }
//! filterable!(Child, "child");
//! filterable!(Other, "other");
//! let relation = __private::many_relation::<Parent, Child>("parent", "children");
//! let other = __private::bool_field::<Other>("other", "enabled").eq(true);
//! let _ = relation.any(other);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::{FilterExpressionError, Filterable};
//! use libtmux::query::__private::{self, Predicate};
//!
//! struct Parent;
//! struct Child;
//! struct Other;
//! macro_rules! filterable {
//!     ($type:ty, $target:literal) => {
//!         impl Filterable for $type {
//!             type Fields = ();
//!             const FILTER_TARGET: &'static str = $target;
//!             fn filter_fields() {}
//!             fn __filter_matches(&self, _: &Predicate) -> bool { false }
//!             fn __filter_validate(_: &Predicate) -> Result<(), FilterExpressionError> {
//!                 Ok(())
//!             }
//!         }
//!     };
//! }
//! filterable!(Child, "child");
//! filterable!(Other, "other");
//! let relation = __private::one_relation::<Parent, Child>("parent", "child");
//! let other = __private::bool_field::<Other>("other", "enabled").eq(true);
//! let _ = relation.is(other);
//! ```
//!
//! To-many and to-one relations expose disjoint quantifier families:
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! let relation = __private::many_relation::<Parent, Child>("parent", "children");
//! let child = __private::bool_field::<Child>("child", "enabled").eq(true);
//! let _ = relation.is(child);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! let relation = __private::one_relation::<Parent, Child>("parent", "child");
//! let child = __private::bool_field::<Child>("child", "enabled").eq(true);
//! let _ = relation.any(child);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! let relation = __private::one_relation::<Parent, Child>("parent", "child");
//! let child = __private::bool_field::<Child>("child", "enabled").eq(true);
//! let _ = relation.all(child);
//! ```
//!
//! ```compile_fail
//! use libtmux::query::__private;
//!
//! struct Parent;
//! struct Child;
//! let relation = __private::one_relation::<Parent, Child>("parent", "child");
//! let child = __private::bool_field::<Child>("child", "enabled").eq(true);
//! let _ = relation.none(child);
//! ```
//!
//! Expression error kinds are non-exhaustive for downstream callers:
//!
//! ```compile_fail
//! use libtmux::query::FilterExpressionErrorKind;
//!
//! fn label(kind: FilterExpressionErrorKind) -> &'static str {
//!     match kind {
//!         FilterExpressionErrorKind::InvalidRegex => "invalid regex",
//!         FilterExpressionErrorKind::UnsupportedVersion => "unsupported version",
//!         FilterExpressionErrorKind::InvalidTarget => "invalid target",
//!         FilterExpressionErrorKind::UnknownField => "unknown field",
//!         FilterExpressionErrorKind::UnknownOperator => "unknown operator",
//!         FilterExpressionErrorKind::UnknownQuantifier => "unknown quantifier",
//!         FilterExpressionErrorKind::InvalidLiteral => "invalid literal",
//!         FilterExpressionErrorKind::InvalidStructure => "invalid structure",
//!     }
//! }
//! ```

use std::fmt;
use std::marker::PhantomData;
#[cfg(feature = "serde")]
use std::sync::OnceLock;

use caseless::default_case_fold_str;
use regex::{Regex, RegexBuilder};

/// A predicate that evaluates a borrowed candidate.
///
/// Functions and closures with the same signature implement this trait.
///
/// # Examples
///
/// ```
/// use libtmux::query::Matcher;
///
/// struct IsEven;
///
/// impl Matcher<i32> for IsEven {
///     fn matches(&self, candidate: &i32) -> bool {
///         candidate % 2 == 0
///     }
/// }
///
/// assert!(IsEven.matches(&2));
/// assert!(!IsEven.matches(&3));
/// ```
pub trait Matcher<T> {
    /// Return whether `candidate` matches this predicate.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::Matcher;
    ///
    /// let is_positive = |candidate: &i32| *candidate > 0;
    /// assert!(is_positive.matches(&1));
    /// assert!(!is_positive.matches(&-1));
    /// ```
    fn matches(&self, candidate: &T) -> bool;
}

impl<T, F> Matcher<T> for F
where
    F: Fn(&T) -> bool,
{
    fn matches(&self, candidate: &T) -> bool {
        self(candidate)
    }
}

/// The ways an iterator can fail to contain exactly one item.
///
/// # Examples
///
/// ```
/// use libtmux::query::{ExactlyOneError, QueryIteratorExt};
///
/// let values: Vec<i32> = Vec::new();
/// assert_eq!(values.iter().exactly_one(), Err(ExactlyOneError::NoItems));
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExactlyOneError {
    /// The iterator contained no items.
    NoItems,
    /// The iterator contained more than one item.
    MultipleItems,
}

impl fmt::Display for ExactlyOneError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoItems => formatter.write_str("expected exactly one item, found none"),
            Self::MultipleItems => formatter.write_str("expected exactly one item, found multiple"),
        }
    }
}

impl std::error::Error for ExactlyOneError {}

/// An error indicating that an iterator contained more than one item.
///
/// # Examples
///
/// ```
/// use libtmux::query::{MultipleItemsError, QueryIteratorExt};
///
/// let values = [1, 2];
/// assert_eq!(values.iter().one_or_none(), Err(MultipleItemsError));
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MultipleItemsError;

impl fmt::Display for MultipleItemsError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("expected at most one item, found multiple")
    }
}

impl std::error::Error for MultipleItemsError {}

/// Cardinality and named-predicate operations for borrowed iterators.
///
/// # Examples
///
/// ```
/// use libtmux::query::QueryIteratorExt;
///
/// let values = [1, 2, 3];
/// assert_eq!(values.iter().exactly_one(), Err(libtmux::query::ExactlyOneError::MultipleItems));
/// ```
#[allow(clippy::module_name_repetitions)]
pub trait QueryIteratorExt<'a, T: 'a>: Iterator<Item = &'a T> + Sized {
    /// Lazily yield candidates accepted by `matcher`.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{Matcher, QueryIteratorExt};
    ///
    /// struct IsEven;
    ///
    /// impl Matcher<i32> for IsEven {
    ///     fn matches(&self, candidate: &i32) -> bool {
    ///         candidate % 2 == 0
    ///     }
    /// }
    ///
    /// let values = [1, 2, 3, 4];
    /// let selected = values.iter().matching(IsEven).copied().collect::<Vec<_>>();
    /// assert_eq!(selected, [2, 4]);
    /// ```
    fn matching<M: Matcher<T>>(self, matcher: M) -> impl Iterator<Item = &'a T> {
        self.filter(move |candidate| matcher.matches(*candidate))
    }

    /// Return the only item, or an error for zero or multiple items.
    ///
    /// At most two items are pulled from the iterator.
    ///
    /// # Errors
    ///
    /// Returns [`ExactlyOneError::NoItems`] for an empty iterator and
    /// [`ExactlyOneError::MultipleItems`] when a second item is present.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::QueryIteratorExt;
    ///
    /// let values = [7];
    /// assert_eq!(values.iter().exactly_one(), Ok(&values[0]));
    /// ```
    fn exactly_one(mut self) -> Result<&'a T, ExactlyOneError> {
        let Some(item) = self.next() else {
            return Err(ExactlyOneError::NoItems);
        };

        if self.next().is_some() {
            Err(ExactlyOneError::MultipleItems)
        } else {
            Ok(item)
        }
    }

    /// Return zero or one item, or an error for multiple items.
    ///
    /// At most two items are pulled from the iterator.
    ///
    /// # Errors
    ///
    /// Returns [`MultipleItemsError`] when a second item is present.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::QueryIteratorExt;
    ///
    /// let empty: Vec<i32> = Vec::new();
    /// assert_eq!(empty.iter().one_or_none(), Ok(None));
    ///
    /// let values = [7];
    /// assert_eq!(values.iter().one_or_none(), Ok(Some(&values[0])));
    /// ```
    fn one_or_none(mut self) -> Result<Option<&'a T>, MultipleItemsError> {
        let item = self.next();
        if item.is_some() && self.next().is_some() {
            Err(MultipleItemsError)
        } else {
            Ok(item)
        }
    }
}

impl<'a, T: 'a, I> QueryIteratorExt<'a, T> for I where I: Iterator<Item = &'a T> + Sized {}

/// The category of an invalid portable filter expression.
///
/// Callers must retain a wildcard arm because future schema versions may add
/// more source-less validation categories.
///
/// # Examples
///
/// ```
/// use libtmux::query::FilterExpressionErrorKind;
///
/// let kind = FilterExpressionErrorKind::InvalidRegex;
/// assert_eq!(kind, FilterExpressionErrorKind::InvalidRegex);
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FilterExpressionErrorKind {
    /// A regular expression did not compile under the version 1 dialect.
    InvalidRegex,
    /// The serialized expression schema version is unsupported.
    UnsupportedVersion,
    /// The expression target does not match the requested candidate type.
    InvalidTarget,
    /// The candidate schema has no field with the requested stable name.
    UnknownField,
    /// The field type does not support the requested operator.
    UnknownOperator,
    /// A relation does not support the requested quantifier.
    UnknownQuantifier,
    /// A literal cannot be represented by the field type.
    InvalidLiteral,
    /// The expression tree has an invalid shape.
    InvalidStructure,
}

/// A source-less, value-free portable expression validation error.
///
/// The error retains only its category. In particular, it never retains a
/// regex pattern, field literal, or rejected serialized value.
///
/// # Examples
///
/// ```
/// use libtmux::query::{FilterExpressionErrorKind, TextField};
/// use libtmux::query::__private;
///
/// struct Row;
/// let field: TextField<Row> = __private::text_field("row", "name");
/// let error = field.regex("[").expect_err("the pattern is invalid");
/// assert_eq!(error.kind(), FilterExpressionErrorKind::InvalidRegex);
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FilterExpressionError {
    kind: FilterExpressionErrorKind,
}

impl FilterExpressionError {
    const fn new(kind: FilterExpressionErrorKind) -> Self {
        Self { kind }
    }

    /// Return the value-free validation category.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::FilterExpressionErrorKind;
    /// use libtmux::query::__private;
    ///
    /// let error = __private::unknown_field_error();
    /// assert_eq!(error.kind(), FilterExpressionErrorKind::UnknownField);
    /// ```
    #[must_use]
    pub const fn kind(&self) -> FilterExpressionErrorKind {
        self.kind
    }
}

impl fmt::Display for FilterExpressionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self.kind {
            FilterExpressionErrorKind::InvalidRegex => "invalid regular expression",
            FilterExpressionErrorKind::UnsupportedVersion => "unsupported expression version",
            FilterExpressionErrorKind::InvalidTarget => "invalid expression target",
            FilterExpressionErrorKind::UnknownField => "unknown expression field",
            FilterExpressionErrorKind::UnknownOperator => "unknown expression operator",
            FilterExpressionErrorKind::UnknownQuantifier => "unknown relation quantifier",
            FilterExpressionErrorKind::InvalidLiteral => "invalid expression literal",
            FilterExpressionErrorKind::InvalidStructure => "invalid expression structure",
        })
    }
}

impl std::error::Error for FilterExpressionError {}

/// Stable string semantics for a custom enum filter field.
///
/// Every value returned by [`FilterEnum::filter_name`] must be present in
/// [`FilterEnum::FILTER_VARIANTS`], and the variant names must be unique.
///
/// # Examples
///
/// ```
/// use libtmux::query::FilterEnum;
///
/// enum State {
///     Ready,
///     Blocked,
/// }
///
/// impl FilterEnum for State {
///     const FILTER_VARIANTS: &'static [&'static str] = &["ready", "blocked"];
///
///     fn filter_name(&self) -> &'static str {
///         match self {
///             Self::Ready => "ready",
///             Self::Blocked => "blocked",
///         }
///     }
/// }
///
/// assert_eq!(State::Ready.filter_name(), "ready");
/// # let _ = State::Blocked;
/// ```
pub trait FilterEnum {
    /// Every stable string accepted for this enum field.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::FilterEnum;
    ///
    /// enum State { Ready }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
    ///     fn filter_name(&self) -> &'static str { "ready" }
    /// }
    /// assert_eq!(State::FILTER_VARIANTS, ["ready"]);
    /// # let _ = State::Ready;
    /// ```
    const FILTER_VARIANTS: &'static [&'static str];

    /// Return this value's stable filter string.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::FilterEnum;
    ///
    /// enum State { Ready }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
    ///     fn filter_name(&self) -> &'static str { "ready" }
    /// }
    /// assert_eq!(State::Ready.filter_name(), "ready");
    /// ```
    fn filter_name(&self) -> &'static str;
}

/// A type with a stable schema that can evaluate portable filter predicates.
///
/// This trait is designed for generated implementations; the example spells
/// out that ABI by hand. Methods prefixed with `__filter_` are not ordinary
/// authoring hooks.
///
/// # Examples
///
/// ```
/// use std::error::Error as _;
///
/// use libtmux::query::{
///     BoolField, EnumField, FilterEnum, FilterExpressionError,
///     FilterExpressionErrorKind, Filterable, IntegerField, TextField,
/// };
/// use libtmux::query::__private::{self, IntegerKind, Predicate};
///
/// enum State {
///     Ready,
/// }
///
/// impl FilterEnum for State {
///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
///
///     fn filter_name(&self) -> &'static str {
///         match self {
///             Self::Ready => "ready",
///         }
///     }
/// }
///
/// struct Task {
///     name: &'static [u8],
///     done: bool,
///     priority: i8,
///     retries: u8,
///     state: State,
/// }
///
/// struct TaskFields {
///     name: TextField<Task>,
///     done: BoolField<Task>,
///     priority: IntegerField<Task, i8>,
///     retries: IntegerField<Task, u8>,
///     state: EnumField<Task, State>,
/// }
///
/// impl Filterable for Task {
///     type Fields = TaskFields;
///     const FILTER_TARGET: &'static str = "task";
///
///     fn filter_fields() -> Self::Fields {
///         TaskFields {
///             name: __private::text_field(Self::FILTER_TARGET, "name"),
///             done: __private::bool_field(Self::FILTER_TARGET, "done"),
///             priority: __private::integer_field(Self::FILTER_TARGET, "priority"),
///             retries: __private::integer_field(Self::FILTER_TARGET, "retries"),
///             state: __private::enum_field(Self::FILTER_TARGET, "state"),
///         }
///     }
///
///     fn __filter_matches(&self, predicate: &Predicate) -> bool {
///         Self::__filter_validate(predicate)
///             .expect("typed field expressions must validate before matching");
///         match predicate.field() {
///             "name" => predicate.matches_text(self.name),
///             "done" => predicate.matches_bool(self.done),
///             "priority" => predicate.matches_signed(i128::from(self.priority)),
///             "retries" => predicate.matches_unsigned(u128::from(self.retries)),
///             "state" => predicate.matches_enum(self.state.filter_name()),
///             _ => false,
///         }
///     }
///
///     fn __filter_validate(predicate: &Predicate) -> Result<(), FilterExpressionError> {
///         match predicate.field() {
///             "name" => predicate.validate_text(),
///             "done" => predicate.validate_bool(),
///             "priority" => predicate.validate_integer(IntegerKind::I8),
///             "retries" => predicate.validate_integer(IntegerKind::U8),
///             "state" => predicate.validate_enum(State::FILTER_VARIANTS),
///             _ => Err(__private::unknown_field_error()),
///         }
///     }
/// }
///
/// let task = Task {
///     name: b"build",
///     done: false,
///     priority: -1,
///     retries: 2,
///     state: State::Ready,
/// };
/// let fields = Task::filter_fields();
/// assert!(fields.name.eq("build").matches(&task));
/// assert!(fields.done.eq(false).matches(&task));
/// assert!(fields.priority.eq(-1).matches(&task));
/// assert!(fields.retries.eq(2).matches(&task));
/// assert!(fields.state.eq(State::Ready).matches(&task));
///
/// let error = __private::unknown_field_error();
/// assert_eq!(error.kind(), FilterExpressionErrorKind::UnknownField);
/// assert!(error.source().is_none());
/// ```
///
/// Generated relation dispatch uses the same opaque predicate ABI for
/// already-loaded `Vec<T>` and `Option<T>` fields:
///
/// ```
/// use libtmux::query::{
///     BoolField, FilterExpressionError, Filterable, ManyRelation, OneRelation,
/// };
/// use libtmux::query::__private::{self, Predicate};
///
/// struct Child {
///     done: bool,
/// }
///
/// struct ChildFields {
///     done: BoolField<Child>,
/// }
///
/// impl Filterable for Child {
///     type Fields = ChildFields;
///     const FILTER_TARGET: &'static str = "child";
///
///     fn filter_fields() -> Self::Fields {
///         ChildFields {
///             done: __private::bool_field(Self::FILTER_TARGET, "done"),
///         }
///     }
///
///     fn __filter_matches(&self, predicate: &Predicate) -> bool {
///         assert!(Self::__filter_validate(predicate).is_ok());
///         match predicate.field() {
///             "done" => predicate.matches_bool(self.done),
///             _ => false,
///         }
///     }
///
///     fn __filter_validate(predicate: &Predicate) -> Result<(), FilterExpressionError> {
///         match predicate.field() {
///             "done" => predicate.validate_bool(),
///             _ => Err(__private::unknown_field_error()),
///         }
///     }
/// }
///
/// struct Parent {
///     children: Vec<Child>,
///     favorite: Option<Child>,
/// }
///
/// struct ParentFields {
///     children: ManyRelation<Parent, Child>,
///     favorite: OneRelation<Parent, Child>,
/// }
///
/// impl Filterable for Parent {
///     type Fields = ParentFields;
///     const FILTER_TARGET: &'static str = "parent";
///
///     fn filter_fields() -> Self::Fields {
///         ParentFields {
///             children: __private::many_relation(Self::FILTER_TARGET, "children"),
///             favorite: __private::one_relation(Self::FILTER_TARGET, "favorite"),
///         }
///     }
///
///     fn __filter_matches(&self, predicate: &Predicate) -> bool {
///         assert!(Self::__filter_validate(predicate).is_ok());
///         match predicate.field() {
///             "children" => predicate.matches_many(&self.children),
///             "favorite" => predicate.matches_one(self.favorite.as_ref()),
///             _ => false,
///         }
///     }
///
///     fn __filter_validate(predicate: &Predicate) -> Result<(), FilterExpressionError> {
///         match predicate.field() {
///             "children" => predicate.validate_many::<Child>(),
///             "favorite" => predicate.validate_one::<Child>(),
///             _ => Err(__private::unknown_field_error()),
///         }
///     }
/// }
///
/// let parent = Parent {
///     children: vec![Child { done: false }, Child { done: true }],
///     favorite: Some(Child { done: false }),
/// };
/// let parent_fields = Parent::filter_fields();
/// let child_done = Child::filter_fields().done;
/// assert!(parent_fields.children.any(child_done.eq(false)).matches(&parent));
/// assert!(
///     parent_fields
///         .children
///         .all(child_done.is_in([false, true]))
///         .matches(&parent)
/// );
/// assert!(
///     parent_fields
///         .children
///         .none(child_done.not_in([false, true]))
///         .matches(&parent)
/// );
/// assert!(parent_fields.favorite.is(child_done.eq(false)).matches(&parent));
/// ```
pub trait Filterable: Sized {
    /// The generated companion value containing this type's field handles.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::Filterable;
    ///
    /// fn generated_fields<T: Filterable>() -> T::Fields {
    ///     T::filter_fields()
    /// }
    /// let _ = generated_fields::<T>;
    /// # struct T;
    /// # impl Filterable for T {
    /// #     type Fields = ();
    /// #     const FILTER_TARGET: &'static str = "t";
    /// #     fn filter_fields() {}
    /// #     fn __filter_matches(&self, _: &libtmux::query::__private::Predicate) -> bool { false }
    /// #     fn __filter_validate(_: &libtmux::query::__private::Predicate) -> Result<(), libtmux::query::FilterExpressionError> { Ok(()) }
    /// # }
    /// ```
    type Fields;

    /// The stable target name used by portable expression envelopes.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::Filterable;
    ///
    /// fn target<T: Filterable>() -> &'static str {
    ///     T::FILTER_TARGET
    /// }
    /// # let _ = target::<T>;
    /// # struct T;
    /// # impl Filterable for T {
    /// #     type Fields = ();
    /// #     const FILTER_TARGET: &'static str = "t";
    /// #     fn filter_fields() {}
    /// #     fn __filter_matches(&self, _: &libtmux::query::__private::Predicate) -> bool { false }
    /// #     fn __filter_validate(_: &libtmux::query::__private::Predicate) -> Result<(), libtmux::query::FilterExpressionError> { Ok(()) }
    /// # }
    /// ```
    const FILTER_TARGET: &'static str;

    /// Return typed handles for this candidate schema.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::Filterable;
    ///
    /// fn generated_fields<T: Filterable>() -> T::Fields {
    ///     T::filter_fields()
    /// }
    /// # let _ = generated_fields::<T>;
    /// # struct T;
    /// # impl Filterable for T {
    /// #     type Fields = ();
    /// #     const FILTER_TARGET: &'static str = "t";
    /// #     fn filter_fields() {}
    /// #     fn __filter_matches(&self, _: &libtmux::query::__private::Predicate) -> bool { false }
    /// #     fn __filter_validate(_: &libtmux::query::__private::Predicate) -> Result<(), libtmux::query::FilterExpressionError> { Ok(()) }
    /// # }
    /// ```
    #[must_use]
    fn filter_fields() -> Self::Fields;

    /// Evaluate one already-validated predicate against this candidate.
    ///
    /// The trait-level example executes this method for every scalar field
    /// family in a hand-written generated-code expansion.
    #[doc(hidden)]
    fn __filter_matches(&self, predicate: &__private::Predicate) -> bool;

    /// Validate one opaque predicate against this candidate schema.
    ///
    /// # Errors
    ///
    /// Returns a source-less validation category for a schema mismatch.
    ///
    /// The trait-level example executes this method for every scalar field
    /// family in a hand-written generated-code expansion.
    #[doc(hidden)]
    fn __filter_validate(predicate: &__private::Predicate) -> Result<(), FilterExpressionError>;
}

#[derive(Clone, Copy, Eq, PartialEq)]
struct FieldId {
    target: &'static str,
    field: &'static str,
}

#[cfg(feature = "serde")]
fn set_once_eq<T: Eq>(
    cell: &OnceLock<T>,
    value: T,
    error_kind: FilterExpressionErrorKind,
) -> Result<(), FilterExpressionError> {
    match cell.set(value) {
        Ok(()) => Ok(()),
        Err(value) if cell.get() == Some(&value) => Ok(()),
        Err(_) => Err(FilterExpressionError::new(error_kind)),
    }
}

enum PredicateIdentity {
    Static(FieldId),
    #[cfg(feature = "serde")]
    Wire {
        target: OnceLock<&'static str>,
        field: String,
    },
}

impl PredicateIdentity {
    fn clone_internal(&self) -> Self {
        match self {
            Self::Static(id) => Self::Static(*id),
            #[cfg(feature = "serde")]
            Self::Wire { target, field } => {
                let cloned_target = OnceLock::new();
                if let Some(target) = target.get() {
                    let _ = cloned_target.set(*target);
                }
                Self::Wire {
                    target: cloned_target,
                    field: field.clone(),
                }
            }
        }
    }

    fn field(&self) -> &str {
        match self {
            Self::Static(id) => id.field,
            #[cfg(feature = "serde")]
            Self::Wire { field, .. } => field,
        }
    }

    fn target(&self) -> &str {
        match self {
            Self::Static(id) => id.target,
            #[cfg(feature = "serde")]
            Self::Wire { target, .. } => target.get().copied().unwrap_or_default(),
        }
    }

    fn bind_target(&self, target: &'static str) -> Result<(), FilterExpressionError> {
        match self {
            Self::Static(id) if id.target == target => Ok(()),
            Self::Static(_) => Err(FilterExpressionError::new(
                FilterExpressionErrorKind::InvalidTarget,
            )),
            #[cfg(feature = "serde")]
            Self::Wire {
                target: resolved, ..
            } => set_once_eq(resolved, target, FilterExpressionErrorKind::InvalidTarget),
        }
    }
}

impl PartialEq for PredicateIdentity {
    fn eq(&self, other: &Self) -> bool {
        self.target() == other.target() && self.field() == other.field()
    }
}

impl Eq for PredicateIdentity {}

#[derive(Clone, Copy, Eq, PartialEq)]
#[cfg_attr(
    not(feature = "serde"),
    allow(
        dead_code,
        reason = "ordering reaches text only from the wire, which serde gates"
    )
)]
enum TextOperator {
    Eq,
    EqIgnoreCase,
    Contains,
    ContainsIgnoreCase,
    StartsWith,
    StartsWithIgnoreCase,
    EndsWith,
    EndsWithIgnoreCase,
    In,
    NotIn,
    Regex,
    RegexIgnoreCase,
    Lt,
    Lte,
    Gt,
    Gte,
}

impl TextOperator {
    const fn label(self) -> &'static str {
        match self {
            Self::Eq => "eq",
            Self::EqIgnoreCase => "eq_ignore_case",
            Self::Contains => "contains",
            Self::ContainsIgnoreCase => "contains_ignore_case",
            Self::StartsWith => "starts_with",
            Self::StartsWithIgnoreCase => "starts_with_ignore_case",
            Self::EndsWith => "ends_with",
            Self::EndsWithIgnoreCase => "ends_with_ignore_case",
            Self::In => "in",
            Self::NotIn => "not_in",
            Self::Regex => "regex",
            Self::RegexIgnoreCase => "regex_ignore_case",
            Self::Lt => "lt",
            Self::Lte => "lte",
            Self::Gt => "gt",
            Self::Gte => "gte",
        }
    }

    /// Report whether this operator compares order, which text cannot.
    const fn is_ordering(self) -> bool {
        matches!(self, Self::Lt | Self::Lte | Self::Gt | Self::Gte)
    }

    const fn is_regex(self) -> bool {
        matches!(self, Self::Regex | Self::RegexIgnoreCase)
    }

    #[cfg(feature = "serde")]
    const fn set_operator(self) -> Option<SetOperator> {
        match self {
            Self::Eq => Some(SetOperator::Eq),
            Self::In => Some(SetOperator::In),
            Self::NotIn => Some(SetOperator::NotIn),
            Self::Lt => Some(SetOperator::Lt),
            Self::Lte => Some(SetOperator::Lte),
            Self::Gt => Some(SetOperator::Gt),
            Self::Gte => Some(SetOperator::Gte),
            Self::EqIgnoreCase
            | Self::Contains
            | Self::ContainsIgnoreCase
            | Self::StartsWith
            | Self::StartsWithIgnoreCase
            | Self::EndsWith
            | Self::EndsWithIgnoreCase
            | Self::Regex
            | Self::RegexIgnoreCase => None,
        }
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum SetOperator {
    Eq,
    In,
    NotIn,
    Lt,
    Lte,
    Gt,
    Gte,
}

impl SetOperator {
    /// Report whether this operator compares order rather than membership.
    ///
    /// An ordering operator takes exactly one bound, where `in` takes a set.
    const fn is_ordering(self) -> bool {
        matches!(self, Self::Lt | Self::Lte | Self::Gt | Self::Gte)
    }

    /// Report whether this operator's operand is a set rather than one value.
    ///
    /// Only the wire cares: the typed handles fix the arity at the call site.
    #[cfg(feature = "serde")]
    const fn takes_a_set(self) -> bool {
        matches!(self, Self::In | Self::NotIn)
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum RelationQuantifier {
    Any,
    All,
    None,
    Is,
}

impl RelationQuantifier {
    const fn label(self) -> &'static str {
        match self {
            Self::Any => "any",
            Self::All => "all",
            Self::None => "none",
            Self::Is => "is",
        }
    }
}

impl SetOperator {
    const fn label(self) -> &'static str {
        match self {
            Self::Eq => "eq",
            Self::In => "in",
            Self::NotIn => "not_in",
            Self::Lt => "lt",
            Self::Lte => "lte",
            Self::Gt => "gt",
            Self::Gte => "gte",
        }
    }
}

#[derive(Clone)]
struct TextPredicate {
    operator: TextOperator,
    values: Vec<String>,
    compiled_regex: Option<Regex>,
}

impl PartialEq for TextPredicate {
    fn eq(&self, other: &Self) -> bool {
        self.operator == other.operator && self.values == other.values
    }
}

impl Eq for TextPredicate {}

#[derive(Clone, Eq, PartialEq)]
struct SetPredicate<T> {
    operator: SetOperator,
    values: Vec<T>,
}

#[derive(Clone, Eq, PartialEq)]
struct RelationPredicate {
    quantifier: RelationQuantifier,
    expression: Box<ExprData>,
}

#[cfg(feature = "serde")]
#[derive(Clone, Eq, PartialEq)]
enum WireStringResolved {
    Text(TextPredicate),
    Signed(SetPredicate<i128>),
    Unsigned(SetPredicate<u128>),
    Enum(SetPredicate<String>),
}

#[cfg(feature = "serde")]
struct WireStringPredicate {
    operator: TextOperator,
    values: Vec<String>,
    resolved: OnceLock<WireStringResolved>,
}

#[cfg(feature = "serde")]
impl Clone for WireStringPredicate {
    fn clone(&self) -> Self {
        let resolved = OnceLock::new();
        if let Some(value) = self.resolved.get() {
            let _ = resolved.set(value.clone());
        }
        Self {
            operator: self.operator,
            values: self.values.clone(),
            resolved,
        }
    }
}

#[cfg(feature = "serde")]
struct WireBoolPredicate {
    operator: SetOperator,
    values: Vec<bool>,
    resolved: OnceLock<()>,
}

#[cfg(feature = "serde")]
impl Clone for WireBoolPredicate {
    fn clone(&self) -> Self {
        let resolved = OnceLock::new();
        if self.resolved.get().is_some() {
            let _ = resolved.set(());
        }
        Self {
            operator: self.operator,
            values: self.values.clone(),
            resolved,
        }
    }
}

#[cfg(feature = "serde")]
#[derive(Clone, Copy, Eq, PartialEq)]
enum WireEmptyResolved {
    Text,
    Bool,
    Signed,
    Unsigned,
    Enum,
}

#[cfg(feature = "serde")]
struct WireEmptyPredicate {
    operator: SetOperator,
    resolved: OnceLock<WireEmptyResolved>,
}

#[cfg(feature = "serde")]
impl Clone for WireEmptyPredicate {
    fn clone(&self) -> Self {
        let resolved = OnceLock::new();
        if let Some(value) = self.resolved.get() {
            let _ = resolved.set(*value);
        }
        Self {
            operator: self.operator,
            resolved,
        }
    }
}

/// Evaluate one operator against its operands.
///
/// Ordering compares against the single bound `has_valid_shape` requires;
/// a malformed predicate that reached here matches nothing rather than
/// panicking on an absent bound.
fn set_matches<T: PartialOrd>(operator: SetOperator, values: &[T], candidate: &T) -> bool {
    match operator {
        SetOperator::Eq | SetOperator::In => values.contains(candidate),
        SetOperator::NotIn => !values.contains(candidate),
        SetOperator::Lt => values.first().is_some_and(|bound| candidate < bound),
        SetOperator::Lte => values.first().is_some_and(|bound| candidate <= bound),
        SetOperator::Gt => values.first().is_some_and(|bound| candidate > bound),
        SetOperator::Gte => values.first().is_some_and(|bound| candidate >= bound),
    }
}

impl<T: PartialOrd> SetPredicate<T> {
    fn matches(&self, candidate: &T) -> bool {
        set_matches(self.operator, &self.values, candidate)
    }

    /// Report whether the operator and its operands agree.
    ///
    /// `eq` takes one value and an ordering operator takes one bound; only
    /// `in` and `not_in` take a set.
    fn has_valid_shape(&self) -> bool {
        if self.operator == SetOperator::Eq || self.operator.is_ordering() {
            self.values.len() == 1
        } else {
            true
        }
    }
}

#[derive(Clone)]
enum PredicateData {
    Text(TextPredicate),
    Bool(SetPredicate<bool>),
    Signed(SetPredicate<i128>),
    Unsigned(SetPredicate<u128>),
    Enum(SetPredicate<String>),
    Relation(RelationPredicate),
    #[cfg(feature = "serde")]
    WireString(WireStringPredicate),
    #[cfg(feature = "serde")]
    WireBool(WireBoolPredicate),
    #[cfg(feature = "serde")]
    WireEmpty(WireEmptyPredicate),
}

impl PredicateData {
    fn operator_label(&self) -> &str {
        match self {
            Self::Text(predicate) => predicate.operator.label(),
            Self::Bool(predicate) => predicate.operator.label(),
            Self::Signed(predicate) => predicate.operator.label(),
            Self::Unsigned(predicate) => predicate.operator.label(),
            Self::Enum(predicate) => predicate.operator.label(),
            Self::Relation(_) => "relation",
            #[cfg(feature = "serde")]
            Self::WireString(predicate) => predicate.operator.label(),
            #[cfg(feature = "serde")]
            Self::WireBool(predicate) => predicate.operator.label(),
            #[cfg(feature = "serde")]
            Self::WireEmpty(predicate) => predicate.operator.label(),
        }
    }

    #[cfg(feature = "serde")]
    fn scalar(&self) -> Option<ResolvedScalar<'_>> {
        match self {
            Self::Text(predicate) => Some(ResolvedScalar::Text(
                predicate.operator,
                &predicate.values,
                predicate.compiled_regex.as_ref(),
            )),
            Self::Bool(predicate) => {
                Some(ResolvedScalar::Bool(predicate.operator, &predicate.values))
            }
            Self::Signed(predicate) => Some(ResolvedScalar::Signed(
                predicate.operator,
                &predicate.values,
            )),
            Self::Unsigned(predicate) => Some(ResolvedScalar::Unsigned(
                predicate.operator,
                &predicate.values,
            )),
            Self::Enum(predicate) => {
                Some(ResolvedScalar::Enum(predicate.operator, &predicate.values))
            }
            Self::WireString(predicate) => match predicate.resolved.get()? {
                WireStringResolved::Text(value) => Some(ResolvedScalar::Text(
                    value.operator,
                    &value.values,
                    value.compiled_regex.as_ref(),
                )),
                WireStringResolved::Signed(value) => {
                    Some(ResolvedScalar::Signed(value.operator, &value.values))
                }
                WireStringResolved::Unsigned(value) => {
                    Some(ResolvedScalar::Unsigned(value.operator, &value.values))
                }
                WireStringResolved::Enum(value) => {
                    Some(ResolvedScalar::Enum(value.operator, &value.values))
                }
            },
            Self::WireBool(predicate) if predicate.resolved.get().is_some() => {
                Some(ResolvedScalar::Bool(predicate.operator, &predicate.values))
            }
            Self::WireEmpty(predicate) => match predicate.resolved.get()? {
                WireEmptyResolved::Text => Some(ResolvedScalar::Text(
                    TextOperator::from_set(predicate.operator)?,
                    &[],
                    None,
                )),
                WireEmptyResolved::Bool => Some(ResolvedScalar::Bool(predicate.operator, &[])),
                WireEmptyResolved::Signed => Some(ResolvedScalar::Signed(predicate.operator, &[])),
                WireEmptyResolved::Unsigned => {
                    Some(ResolvedScalar::Unsigned(predicate.operator, &[]))
                }
                WireEmptyResolved::Enum => Some(ResolvedScalar::Enum(predicate.operator, &[])),
            },
            Self::Relation(_) | Self::WireBool(_) => None,
        }
    }

    #[cfg(feature = "serde")]
    fn is_resolved(&self) -> bool {
        match self {
            Self::WireString(predicate) => predicate.resolved.get().is_some(),
            Self::WireBool(predicate) => predicate.resolved.get().is_some(),
            Self::WireEmpty(predicate) => predicate.resolved.get().is_some(),
            Self::Text(_)
            | Self::Bool(_)
            | Self::Signed(_)
            | Self::Unsigned(_)
            | Self::Enum(_)
            | Self::Relation(_) => true,
        }
    }
}

impl TextOperator {
    /// Return the text operator matching a set operator, when one exists.
    ///
    /// Text has no ordering, so an ordering operator has no text form. One
    /// cannot reach here in practice: this converts an empty operand list,
    /// and an ordering operator with no bound fails its shape check first.
    #[cfg(feature = "serde")]
    const fn from_set(operator: SetOperator) -> Option<Self> {
        match operator {
            SetOperator::Eq => Some(Self::Eq),
            SetOperator::In => Some(Self::In),
            SetOperator::NotIn => Some(Self::NotIn),
            SetOperator::Lt | SetOperator::Lte | SetOperator::Gt | SetOperator::Gte => None,
        }
    }
}

#[cfg(feature = "serde")]
#[derive(Clone, Copy)]
enum ResolvedScalar<'a> {
    Text(TextOperator, &'a [String], Option<&'a Regex>),
    Bool(SetOperator, &'a [bool]),
    Signed(SetOperator, &'a [i128]),
    Unsigned(SetOperator, &'a [u128]),
    Enum(SetOperator, &'a [String]),
}

#[cfg(feature = "serde")]
impl PartialEq for ResolvedScalar<'_> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Text(left_op, left, _), Self::Text(right_op, right, _)) => {
                left_op == right_op && left == right
            }
            (Self::Bool(left_op, left), Self::Bool(right_op, right)) => {
                left_op == right_op && left == right
            }
            (Self::Signed(left_op, left), Self::Signed(right_op, right)) => {
                left_op == right_op && left == right
            }
            (Self::Unsigned(left_op, left), Self::Unsigned(right_op, right)) => {
                left_op == right_op && left == right
            }
            (Self::Enum(left_op, left), Self::Enum(right_op, right)) => {
                left_op == right_op && left == right
            }
            _ => false,
        }
    }
}

impl PartialEq for PredicateData {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Relation(left), Self::Relation(right)) => left == right,
            #[cfg(feature = "serde")]
            _ => self.scalar() == other.scalar(),
            #[cfg(not(feature = "serde"))]
            (Self::Text(left), Self::Text(right)) => left == right,
            #[cfg(not(feature = "serde"))]
            (Self::Bool(left), Self::Bool(right)) => left == right,
            #[cfg(not(feature = "serde"))]
            (Self::Signed(left), Self::Signed(right)) => left == right,
            #[cfg(not(feature = "serde"))]
            (Self::Unsigned(left), Self::Unsigned(right)) => left == right,
            #[cfg(not(feature = "serde"))]
            (Self::Enum(left), Self::Enum(right)) => left == right,
            #[cfg(not(feature = "serde"))]
            _ => false,
        }
    }
}

impl Eq for PredicateData {}

fn evaluate<T: Filterable>(expression: &ExprData, candidate: &T) -> bool {
    match expression {
        ExprData::Predicate(predicate) => candidate.__filter_matches(predicate),
        ExprData::And(expressions) => expressions
            .iter()
            .all(|expression| evaluate(expression, candidate)),
        ExprData::Or(expressions) => expressions
            .iter()
            .any(|expression| evaluate(expression, candidate)),
        ExprData::Not(expression) => !evaluate(expression, candidate),
        #[cfg(feature = "serde")]
        ExprData::Invalid(_) => false,
    }
}

fn validate_expression<T: Filterable>(expression: &ExprData) -> Result<(), FilterExpressionError> {
    match expression {
        ExprData::Predicate(predicate) => {
            predicate.bind_target_internal(T::FILTER_TARGET)?;
            #[cfg(feature = "serde")]
            if !valid_wire_name(predicate.field()) {
                return Err(FilterExpressionError::new(
                    FilterExpressionErrorKind::UnknownField,
                ));
            }
            T::__filter_validate(predicate)
        }
        ExprData::And(expressions) | ExprData::Or(expressions) => {
            let mut first_error = None;
            for expression in expressions {
                if let Err(error) = validate_expression::<T>(expression) {
                    first_error.get_or_insert(error);
                }
            }
            first_error.map_or(Ok(()), Err)
        }
        ExprData::Not(expression) => validate_expression::<T>(expression),
        #[cfg(feature = "serde")]
        ExprData::Invalid(kind) => Err(FilterExpressionError::new(*kind)),
    }
}

#[cfg(feature = "serde")]
fn valid_wire_name(value: &str) -> bool {
    let mut bytes = value.bytes();
    matches!(bytes.next(), Some(b'a'..=b'z'))
        && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}

#[cfg(feature = "serde")]
fn validate_wire_targets(
    expression: &ExprData,
    expected_target: Option<&str>,
) -> Result<(), FilterExpressionError> {
    match expression {
        ExprData::Predicate(predicate) => {
            if !valid_wire_name(predicate.target())
                || expected_target.is_some_and(|target| predicate.target() != target)
            {
                return Err(FilterExpressionError::new(
                    FilterExpressionErrorKind::InvalidTarget,
                ));
            }
            if let Some(relation) = predicate.relation_internal() {
                validate_wire_targets(&relation.expression, None)?;
            }
            Ok(())
        }
        ExprData::And(expressions) | ExprData::Or(expressions) => {
            for expression in expressions {
                validate_wire_targets(expression, expected_target)?;
            }
            Ok(())
        }
        ExprData::Not(expression) => validate_wire_targets(expression, expected_target),
        ExprData::Invalid(_) => Ok(()),
    }
}

#[cfg(feature = "serde")]
fn validate_wire_fields(expression: &ExprData) -> Result<(), FilterExpressionError> {
    match expression {
        ExprData::Predicate(predicate) => {
            if !valid_wire_name(predicate.field()) {
                return Err(FilterExpressionError::new(
                    FilterExpressionErrorKind::UnknownField,
                ));
            }
            if let Some(relation) = predicate.relation_internal() {
                validate_wire_fields(&relation.expression)?;
            }
            Ok(())
        }
        ExprData::And(expressions) | ExprData::Or(expressions) => {
            for expression in expressions {
                validate_wire_fields(expression)?;
            }
            Ok(())
        }
        ExprData::Not(expression) => validate_wire_fields(expression),
        ExprData::Invalid(_) => Ok(()),
    }
}

#[cfg(feature = "serde")]
fn expression_is_resolved(expression: &ExprData) -> bool {
    match expression {
        ExprData::Predicate(predicate) => {
            predicate.is_resolved_internal()
                && predicate
                    .relation_internal()
                    .is_none_or(|relation| expression_is_resolved(&relation.expression))
        }
        ExprData::And(expressions) | ExprData::Or(expressions) => {
            expressions.iter().all(expression_is_resolved)
        }
        ExprData::Not(expression) => expression_is_resolved(expression),
        ExprData::Invalid(_) => false,
    }
}

enum ExprData {
    Predicate(__private::Predicate),
    And(Vec<Self>),
    Or(Vec<Self>),
    Not(Box<Self>),
    #[cfg(feature = "serde")]
    Invalid(FilterExpressionErrorKind),
}

impl Clone for ExprData {
    fn clone(&self) -> Self {
        match self {
            Self::Predicate(predicate) => Self::Predicate(predicate.clone_internal()),
            Self::And(expressions) => Self::And(expressions.clone()),
            Self::Or(expressions) => Self::Or(expressions.clone()),
            Self::Not(expression) => Self::Not(expression.clone()),
            #[cfg(feature = "serde")]
            Self::Invalid(kind) => Self::Invalid(*kind),
        }
    }
}

impl PartialEq for ExprData {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Predicate(left), Self::Predicate(right)) => left.eq_internal(right),
            (Self::And(left), Self::And(right)) | (Self::Or(left), Self::Or(right)) => {
                left == right
            }
            (Self::Not(left), Self::Not(right)) => left == right,
            #[cfg(feature = "serde")]
            (Self::Invalid(left), Self::Invalid(right)) => left == right,
            _ => false,
        }
    }
}

impl Eq for ExprData {}

struct RedactedExprDebug<'a>(&'a ExprData);

impl fmt::Debug for RedactedExprDebug<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            ExprData::Predicate(predicate) => {
                if let Some(relation) = predicate.relation_internal() {
                    formatter
                        .debug_struct("Relation")
                        .field("target", &predicate.target())
                        .field("field", &predicate.field())
                        .field("quantifier", &relation.quantifier.label())
                        .field("expression", &RedactedExprDebug(&relation.expression))
                        .finish()
                } else {
                    formatter
                        .debug_struct("Predicate")
                        .field("target", &predicate.target())
                        .field("field", &predicate.field())
                        .field("operator", &predicate.operator_label())
                        .finish()
                }
            }
            ExprData::And(expressions) => formatter
                .debug_tuple("And")
                .field(&RedactedExprList(expressions))
                .finish(),
            ExprData::Or(expressions) => formatter
                .debug_tuple("Or")
                .field(&RedactedExprList(expressions))
                .finish(),
            ExprData::Not(expression) => formatter
                .debug_tuple("Not")
                .field(&RedactedExprDebug(expression))
                .finish(),
            #[cfg(feature = "serde")]
            ExprData::Invalid(kind) => formatter.debug_tuple("Invalid").field(kind).finish(),
        }
    }
}

struct RedactedExprList<'a>(&'a [ExprData]);

impl fmt::Debug for RedactedExprList<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_list()
            .entries(self.0.iter().map(RedactedExprDebug))
            .finish()
    }
}

/// An opaque, portable predicate over candidates of type `T`.
///
/// Expressions have ordered structural equality after adjacent `and` and
/// `or` nodes are flattened. Their debug representation includes structure
/// and stable schema names, but never literal values or lengths.
///
/// # Examples
///
/// ```
/// use libtmux::query::{FilterExpr, TextField};
/// use libtmux::query::__private;
///
/// struct Row;
/// let field: TextField<Row> = __private::text_field("row", "name");
/// let expression: FilterExpr<Row> = field.eq("build");
/// assert_eq!(expression, field.eq("build"));
/// ```
pub struct FilterExpr<T> {
    data: ExprData,
    marker: PhantomData<fn() -> T>,
}

impl<T> FilterExpr<T> {
    fn predicate(predicate: __private::Predicate) -> Self {
        Self {
            data: ExprData::Predicate(predicate),
            marker: PhantomData,
        }
    }

    /// Combine two expressions with ordered short-circuiting conjunction.
    ///
    /// Adjacent conjunction nodes are flattened without reordering operands.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// let expression = field.eq(false).and(field.eq(false));
    /// assert_eq!(expression, field.eq(false).and(field.eq(false)));
    /// ```
    #[must_use]
    pub fn and(self, other: Self) -> Self {
        let mut expressions = match self.data {
            ExprData::And(expressions) => expressions,
            expression => vec![expression],
        };
        match other.data {
            ExprData::And(other_expressions) => expressions.extend(other_expressions),
            expression => expressions.push(expression),
        }
        Self {
            data: ExprData::And(expressions),
            marker: PhantomData,
        }
    }

    /// Combine two expressions with ordered short-circuiting disjunction.
    ///
    /// Adjacent disjunction nodes are flattened without reordering operands.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// let expression = field.eq(false).or(field.eq(true));
    /// assert_ne!(expression, field.eq(true).or(field.eq(false)));
    /// ```
    #[must_use]
    pub fn or(self, other: Self) -> Self {
        let mut expressions = match self.data {
            ExprData::Or(expressions) => expressions,
            expression => vec![expression],
        };
        match other.data {
            ExprData::Or(other_expressions) => expressions.extend(other_expressions),
            expression => expressions.push(expression),
        }
        Self {
            data: ExprData::Or(expressions),
            marker: PhantomData,
        }
    }

    /// Negate this expression.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// assert_eq!(field.eq(false).not(), field.eq(false).not());
    /// ```
    #[must_use]
    // The named method mirrors the portable grammar; implementing `Not`
    // would add an operator surface outside this contract.
    #[allow(clippy::should_implement_trait)]
    pub fn not(self) -> Self {
        Self {
            data: ExprData::Not(Box::new(self.data)),
            marker: PhantomData,
        }
    }
}

impl<T: Filterable> FilterExpr<T> {
    /// Evaluate this validated expression against `candidate`.
    ///
    /// Evaluation is infallible, ordered, and short-circuiting. Every text
    /// predicate first requires strict candidate UTF-8 and returns `false` for
    /// invalid bytes, including empty exclusion. An outer [`Self::not`] can
    /// invert that result.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{BoolField, FilterExpressionError, Filterable};
    /// use libtmux::query::__private::{self, Predicate};
    ///
    /// struct Task(bool);
    /// struct Fields(BoolField<Task>);
    ///
    /// impl Filterable for Task {
    ///     type Fields = Fields;
    ///     const FILTER_TARGET: &'static str = "task";
    ///
    ///     fn filter_fields() -> Self::Fields {
    ///         Fields(__private::bool_field(Self::FILTER_TARGET, "done"))
    ///     }
    ///
    ///     fn __filter_matches(&self, predicate: &Predicate) -> bool {
    ///         predicate.matches_bool(self.0)
    ///     }
    ///
    ///     fn __filter_validate(_: &Predicate) -> Result<(), FilterExpressionError> {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let expression = Task::filter_fields().0.eq(true);
    /// assert!(expression.matches(&Task(true)));
    /// ```
    #[must_use]
    pub fn matches(&self, candidate: &T) -> bool {
        evaluate(&self.data, candidate)
    }
}

impl<T> Clone for FilterExpr<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for FilterExpr<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("FilterExpr")
            .field(&RedactedExprDebug(&self.data))
            .finish()
    }
}

impl<T> PartialEq for FilterExpr<T> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<T> Eq for FilterExpr<T> {}

impl<T: Filterable> Matcher<T> for FilterExpr<T> {
    fn matches(&self, candidate: &T) -> bool {
        Self::matches(self, candidate)
    }
}

impl<T: Filterable> Matcher<T> for &FilterExpr<T> {
    fn matches(&self, candidate: &T) -> bool {
        FilterExpr::matches(self, candidate)
    }
}

/// A typed handle for a portable text field on `T`.
///
/// All operators require strict UTF-8 in the candidate and return `false` for
/// invalid bytes before any outer logical negation. Rust membership authoring
/// accepts any `IntoIterator`; the version 1 wire representation uses an
/// array. A scalar string is not substring membership: use
/// [`TextField::contains`] for that operation.
///
/// # Examples
///
/// ```
/// use libtmux::query::TextField;
/// use libtmux::query::__private;
///
/// struct Row;
/// let field: TextField<Row> = __private::text_field("row", "name");
/// let _ = field.contains("build");
/// ```
pub struct TextField<T> {
    id: FieldId,
    marker: PhantomData<fn() -> T>,
}

/// A typed handle for a portable boolean field on `T`.
///
/// # Examples
///
/// ```
/// use libtmux::query::BoolField;
/// use libtmux::query::__private;
///
/// struct Row;
/// let field: BoolField<Row> = __private::bool_field("row", "done");
/// let _ = field.eq(false);
/// ```
pub struct BoolField<T> {
    id: FieldId,
    marker: PhantomData<fn() -> T>,
}

/// A typed handle for a fixed-width integer field `N` on `T`.
///
/// Only the ten portable fixed-width Rust integer primitives have authoring
/// methods.
///
/// # Examples
///
/// ```
/// use libtmux::query::IntegerField;
/// use libtmux::query::__private;
///
/// struct Row;
/// let field: IntegerField<Row, i64> = __private::integer_field("row", "count");
/// let _ = field.eq(7_i64);
/// ```
pub struct IntegerField<T, N> {
    id: FieldId,
    marker: PhantomData<fn() -> (T, N)>,
}

/// A typed handle for a custom enum field `E` on `T`.
///
/// # Examples
///
/// ```
/// use libtmux::query::{EnumField, FilterEnum};
/// use libtmux::query::__private;
///
/// enum State { Ready }
/// impl FilterEnum for State {
///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
///     fn filter_name(&self) -> &'static str { "ready" }
/// }
/// struct Row;
/// let field: EnumField<Row, State> = __private::enum_field("row", "state");
/// let _ = field.eq(State::Ready);
/// ```
pub struct EnumField<T, E> {
    id: FieldId,
    marker: PhantomData<fn() -> (T, E)>,
}

/// A value-only handle for a to-many relation from `From` to `To`.
///
/// Relation expressions inspect only the already-loaded related values on a
/// candidate and never perform I/O.
///
/// # Examples
///
/// ```
/// use libtmux::query::ManyRelation;
/// use libtmux::query::__private;
///
/// struct Parent;
/// struct Child;
/// let relation: ManyRelation<Parent, Child> =
///     __private::many_relation("parent", "children");
/// assert!(format!("{relation:?}").contains("children"));
/// ```
pub struct ManyRelation<From, To> {
    id: FieldId,
    marker: PhantomData<fn() -> (From, To)>,
}

/// A value-only handle for a to-one relation from `From` to `To`.
///
/// Relation expressions inspect only the already-loaded optional value on a
/// candidate and never perform I/O.
///
/// # Examples
///
/// ```
/// use libtmux::query::OneRelation;
/// use libtmux::query::__private;
///
/// struct Parent;
/// struct Owner;
/// let relation: OneRelation<Parent, Owner> =
///     __private::one_relation("parent", "owner");
/// assert!(format!("{relation:?}").contains("owner"));
/// ```
pub struct OneRelation<From, To> {
    id: FieldId,
    marker: PhantomData<fn() -> (From, To)>,
}

impl<From, To> ManyRelation<From, To> {
    fn expression(
        self,
        quantifier: RelationQuantifier,
        expression: FilterExpr<To>,
    ) -> FilterExpr<From> {
        FilterExpr::predicate(__private::Predicate::new(
            self.id,
            PredicateData::Relation(RelationPredicate {
                quantifier,
                expression: Box::new(expression.data),
            }),
        ))
    }

    /// Match when any related candidate satisfies `expression`.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{BoolField, ManyRelation};
    /// use libtmux::query::__private;
    ///
    /// struct Parent;
    /// struct Child;
    /// let relation: ManyRelation<Parent, Child> =
    ///     __private::many_relation("parent", "children");
    /// let done: BoolField<Child> = __private::bool_field("child", "done");
    /// assert_eq!(relation.any(done.eq(true)), relation.any(done.eq(true)));
    /// ```
    #[must_use]
    pub fn any(self, expression: FilterExpr<To>) -> FilterExpr<From> {
        self.expression(RelationQuantifier::Any, expression)
    }

    /// Match when every related candidate satisfies `expression`.
    ///
    /// This is true for an empty loaded relation.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{BoolField, ManyRelation};
    /// use libtmux::query::__private;
    ///
    /// struct Parent;
    /// struct Child;
    /// let relation: ManyRelation<Parent, Child> =
    ///     __private::many_relation("parent", "children");
    /// let done: BoolField<Child> = __private::bool_field("child", "done");
    /// assert_eq!(relation.all(done.eq(true)), relation.all(done.eq(true)));
    /// ```
    #[must_use]
    pub fn all(self, expression: FilterExpr<To>) -> FilterExpr<From> {
        self.expression(RelationQuantifier::All, expression)
    }

    /// Match when no related candidate satisfies `expression`.
    ///
    /// This is true for an empty loaded relation.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{BoolField, ManyRelation};
    /// use libtmux::query::__private;
    ///
    /// struct Parent;
    /// struct Child;
    /// let relation: ManyRelation<Parent, Child> =
    ///     __private::many_relation("parent", "children");
    /// let done: BoolField<Child> = __private::bool_field("child", "done");
    /// assert_eq!(relation.none(done.eq(true)), relation.none(done.eq(true)));
    /// ```
    #[must_use]
    pub fn none(self, expression: FilterExpr<To>) -> FilterExpr<From> {
        self.expression(RelationQuantifier::None, expression)
    }
}

impl<From, To> OneRelation<From, To> {
    /// Match when the related candidate exists and satisfies `expression`.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{BoolField, OneRelation};
    /// use libtmux::query::__private;
    ///
    /// struct Parent;
    /// struct Child;
    /// let relation: OneRelation<Parent, Child> =
    ///     __private::one_relation("parent", "child");
    /// let done: BoolField<Child> = __private::bool_field("child", "done");
    /// assert_eq!(relation.is(done.eq(true)), relation.is(done.eq(true)));
    /// ```
    #[must_use]
    pub fn is(self, expression: FilterExpr<To>) -> FilterExpr<From> {
        FilterExpr::predicate(__private::Predicate::new(
            self.id,
            PredicateData::Relation(RelationPredicate {
                quantifier: RelationQuantifier::Is,
                expression: Box::new(expression.data),
            }),
        ))
    }
}

macro_rules! impl_handle_traits {
    ($name:ident<$($type_parameter:ident),+>) => {
        impl<$($type_parameter),+> Copy for $name<$($type_parameter),+> {}

        impl<$($type_parameter),+> Clone for $name<$($type_parameter),+> {
            fn clone(&self) -> Self {
                *self
            }
        }

        impl<$($type_parameter),+> PartialEq for $name<$($type_parameter),+> {
            fn eq(&self, other: &Self) -> bool {
                self.id == other.id
            }
        }

        impl<$($type_parameter),+> Eq for $name<$($type_parameter),+> {}

        impl<$($type_parameter),+> fmt::Debug for $name<$($type_parameter),+> {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter
                    .debug_struct(stringify!($name))
                    .field("target", &self.id.target)
                    .field("field", &self.id.field)
                    .finish()
            }
        }
    };
}

impl_handle_traits!(TextField<T>);
impl_handle_traits!(BoolField<T>);
impl_handle_traits!(IntegerField<T, N>);
impl_handle_traits!(EnumField<T, E>);
impl_handle_traits!(ManyRelation<From, To>);
impl_handle_traits!(OneRelation<From, To>);

impl<T> TextField<T> {
    fn expression(
        self,
        operator: TextOperator,
        values: Vec<String>,
        compiled_regex: Option<Regex>,
    ) -> FilterExpr<T> {
        FilterExpr::predicate(__private::Predicate::new(
            self.id,
            PredicateData::Text(TextPredicate {
                operator,
                values,
                compiled_regex,
            }),
        ))
    }

    fn one(self, operator: TextOperator, value: impl Into<String>) -> FilterExpr<T> {
        self.expression(operator, vec![value.into()], None)
    }

    /// Compare a candidate with one exact string.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// assert_eq!(field.eq("build"), field.eq(String::from("build")));
    /// ```
    #[must_use]
    pub fn eq(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::Eq, value)
    }

    /// Compare using Unicode default case folding without normalization.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.eq_ignore_case("BUILD");
    /// ```
    #[must_use]
    pub fn eq_ignore_case(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::EqIgnoreCase, value)
    }

    /// Test exact substring containment.
    ///
    /// This is the substring operator; membership never treats one string as
    /// a collection of candidate substrings.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.contains("build");
    /// ```
    #[must_use]
    pub fn contains(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::Contains, value)
    }

    /// Test folded substring containment without normalization.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.contains_ignore_case("BUILD");
    /// ```
    #[must_use]
    pub fn contains_ignore_case(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::ContainsIgnoreCase, value)
    }

    /// Test an exact string prefix.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.starts_with("build");
    /// ```
    #[must_use]
    pub fn starts_with(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::StartsWith, value)
    }

    /// Test a folded string prefix without normalization.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.starts_with_ignore_case("BUILD");
    /// ```
    #[must_use]
    pub fn starts_with_ignore_case(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::StartsWithIgnoreCase, value)
    }

    /// Test an exact string suffix.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.ends_with("build");
    /// ```
    #[must_use]
    pub fn ends_with(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::EndsWith, value)
    }

    /// Test a folded string suffix without normalization.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.ends_with_ignore_case("BUILD");
    /// ```
    #[must_use]
    pub fn ends_with_ignore_case(self, value: impl Into<String>) -> FilterExpr<T> {
        self.one(TextOperator::EndsWithIgnoreCase, value)
    }

    /// Test exact membership in ordered string values.
    ///
    /// Rust authoring accepts any `IntoIterator`; the version 1 wire value is
    /// an array, never a scalar string. An empty input never matches. Invalid
    /// candidate UTF-8 also never matches.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.is_in(["build", "test"]);
    /// ```
    #[must_use]
    pub fn is_in<I, S>(self, values: I) -> FilterExpr<T>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.expression(
            TextOperator::In,
            values.into_iter().map(Into::into).collect(),
            None,
        )
    }

    /// Test exact exclusion from ordered string values.
    ///
    /// Rust authoring accepts any `IntoIterator`; the version 1 wire value is
    /// an array, never a scalar string. An empty input matches every valid
    /// UTF-8 candidate, but invalid candidate bytes remain a nonmatch.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field.not_in(["done"]);
    /// ```
    #[must_use]
    pub fn not_in<I, S>(self, values: I) -> FilterExpr<T>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.expression(
            TextOperator::NotIn,
            values.into_iter().map(Into::into).collect(),
            None,
        )
    }

    fn regex_inner(
        self,
        pattern: String,
        ignore_case: bool,
    ) -> Result<FilterExpr<T>, FilterExpressionError> {
        let compiled_regex = RegexBuilder::new(&pattern)
            .case_insensitive(ignore_case)
            .build()
            .map_err(|_| FilterExpressionError::new(FilterExpressionErrorKind::InvalidRegex))?;
        let operator = if ignore_case {
            TextOperator::RegexIgnoreCase
        } else {
            TextOperator::Regex
        };
        Ok(self.expression(operator, vec![pattern], Some(compiled_regex)))
    }

    /// Compile and match a case-sensitive Rust regular expression.
    ///
    /// Rust syntax excludes Python-only look-around and backreferences.
    ///
    /// # Errors
    ///
    /// Returns a source-less [`FilterExpressionErrorKind::InvalidRegex`] when
    /// `pattern` does not compile under the version 1 regex dialect.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let expression = field.regex("^build$").expect("the pattern is valid");
    /// assert_eq!(expression, field.regex("^build$").expect("the pattern is valid"));
    /// ```
    pub fn regex(self, pattern: impl Into<String>) -> Result<FilterExpr<T>, FilterExpressionError> {
        self.regex_inner(pattern.into(), false)
    }

    /// Compile and match a Unicode case-insensitive Rust regular expression.
    ///
    /// Rust syntax excludes Python-only look-around and backreferences.
    ///
    /// # Errors
    ///
    /// Returns a source-less [`FilterExpressionErrorKind::InvalidRegex`] when
    /// `pattern` does not compile under the version 1 regex dialect.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::TextField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// let _ = field
    ///     .regex_ignore_case("^build$")
    ///     .expect("the pattern is valid");
    /// ```
    pub fn regex_ignore_case(
        self,
        pattern: impl Into<String>,
    ) -> Result<FilterExpr<T>, FilterExpressionError> {
        self.regex_inner(pattern.into(), true)
    }
}

impl<T> BoolField<T> {
    fn expression(self, operator: SetOperator, values: Vec<bool>) -> FilterExpr<T> {
        FilterExpr::predicate(__private::Predicate::new(
            self.id,
            PredicateData::Bool(SetPredicate { operator, values }),
        ))
    }

    /// Compare with one boolean value.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// assert_eq!(field.eq(true), field.eq(true));
    /// ```
    #[must_use]
    pub fn eq(self, value: bool) -> FilterExpr<T> {
        self.expression(SetOperator::Eq, vec![value])
    }

    /// Test membership in an ordered set of booleans.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// let _ = field.is_in([false, true]);
    /// ```
    #[must_use]
    pub fn is_in(self, values: impl IntoIterator<Item = bool>) -> FilterExpr<T> {
        self.expression(SetOperator::In, values.into_iter().collect())
    }

    /// Test exclusion from an ordered set of booleans.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    ///
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// let _ = field.not_in([true]);
    /// ```
    #[must_use]
    pub fn not_in(self, values: impl IntoIterator<Item = bool>) -> FilterExpr<T> {
        self.expression(SetOperator::NotIn, values.into_iter().collect())
    }
}

macro_rules! impl_integer_field {
    ($integer:ty, $variant:ident, $convert:path) => {
        impl<T> IntegerField<T, $integer> {
            fn expression(self, operator: SetOperator, values: Vec<$integer>) -> FilterExpr<T> {
                FilterExpr::predicate(__private::Predicate::new(
                    self.id,
                    PredicateData::$variant(SetPredicate {
                        operator,
                        values: values.into_iter().map($convert).collect(),
                    }),
                ))
            }

            /// Compare with one exact fixed-width integer value.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// assert_eq!(field.eq(1), field.eq(1));
            /// ```
            #[must_use]
            pub fn eq(self, value: $integer) -> FilterExpr<T> {
                self.expression(SetOperator::Eq, vec![value])
            }

            /// Test membership in an ordered set of fixed-width integers.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.is_in([1, 2]);
            /// ```
            #[must_use]
            pub fn is_in(self, values: impl IntoIterator<Item = $integer>) -> FilterExpr<T> {
                self.expression(SetOperator::In, values.into_iter().collect())
            }

            /// Test exclusion from an ordered set of fixed-width integers.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.not_in([1, 2]);
            /// ```
            #[must_use]
            pub fn not_in(self, values: impl IntoIterator<Item = $integer>) -> FilterExpr<T> {
                self.expression(SetOperator::NotIn, values.into_iter().collect())
            }

            /// Test that the field is below a bound.
            ///
            /// Ordering exists for integers and not for text or booleans, so
            /// a comparison that has no meaning for a field's type does not
            /// compile.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.lt(10);
            /// ```
            #[must_use]
            pub fn lt(self, bound: $integer) -> FilterExpr<T> {
                self.expression(SetOperator::Lt, vec![bound])
            }

            /// Test that the field is at or below a bound.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.lte(10);
            /// ```
            #[must_use]
            pub fn lte(self, bound: $integer) -> FilterExpr<T> {
                self.expression(SetOperator::Lte, vec![bound])
            }

            /// Test that the field is above a bound.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.gt(1);
            /// ```
            #[must_use]
            pub fn gt(self, bound: $integer) -> FilterExpr<T> {
                self.expression(SetOperator::Gt, vec![bound])
            }

            /// Test that the field is at or above a bound.
            ///
            /// # Examples
            ///
            /// ```
            /// use libtmux::query::IntegerField;
            /// use libtmux::query::__private;
            ///
            /// struct Row;
            /// let field: IntegerField<Row, i64> =
            ///     __private::integer_field("row", "count");
            /// let _ = field.gte(1);
            /// ```
            #[must_use]
            pub fn gte(self, bound: $integer) -> FilterExpr<T> {
                self.expression(SetOperator::Gte, vec![bound])
            }
        }
    };
}

impl_integer_field!(i8, Signed, i128::from);
impl_integer_field!(i16, Signed, i128::from);
impl_integer_field!(i32, Signed, i128::from);
impl_integer_field!(i64, Signed, i128::from);
impl_integer_field!(i128, Signed, i128::from);
impl_integer_field!(u8, Unsigned, u128::from);
impl_integer_field!(u16, Unsigned, u128::from);
impl_integer_field!(u32, Unsigned, u128::from);
impl_integer_field!(u64, Unsigned, u128::from);
impl_integer_field!(u128, Unsigned, u128::from);

impl<T, E: FilterEnum> EnumField<T, E> {
    fn expression(self, operator: SetOperator, values: Vec<E>) -> FilterExpr<T> {
        FilterExpr::predicate(__private::Predicate::new(
            self.id,
            PredicateData::Enum(SetPredicate {
                operator,
                values: values
                    .into_iter()
                    .map(|value| value.filter_name().to_owned())
                    .collect(),
            }),
        ))
    }

    /// Compare with one custom enum value's stable filter name.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{EnumField, FilterEnum};
    /// use libtmux::query::__private;
    ///
    /// enum State { Ready }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
    ///     fn filter_name(&self) -> &'static str { "ready" }
    /// }
    /// struct Row;
    /// let field: EnumField<Row, State> = __private::enum_field("row", "state");
    /// let _ = field.eq(State::Ready);
    /// ```
    #[must_use]
    pub fn eq(self, value: E) -> FilterExpr<T> {
        self.expression(SetOperator::Eq, vec![value])
    }

    /// Test membership using custom enum values' stable filter names.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{EnumField, FilterEnum};
    /// use libtmux::query::__private;
    ///
    /// enum State { Ready, Blocked }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready", "blocked"];
    ///     fn filter_name(&self) -> &'static str {
    ///         match self { Self::Ready => "ready", Self::Blocked => "blocked" }
    ///     }
    /// }
    /// struct Row;
    /// let field: EnumField<Row, State> = __private::enum_field("row", "state");
    /// let _ = field.is_in([State::Ready, State::Blocked]);
    /// ```
    #[must_use]
    pub fn is_in(self, values: impl IntoIterator<Item = E>) -> FilterExpr<T> {
        self.expression(SetOperator::In, values.into_iter().collect())
    }

    /// Test exclusion using custom enum values' stable filter names.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{EnumField, FilterEnum};
    /// use libtmux::query::__private;
    ///
    /// enum State { Ready }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
    ///     fn filter_name(&self) -> &'static str { "ready" }
    /// }
    /// struct Row;
    /// let field: EnumField<Row, State> = __private::enum_field("row", "state");
    /// let _ = field.not_in([State::Ready]);
    /// ```
    #[must_use]
    pub fn not_in(self, values: impl IntoIterator<Item = E>) -> FilterExpr<T> {
        self.expression(SetOperator::NotIn, values.into_iter().collect())
    }
}

/// Compatibility-sensitive support used by generated `Filterable` code.
///
/// These values are public only so generated implementations can name them.
/// Applications author expressions through typed field handles.
#[doc(hidden)]
pub mod __private {
    use super::{
        BoolField, EnumField, FieldId, FilterEnum, FilterExpressionError,
        FilterExpressionErrorKind, Filterable, IntegerField, ManyRelation, OneRelation,
        PhantomData, PredicateData, PredicateIdentity, RelationPredicate, RelationQuantifier,
        SetOperator, TextField, TextOperator, default_case_fold_str, evaluate, validate_expression,
    };

    #[cfg(feature = "serde")]
    use super::{ResolvedScalar, WireEmptyResolved, WireStringResolved};

    /// The fixed-width integer types understood by generated schema checks.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::__private::IntegerKind;
    ///
    /// let signed = IntegerKind::I8;
    /// let unsigned = IntegerKind::U8;
    /// let _ = (signed, unsigned);
    /// ```
    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    pub enum IntegerKind {
        /// `i8`.
        I8,
        /// `i16`.
        I16,
        /// `i32`.
        I32,
        /// `i64`.
        I64,
        /// `i128`.
        I128,
        /// `u8`.
        U8,
        /// `u16`.
        U16,
        /// `u32`.
        U32,
        /// `u64`.
        U64,
        /// `u128`.
        U128,
    }

    impl IntegerKind {
        fn signed_bounds(self) -> Option<(i128, i128)> {
            match self {
                Self::I8 => Some((i128::from(i8::MIN), i128::from(i8::MAX))),
                Self::I16 => Some((i128::from(i16::MIN), i128::from(i16::MAX))),
                Self::I32 => Some((i128::from(i32::MIN), i128::from(i32::MAX))),
                Self::I64 => Some((i128::from(i64::MIN), i128::from(i64::MAX))),
                Self::I128 => Some((i128::MIN, i128::MAX)),
                Self::U8 | Self::U16 | Self::U32 | Self::U64 | Self::U128 => None,
            }
        }

        fn unsigned_max(self) -> Option<u128> {
            match self {
                Self::U8 => Some(u128::from(u8::MAX)),
                Self::U16 => Some(u128::from(u16::MAX)),
                Self::U32 => Some(u128::from(u32::MAX)),
                Self::U64 => Some(u128::from(u64::MAX)),
                Self::U128 => Some(u128::MAX),
                Self::I8 | Self::I16 | Self::I32 | Self::I64 | Self::I128 => None,
            }
        }
    }

    /// One opaque predicate passed to generated candidate dispatch.
    ///
    /// Downstream code can inspect only the stable field name and call the
    /// typed matching or validation helpers.
    ///
    /// The [`crate::query::Filterable`] example executes every scalar helper
    /// through a hand-written generated-code expansion.
    pub struct Predicate {
        id: PredicateIdentity,
        data: PredicateData,
    }

    // The field name, not the operand. A predicate carries values a caller
    // filtered on, which are tmux data rather than this crate's to disclose.
    impl core::fmt::Debug for Predicate {
        fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            formatter
                .debug_struct("Predicate")
                .field("field", &self.field())
                .finish_non_exhaustive()
        }
    }

    impl Predicate {
        pub(super) fn new(id: FieldId, data: PredicateData) -> Self {
            Self {
                id: PredicateIdentity::Static(id),
                data,
            }
        }

        #[cfg(feature = "serde")]
        pub(super) fn from_wire(field: String, data: PredicateData) -> Self {
            Self {
                id: PredicateIdentity::Wire {
                    target: super::OnceLock::new(),
                    field,
                },
                data,
            }
        }

        pub(super) fn clone_internal(&self) -> Self {
            Self {
                id: self.id.clone_internal(),
                data: self.data.clone(),
            }
        }

        pub(super) fn eq_internal(&self, other: &Self) -> bool {
            self.id == other.id && self.data == other.data
        }

        pub(super) fn target(&self) -> &str {
            self.id.target()
        }

        pub(super) fn operator_label(&self) -> &str {
            self.data.operator_label()
        }

        pub(super) fn bind_target_internal(
            &self,
            target: &'static str,
        ) -> Result<(), FilterExpressionError> {
            self.id.bind_target(target)
        }

        pub(super) fn relation_internal(&self) -> Option<&RelationPredicate> {
            match &self.data {
                PredicateData::Relation(relation) => Some(relation),
                _ => None,
            }
        }

        #[cfg(feature = "serde")]
        pub(super) fn scalar_internal(&self) -> Option<ResolvedScalar<'_>> {
            self.data.scalar()
        }

        #[cfg(feature = "serde")]
        pub(super) fn is_resolved_internal(&self) -> bool {
            self.data.is_resolved()
        }

        /// Return the stable field name used by generated dispatch.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn field(&self) -> &str {
            self.id.field()
        }

        /// Match a strict UTF-8 candidate with this text predicate.
        ///
        /// Invalid UTF-8 returns `false` before every operator, including
        /// exclusion from an empty set.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn matches_text(&self, candidate: &[u8]) -> bool {
            let Ok(candidate) = std::str::from_utf8(candidate) else {
                return false;
            };
            #[cfg(feature = "serde")]
            let Some(ResolvedScalar::Text(operator, values, compiled_regex)) = self.data.scalar()
            else {
                return false;
            };
            #[cfg(not(feature = "serde"))]
            let PredicateData::Text(predicate) = &self.data else {
                return false;
            };
            #[cfg(not(feature = "serde"))]
            let (operator, values, compiled_regex) = (
                predicate.operator,
                predicate.values.as_slice(),
                predicate.compiled_regex.as_ref(),
            );
            let value = values.first().map(String::as_str).unwrap_or_default();
            match operator {
                TextOperator::Eq => candidate == value,
                TextOperator::EqIgnoreCase => {
                    default_case_fold_str(candidate) == default_case_fold_str(value)
                }
                TextOperator::Contains => candidate.contains(value),
                TextOperator::ContainsIgnoreCase => {
                    default_case_fold_str(candidate).contains(&default_case_fold_str(value))
                }
                TextOperator::StartsWith => candidate.starts_with(value),
                TextOperator::StartsWithIgnoreCase => {
                    default_case_fold_str(candidate).starts_with(&default_case_fold_str(value))
                }
                TextOperator::EndsWith => candidate.ends_with(value),
                TextOperator::EndsWithIgnoreCase => {
                    default_case_fold_str(candidate).ends_with(&default_case_fold_str(value))
                }
                TextOperator::In => values.iter().any(|value| value == candidate),
                TextOperator::NotIn => values.iter().all(|value| value != candidate),
                TextOperator::Regex | TextOperator::RegexIgnoreCase => {
                    compiled_regex.is_some_and(|regex| regex.is_match(candidate))
                }
                // Text has no ordering. Validation rejects these before a
                // text field ever sees one, so nothing matches here.
                TextOperator::Lt | TextOperator::Lte | TextOperator::Gt | TextOperator::Gte => {
                    false
                }
            }
        }

        /// Match a boolean candidate with this boolean predicate.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn matches_bool(&self, candidate: bool) -> bool {
            #[cfg(feature = "serde")]
            if let Some(ResolvedScalar::Bool(operator, values)) = self.data.scalar() {
                return set_matches(operator, values, &candidate);
            }
            match &self.data {
                PredicateData::Bool(predicate) => predicate.matches(&candidate),
                _ => false,
            }
        }

        /// Match a signed candidate widened without loss to `i128`.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn matches_signed(&self, candidate: i128) -> bool {
            #[cfg(feature = "serde")]
            if let Some(ResolvedScalar::Signed(operator, values)) = self.data.scalar() {
                return set_matches(operator, values, &candidate);
            }
            match &self.data {
                PredicateData::Signed(predicate) => predicate.matches(&candidate),
                _ => false,
            }
        }

        /// Match an unsigned candidate widened without loss to `u128`.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn matches_unsigned(&self, candidate: u128) -> bool {
            #[cfg(feature = "serde")]
            if let Some(ResolvedScalar::Unsigned(operator, values)) = self.data.scalar() {
                return set_matches(operator, values, &candidate);
            }
            match &self.data {
                PredicateData::Unsigned(predicate) => predicate.matches(&candidate),
                _ => false,
            }
        }

        /// Match a custom enum candidate's stable filter string.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        #[must_use]
        pub fn matches_enum(&self, candidate: &str) -> bool {
            #[cfg(feature = "serde")]
            if let Some(ResolvedScalar::Enum(operator, values)) = self.data.scalar() {
                return values.iter().any(|value| value == candidate)
                    != (operator == SetOperator::NotIn);
            }
            match &self.data {
                PredicateData::Enum(predicate) => {
                    predicate.values.iter().any(|value| value == candidate)
                        != (predicate.operator == SetOperator::NotIn)
                }
                _ => false,
            }
        }

        /// Match this relation predicate against already-loaded related values.
        ///
        /// `any`, `all`, and `none` use the standard iterator truth table and
        /// short-circuit from left to right. Other predicate families and the
        /// to-one `is` quantifier return `false`.
        ///
        /// The [`crate::query::Filterable`] relation example executes this
        /// method in a hand-written generated-code expansion.
        #[must_use]
        pub fn matches_many<U: Filterable>(&self, values: &[U]) -> bool {
            let PredicateData::Relation(relation) = &self.data else {
                return false;
            };
            match relation.quantifier {
                RelationQuantifier::Any => values
                    .iter()
                    .any(|candidate| evaluate(&relation.expression, candidate)),
                RelationQuantifier::All => values
                    .iter()
                    .all(|candidate| evaluate(&relation.expression, candidate)),
                RelationQuantifier::None => values
                    .iter()
                    .all(|candidate| !evaluate(&relation.expression, candidate)),
                RelationQuantifier::Is => false,
            }
        }

        /// Match this relation predicate against one already-loaded value.
        ///
        /// The `is` quantifier evaluates an existing value. An absent value,
        /// another quantifier, or another predicate family returns `false`.
        ///
        /// The [`crate::query::Filterable`] relation example executes this
        /// method in a hand-written generated-code expansion.
        #[must_use]
        pub fn matches_one<U: Filterable>(&self, value: Option<&U>) -> bool {
            let PredicateData::Relation(relation) = &self.data else {
                return false;
            };
            match (relation.quantifier, value) {
                (RelationQuantifier::Is, Some(candidate)) => {
                    evaluate(&relation.expression, candidate)
                }
                _ => false,
            }
        }

        /// Validate that this predicate is a well-formed text predicate.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for another
        /// scalar family and [`FilterExpressionErrorKind::InvalidStructure`]
        /// for an invalid text value or compiled-regex shape.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        pub fn validate_text(&self) -> Result<(), FilterExpressionError> {
            match &self.data {
                PredicateData::Text(predicate) => validate_text_shape(predicate),
                #[cfg(feature = "serde")]
                PredicateData::WireString(predicate) => {
                    let compiled_regex = if predicate.operator.is_regex() {
                        let Some(pattern) = predicate.values.first() else {
                            return validation_error(FilterExpressionErrorKind::InvalidStructure);
                        };
                        Some(
                            super::RegexBuilder::new(pattern)
                                .case_insensitive(
                                    predicate.operator == TextOperator::RegexIgnoreCase,
                                )
                                .build()
                                .map_err(|_| {
                                    FilterExpressionError::new(
                                        FilterExpressionErrorKind::InvalidRegex,
                                    )
                                })?,
                        )
                    } else {
                        None
                    };
                    let resolved = super::TextPredicate {
                        operator: predicate.operator,
                        values: predicate.values.clone(),
                        compiled_regex,
                    };
                    validate_text_shape(&resolved)?;
                    resolve_once(&predicate.resolved, WireStringResolved::Text(resolved))
                }
                #[cfg(feature = "serde")]
                PredicateData::WireBool(_) => {
                    validation_error(FilterExpressionErrorKind::InvalidLiteral)
                }
                #[cfg(feature = "serde")]
                PredicateData::WireEmpty(predicate) => {
                    resolve_once(&predicate.resolved, WireEmptyResolved::Text)
                }
                _ => validation_error(FilterExpressionErrorKind::UnknownOperator),
            }
        }

        /// Validate that this predicate is a well-formed boolean predicate.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for another
        /// scalar family and [`FilterExpressionErrorKind::InvalidStructure`]
        /// for an invalid equality shape.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        pub fn validate_bool(&self) -> Result<(), FilterExpressionError> {
            match &self.data {
                PredicateData::Bool(predicate) => validate_set_shape(predicate),
                #[cfg(feature = "serde")]
                PredicateData::WireBool(predicate) => {
                    if !predicate.operator.takes_a_set() && predicate.values.len() != 1 {
                        return validation_error(FilterExpressionErrorKind::InvalidStructure);
                    }
                    resolve_once(&predicate.resolved, ())
                }
                #[cfg(feature = "serde")]
                PredicateData::WireString(predicate) => {
                    if predicate.operator.set_operator().is_some() {
                        validation_error(FilterExpressionErrorKind::InvalidLiteral)
                    } else {
                        validation_error(FilterExpressionErrorKind::UnknownOperator)
                    }
                }
                #[cfg(feature = "serde")]
                PredicateData::WireEmpty(predicate) => {
                    resolve_once(&predicate.resolved, WireEmptyResolved::Bool)
                }
                _ => validation_error(FilterExpressionErrorKind::UnknownOperator),
            }
        }

        /// Validate this predicate for one fixed-width integer kind.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for a
        /// non-integer family, [`FilterExpressionErrorKind::InvalidStructure`]
        /// for an invalid equality shape, or
        /// [`FilterExpressionErrorKind::InvalidLiteral`] for signedness or
        /// range mismatches.
        ///
        /// The [`crate::query::Filterable`] example executes this method for
        /// both signed and unsigned fields in a hand-written expansion.
        // Generated code passes this small ABI discriminator by value; adding
        // public traits to the hidden enum would widen that frozen surface.
        #[allow(clippy::needless_pass_by_value)]
        pub fn validate_integer(&self, kind: IntegerKind) -> Result<(), FilterExpressionError> {
            match &self.data {
                PredicateData::Signed(predicate) => {
                    if !predicate.has_valid_shape() {
                        return validation_error(FilterExpressionErrorKind::InvalidStructure);
                    }
                    let Some((minimum, maximum)) = kind.signed_bounds() else {
                        return validation_error(FilterExpressionErrorKind::InvalidLiteral);
                    };
                    if predicate
                        .values
                        .iter()
                        .all(|value| (minimum..=maximum).contains(value))
                    {
                        Ok(())
                    } else {
                        validation_error(FilterExpressionErrorKind::InvalidLiteral)
                    }
                }
                PredicateData::Unsigned(predicate) => {
                    if !predicate.has_valid_shape() {
                        return validation_error(FilterExpressionErrorKind::InvalidStructure);
                    }
                    let Some(maximum) = kind.unsigned_max() else {
                        return validation_error(FilterExpressionErrorKind::InvalidLiteral);
                    };
                    if predicate.values.iter().all(|value| *value <= maximum) {
                        Ok(())
                    } else {
                        validation_error(FilterExpressionErrorKind::InvalidLiteral)
                    }
                }
                #[cfg(feature = "serde")]
                PredicateData::WireString(predicate) => {
                    let Some(operator) = predicate.operator.set_operator() else {
                        return validation_error(FilterExpressionErrorKind::UnknownOperator);
                    };
                    // Only `in` and `not_in` take a set; everything else,
                    // including a bound, takes exactly one value.
                    if !operator.takes_a_set() && predicate.values.len() != 1 {
                        return validation_error(FilterExpressionErrorKind::InvalidStructure);
                    }
                    if let Some((minimum, maximum)) = kind.signed_bounds() {
                        let values = predicate
                            .values
                            .iter()
                            .map(|value| parse_signed(value, minimum, maximum))
                            .collect::<Result<Vec<_>, _>>()?;
                        resolve_once(
                            &predicate.resolved,
                            WireStringResolved::Signed(super::SetPredicate { operator, values }),
                        )
                    } else if let Some(maximum) = kind.unsigned_max() {
                        let values = predicate
                            .values
                            .iter()
                            .map(|value| parse_unsigned(value, maximum))
                            .collect::<Result<Vec<_>, _>>()?;
                        resolve_once(
                            &predicate.resolved,
                            WireStringResolved::Unsigned(super::SetPredicate { operator, values }),
                        )
                    } else {
                        validation_error(FilterExpressionErrorKind::InvalidLiteral)
                    }
                }
                #[cfg(feature = "serde")]
                PredicateData::WireBool(_) => {
                    validation_error(FilterExpressionErrorKind::InvalidLiteral)
                }
                #[cfg(feature = "serde")]
                PredicateData::WireEmpty(predicate) => {
                    let resolved = if kind.signed_bounds().is_some() {
                        WireEmptyResolved::Signed
                    } else if kind.unsigned_max().is_some() {
                        WireEmptyResolved::Unsigned
                    } else {
                        return validation_error(FilterExpressionErrorKind::InvalidLiteral);
                    };
                    resolve_once(&predicate.resolved, resolved)
                }
                _ => validation_error(FilterExpressionErrorKind::UnknownOperator),
            }
        }

        /// Validate this predicate against a custom enum's stable variants.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for another
        /// scalar family, [`FilterExpressionErrorKind::InvalidStructure`] for
        /// an invalid equality shape, or
        /// [`FilterExpressionErrorKind::InvalidLiteral`] for an unknown
        /// variant.
        ///
        /// The [`crate::query::Filterable`] example executes this method in a
        /// hand-written generated-code expansion.
        pub fn validate_enum(&self, variants: &[&str]) -> Result<(), FilterExpressionError> {
            match &self.data {
                PredicateData::Enum(predicate) => validate_enum_values(predicate, variants),
                #[cfg(feature = "serde")]
                PredicateData::WireString(predicate) => {
                    let Some(operator) = predicate.operator.set_operator() else {
                        return validation_error(FilterExpressionErrorKind::UnknownOperator);
                    };
                    let resolved = super::SetPredicate {
                        operator,
                        values: predicate.values.clone(),
                    };
                    validate_enum_values(&resolved, variants)?;
                    resolve_once(&predicate.resolved, WireStringResolved::Enum(resolved))
                }
                #[cfg(feature = "serde")]
                PredicateData::WireBool(_) => {
                    validation_error(FilterExpressionErrorKind::InvalidLiteral)
                }
                #[cfg(feature = "serde")]
                PredicateData::WireEmpty(predicate) => {
                    resolve_once(&predicate.resolved, WireEmptyResolved::Enum)
                }
                _ => validation_error(FilterExpressionErrorKind::UnknownOperator),
            }
        }

        /// Validate this predicate as a to-many relation over `U`.
        ///
        /// Validation walks every nested logical branch and delegates each
        /// leaf to `U`'s generated schema implementation.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for a scalar
        /// predicate, [`FilterExpressionErrorKind::UnknownQuantifier`] for
        /// `is`, or the exact source-less nested schema error.
        ///
        /// The [`crate::query::Filterable`] relation example executes this
        /// method in a hand-written generated-code expansion.
        pub fn validate_many<U: Filterable>(&self) -> Result<(), FilterExpressionError> {
            let PredicateData::Relation(relation) = &self.data else {
                return validation_error(FilterExpressionErrorKind::UnknownOperator);
            };
            match relation.quantifier {
                RelationQuantifier::Any | RelationQuantifier::All | RelationQuantifier::None => {
                    validate_expression::<U>(&relation.expression)
                }
                RelationQuantifier::Is => {
                    validation_error(FilterExpressionErrorKind::UnknownQuantifier)
                }
            }
        }

        /// Validate this predicate as a to-one relation over `U`.
        ///
        /// Validation walks every nested logical branch and delegates each
        /// leaf to `U`'s generated schema implementation.
        ///
        /// # Errors
        ///
        /// Returns [`FilterExpressionErrorKind::UnknownOperator`] for a scalar
        /// predicate, [`FilterExpressionErrorKind::UnknownQuantifier`] for a
        /// to-many quantifier, or the exact source-less nested schema error.
        ///
        /// The [`crate::query::Filterable`] relation example executes this
        /// method in a hand-written generated-code expansion.
        pub fn validate_one<U: Filterable>(&self) -> Result<(), FilterExpressionError> {
            let PredicateData::Relation(relation) = &self.data else {
                return validation_error(FilterExpressionErrorKind::UnknownOperator);
            };
            match relation.quantifier {
                RelationQuantifier::Is => validate_expression::<U>(&relation.expression),
                RelationQuantifier::Any | RelationQuantifier::All | RelationQuantifier::None => {
                    validation_error(FilterExpressionErrorKind::UnknownQuantifier)
                }
            }
        }
    }

    fn validate_text_shape(predicate: &super::TextPredicate) -> Result<(), FilterExpressionError> {
        // Text has no ordering, so an ordering operator on a text field is
        // rejected rather than silently matching nothing.
        if predicate.operator.is_ordering() {
            return validation_error(FilterExpressionErrorKind::UnknownOperator);
        }

        let one_value = predicate.values.len() == 1;
        let regex_state = predicate.operator.is_regex() == predicate.compiled_regex.is_some();
        let value_shape =
            matches!(predicate.operator, TextOperator::In | TextOperator::NotIn) || one_value;

        if regex_state && value_shape {
            Ok(())
        } else {
            validation_error(FilterExpressionErrorKind::InvalidStructure)
        }
    }

    fn validate_set_shape<T: PartialOrd>(
        predicate: &super::SetPredicate<T>,
    ) -> Result<(), FilterExpressionError> {
        if predicate.has_valid_shape() {
            Ok(())
        } else {
            validation_error(FilterExpressionErrorKind::InvalidStructure)
        }
    }

    fn validate_enum_values(
        predicate: &super::SetPredicate<String>,
        variants: &[&str],
    ) -> Result<(), FilterExpressionError> {
        validate_set_shape(predicate)?;
        if predicate
            .values
            .iter()
            .all(|value| variants.contains(&value.as_str()))
        {
            Ok(())
        } else {
            validation_error(FilterExpressionErrorKind::InvalidLiteral)
        }
    }

    #[cfg(feature = "serde")]
    fn resolve_once<T: Eq>(
        cell: &super::OnceLock<T>,
        value: T,
    ) -> Result<(), FilterExpressionError> {
        super::set_once_eq(cell, value, FilterExpressionErrorKind::InvalidStructure)
    }

    #[cfg(feature = "serde")]
    fn has_canonical_digits(value: &str, signed: bool) -> bool {
        let digits = if signed && value.starts_with('-') {
            &value[1..]
        } else {
            value
        };
        if digits == "0" {
            return !value.starts_with('-');
        }
        let Some(first) = digits.as_bytes().first() else {
            return false;
        };
        matches!(first, b'1'..=b'9') && digits.as_bytes().iter().all(u8::is_ascii_digit)
    }

    #[cfg(feature = "serde")]
    fn parse_signed(
        value: &str,
        minimum: i128,
        maximum: i128,
    ) -> Result<i128, FilterExpressionError> {
        if !has_canonical_digits(value, true) {
            return Err(FilterExpressionError::new(
                FilterExpressionErrorKind::InvalidLiteral,
            ));
        }
        value
            .parse::<i128>()
            .ok()
            .filter(|parsed| (minimum..=maximum).contains(parsed))
            .ok_or_else(|| FilterExpressionError::new(FilterExpressionErrorKind::InvalidLiteral))
    }

    #[cfg(feature = "serde")]
    fn parse_unsigned(value: &str, maximum: u128) -> Result<u128, FilterExpressionError> {
        if value.starts_with('-') || !has_canonical_digits(value, false) {
            return Err(FilterExpressionError::new(
                FilterExpressionErrorKind::InvalidLiteral,
            ));
        }
        value
            .parse::<u128>()
            .ok()
            .filter(|parsed| *parsed <= maximum)
            .ok_or_else(|| FilterExpressionError::new(FilterExpressionErrorKind::InvalidLiteral))
    }

    #[cfg(feature = "serde")]
    fn set_matches<T: PartialOrd>(operator: SetOperator, values: &[T], candidate: &T) -> bool {
        super::set_matches(operator, values, candidate)
    }

    fn validation_error(kind: FilterExpressionErrorKind) -> Result<(), FilterExpressionError> {
        Err(FilterExpressionError::new(kind))
    }

    /// Construct a text handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{TextField};
    /// use libtmux::query::__private;
    /// struct Row;
    /// let field: TextField<Row> = __private::text_field("row", "name");
    /// assert!(format!("{field:?}").contains("name"));
    /// ```
    #[must_use]
    pub const fn text_field<T>(target: &'static str, field: &'static str) -> TextField<T> {
        TextField {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct a boolean handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::BoolField;
    /// use libtmux::query::__private;
    /// struct Row;
    /// let field: BoolField<Row> = __private::bool_field("row", "done");
    /// assert!(format!("{field:?}").contains("done"));
    /// ```
    #[must_use]
    pub const fn bool_field<T>(target: &'static str, field: &'static str) -> BoolField<T> {
        BoolField {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct an integer handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::IntegerField;
    /// use libtmux::query::__private;
    /// struct Row;
    /// let field: IntegerField<Row, i64> = __private::integer_field("row", "count");
    /// assert!(format!("{field:?}").contains("count"));
    /// ```
    #[must_use]
    pub const fn integer_field<T, N>(
        target: &'static str,
        field: &'static str,
    ) -> IntegerField<T, N> {
        IntegerField {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct a custom enum handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::{EnumField, FilterEnum};
    /// use libtmux::query::__private;
    /// enum State { Ready }
    /// impl FilterEnum for State {
    ///     const FILTER_VARIANTS: &'static [&'static str] = &["ready"];
    ///     fn filter_name(&self) -> &'static str { "ready" }
    /// }
    /// struct Row;
    /// let field: EnumField<Row, State> = __private::enum_field("row", "state");
    /// assert!(format!("{field:?}").contains("state"));
    /// ```
    #[must_use]
    pub const fn enum_field<T, E: FilterEnum>(
        target: &'static str,
        field: &'static str,
    ) -> EnumField<T, E> {
        EnumField {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct a to-many relation handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::ManyRelation;
    /// use libtmux::query::__private;
    /// struct Parent;
    /// struct Child;
    /// let field: ManyRelation<Parent, Child> =
    ///     __private::many_relation("parent", "children");
    /// assert!(format!("{field:?}").contains("children"));
    /// ```
    #[must_use]
    pub const fn many_relation<From, To>(
        target: &'static str,
        field: &'static str,
    ) -> ManyRelation<From, To> {
        ManyRelation {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct a to-one relation handle for generated code.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::OneRelation;
    /// use libtmux::query::__private;
    /// struct Parent;
    /// struct Owner;
    /// let field: OneRelation<Parent, Owner> = __private::one_relation("parent", "owner");
    /// assert!(format!("{field:?}").contains("owner"));
    /// ```
    #[must_use]
    pub const fn one_relation<From, To>(
        target: &'static str,
        field: &'static str,
    ) -> OneRelation<From, To> {
        OneRelation {
            id: FieldId { target, field },
            marker: PhantomData,
        }
    }

    /// Construct the source-less generated fallback for an unknown field.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::query::FilterExpressionErrorKind;
    /// use libtmux::query::__private;
    /// let error = __private::unknown_field_error();
    /// assert_eq!(error.kind(), FilterExpressionErrorKind::UnknownField);
    /// ```
    #[must_use]
    pub const fn unknown_field_error() -> FilterExpressionError {
        FilterExpressionError::new(FilterExpressionErrorKind::UnknownField)
    }
}

#[cfg(feature = "serde")]
mod serde_v1 {
    use std::fmt;
    use std::marker::PhantomData;

    use serde::de::{
        self, Deserialize, Deserializer, Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor,
    };
    use serde::ser::{Error as _, Serialize, SerializeSeq, SerializeStruct, Serializer};

    use super::{
        ExprData, FilterExpr, FilterExpressionError, FilterExpressionErrorKind, Filterable,
        PredicateData, RelationPredicate, RelationQuantifier, ResolvedScalar, SetOperator,
        TextOperator, WireBoolPredicate, WireEmptyPredicate, WireStringPredicate,
        expression_is_resolved, validate_expression,
    };

    const VERSION: u8 = 1;

    fn expression_error(kind: FilterExpressionErrorKind) -> FilterExpressionError {
        FilterExpressionError::new(kind)
    }

    fn invalid_structure<E: de::Error>() -> E {
        E::custom(expression_error(
            FilterExpressionErrorKind::InvalidStructure,
        ))
    }

    fn consume_seq<'de, A: SeqAccess<'de>>(mut sequence: A) -> Result<(), A::Error> {
        while sequence.next_element::<IgnoredAny>()?.is_some() {}
        Ok(())
    }

    fn consume_map<'de, A: MapAccess<'de>>(mut map: A) -> Result<(), A::Error> {
        while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
        Ok(())
    }

    #[derive(Clone, Copy)]
    enum WireVersion {
        One,
        Unsupported,
        Invalid,
    }

    struct VersionVisitor;

    impl<'de> Visitor<'de> for VersionVisitor {
        type Value = WireVersion;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a portable filter version")
        }

        fn visit_i8<E: de::Error>(self, value: i8) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_i16<E: de::Error>(self, value: i16) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_i32<E: de::Error>(self, value: i32) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_i128<E: de::Error>(self, value: i128) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_u8<E: de::Error>(self, value: u8) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_u16<E: de::Error>(self, value: u16) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_u32<E: de::Error>(self, value: u32) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_u128<E: de::Error>(self, value: u128) -> Result<Self::Value, E> {
            Ok(if value == 1 {
                WireVersion::One
            } else {
                WireVersion::Unsupported
            })
        }

        fn visit_f32<E: de::Error>(self, value: f32) -> Result<Self::Value, E> {
            self.visit_f64(f64::from(value))
        }

        #[allow(clippy::float_cmp)]
        fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
            Ok(if value == 1.0 {
                WireVersion::One
            } else if value.is_finite() && value.fract() == 0.0 {
                WireVersion::Unsupported
            } else {
                WireVersion::Invalid
            })
        }

        fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
            Ok(WireVersion::Invalid)
        }

        fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
            Ok(WireVersion::Invalid)
        }

        fn visit_string<E: de::Error>(self, _: String) -> Result<Self::Value, E> {
            Ok(WireVersion::Invalid)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireVersion::Invalid)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireVersion::Invalid)
        }

        fn visit_some<D: Deserializer<'de>>(
            self,
            deserializer: D,
        ) -> Result<Self::Value, D::Error> {
            deserializer.deserialize_any(self)
        }

        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error> {
            consume_seq(sequence)?;
            Ok(WireVersion::Invalid)
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            consume_map(map)?;
            Ok(WireVersion::Invalid)
        }
    }

    impl<'de> Deserialize<'de> for WireVersion {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(VersionVisitor)
        }
    }

    enum WireValue {
        String(String),
        Bool(bool),
        Strings(Vec<String>),
        Bools(Vec<bool>),
        Empty,
        Other,
    }

    enum WireElement {
        String(String),
        Bool(bool),
        Other,
    }

    struct WireElementVisitor;

    impl<'de> Visitor<'de> for WireElementVisitor {
        type Value = WireElement;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a portable scalar literal")
        }

        fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
            Ok(WireElement::String(value.to_owned()))
        }

        fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
            Ok(WireElement::String(value))
        }

        fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
            Ok(WireElement::Bool(value))
        }

        fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_i128<E: de::Error>(self, _: i128) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_u128<E: de::Error>(self, _: u128) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireElement::Other)
        }

        fn visit_some<D: Deserializer<'de>>(
            self,
            deserializer: D,
        ) -> Result<Self::Value, D::Error> {
            deserializer.deserialize_any(self)
        }

        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error> {
            consume_seq(sequence)?;
            Ok(WireElement::Other)
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            consume_map(map)?;
            Ok(WireElement::Other)
        }
    }

    impl<'de> Deserialize<'de> for WireElement {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(WireElementVisitor)
        }
    }

    struct WireValueVisitor;

    impl<'de> Visitor<'de> for WireValueVisitor {
        type Value = WireValue;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a portable wire value")
        }

        fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
            Ok(WireValue::String(value.to_owned()))
        }

        fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
            Ok(WireValue::String(value))
        }

        fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
            Ok(WireValue::Bool(value))
        }

        fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_i128<E: de::Error>(self, _: i128) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_u128<E: de::Error>(self, _: u128) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(WireValue::Other)
        }

        fn visit_some<D: Deserializer<'de>>(
            self,
            deserializer: D,
        ) -> Result<Self::Value, D::Error> {
            deserializer.deserialize_any(self)
        }

        fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Self::Value, A::Error> {
            let mut strings = Vec::new();
            let mut booleans = Vec::new();
            let mut family = None;
            let mut invalid = false;
            while let Some(element) = sequence.next_element::<WireElement>()? {
                match element {
                    WireElement::String(value) => {
                        if family == Some(false) {
                            invalid = true;
                        }
                        family = Some(true);
                        strings.push(value);
                    }
                    WireElement::Bool(value) => {
                        if family == Some(true) {
                            invalid = true;
                        }
                        family = Some(false);
                        booleans.push(value);
                    }
                    WireElement::Other => invalid = true,
                }
            }
            Ok(if invalid {
                WireValue::Other
            } else {
                match family {
                    None => WireValue::Empty,
                    Some(true) => WireValue::Strings(strings),
                    Some(false) => WireValue::Bools(booleans),
                }
            })
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            consume_map(map)?;
            Ok(WireValue::Other)
        }
    }

    impl<'de> Deserialize<'de> for WireValue {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(WireValueVisitor)
        }
    }

    struct RawNode {
        invalid_member: bool,
        op: Option<WireValue>,
        args: Option<RawArgs>,
        expression: Option<RawExpression>,
        field: Option<WireValue>,
        value: Option<WireValue>,
        quantifier: Option<WireValue>,
    }

    enum RawArgs {
        Nodes(Vec<RawNode>),
        Other,
    }

    enum RawExpression {
        Node(Box<RawNode>),
        Other,
    }

    struct RawNodeVisitor;

    impl RawNode {
        fn from_map<'de, A: MapAccess<'de>>(mut map: A) -> Result<Self, A::Error> {
            let mut node = Self {
                invalid_member: false,
                op: None,
                args: None,
                expression: None,
                field: None,
                value: None,
                quantifier: None,
            };
            while let Some(key) = map.next_key::<String>()? {
                match key.as_str() {
                    "op" if node.op.is_none() => node.op = Some(map.next_value()?),
                    "args" if node.args.is_none() => node.args = Some(map.next_value()?),
                    "expr" if node.expression.is_none() => {
                        node.expression = Some(map.next_value()?);
                    }
                    "field" if node.field.is_none() => node.field = Some(map.next_value()?),
                    "value" if node.value.is_none() => node.value = Some(map.next_value()?),
                    "quantifier" if node.quantifier.is_none() => {
                        node.quantifier = Some(map.next_value()?);
                    }
                    _ => {
                        node.invalid_member = true;
                        map.next_value::<IgnoredAny>()?;
                    }
                }
            }
            Ok(node)
        }

        fn operator(&self) -> Option<&str> {
            match self.op.as_ref()? {
                WireValue::String(operator) => Some(operator),
                _ => None,
            }
        }

        fn has_only_scalar_members(&self) -> bool {
            self.args.is_none() && self.expression.is_none() && self.quantifier.is_none()
        }

        fn has_only_args_members(&self) -> bool {
            self.expression.is_none()
                && self.field.is_none()
                && self.value.is_none()
                && self.quantifier.is_none()
        }

        fn has_only_expression_members(&self) -> bool {
            self.args.is_none()
                && self.field.is_none()
                && self.value.is_none()
                && self.quantifier.is_none()
        }

        fn has_only_relation_members(&self) -> bool {
            self.args.is_none() && self.value.is_none()
        }

        fn validate_string(value: Option<&WireValue>) -> bool {
            matches!(value, Some(WireValue::String(_)))
        }

        fn validate_nested(expression: Option<&RawExpression>) -> bool {
            match expression {
                Some(RawExpression::Node(expression)) => expression.validate_structure().is_ok(),
                Some(RawExpression::Other) | None => false,
            }
        }

        fn validate_args(args: Option<&RawArgs>) -> bool {
            match args {
                Some(RawArgs::Nodes(expressions)) if expressions.len() >= 2 => expressions
                    .iter()
                    .all(|expression| expression.validate_structure().is_ok()),
                Some(RawArgs::Nodes(_) | RawArgs::Other) | None => false,
            }
        }

        fn validate_scalar_value(&self, operator: &str) -> bool {
            matches!(
                (operator, self.value.as_ref()),
                ("eq", Some(WireValue::String(_) | WireValue::Bool(_)))
                    | (
                        "in" | "not_in",
                        Some(WireValue::Strings(_) | WireValue::Bools(_) | WireValue::Empty),
                    )
                    | (
                        "eq_ignore_case"
                            | "contains"
                            | "contains_ignore_case"
                            | "starts_with"
                            | "starts_with_ignore_case"
                            | "ends_with"
                            | "ends_with_ignore_case"
                            | "regex"
                            | "regex_ignore_case",
                        Some(WireValue::String(_)),
                    )
            )
        }

        fn validate_unknown_shape(&self) -> bool {
            if self.has_only_scalar_members()
                && Self::validate_string(self.field.as_ref())
                && matches!(
                    self.value,
                    Some(
                        WireValue::String(_)
                            | WireValue::Bool(_)
                            | WireValue::Strings(_)
                            | WireValue::Bools(_)
                            | WireValue::Empty
                    )
                )
            {
                true
            } else if self.has_only_args_members() {
                Self::validate_args(self.args.as_ref())
            } else if self.has_only_expression_members()
                || (self.has_only_relation_members()
                    && Self::validate_string(self.field.as_ref())
                    && Self::validate_string(self.quantifier.as_ref()))
            {
                Self::validate_nested(self.expression.as_ref())
            } else {
                false
            }
        }

        fn validate_structure(&self) -> Result<(), FilterExpressionError> {
            if self.invalid_member {
                return Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                ));
            }
            let Some(operator) = self.operator() else {
                return Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                ));
            };
            let valid = match operator {
                "and" | "or" => {
                    self.has_only_args_members() && Self::validate_args(self.args.as_ref())
                }
                "not" => {
                    self.has_only_expression_members()
                        && Self::validate_nested(self.expression.as_ref())
                }
                "relation" => {
                    self.has_only_relation_members()
                        && Self::validate_string(self.field.as_ref())
                        && Self::validate_string(self.quantifier.as_ref())
                        && Self::validate_nested(self.expression.as_ref())
                }
                "eq"
                | "eq_ignore_case"
                | "contains"
                | "contains_ignore_case"
                | "starts_with"
                | "starts_with_ignore_case"
                | "ends_with"
                | "ends_with_ignore_case"
                | "in"
                | "not_in"
                | "regex"
                | "regex_ignore_case" => {
                    self.has_only_scalar_members()
                        && Self::validate_string(self.field.as_ref())
                        && self.validate_scalar_value(operator)
                }
                _ => self.validate_unknown_shape(),
            };
            if valid {
                Ok(())
            } else {
                Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                ))
            }
        }

        fn take_string(value: Option<WireValue>) -> Result<String, FilterExpressionError> {
            match value {
                Some(WireValue::String(value)) => Ok(value),
                _ => Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                )),
            }
        }

        fn take_nested(value: Option<RawExpression>) -> Result<RawNode, FilterExpressionError> {
            match value {
                Some(RawExpression::Node(value)) => Ok(*value),
                Some(RawExpression::Other) | None => Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                )),
            }
        }

        fn into_junction(self, operator: &str) -> Result<ExprData, FilterExpressionError> {
            let RawArgs::Nodes(nodes) = self
                .args
                .ok_or_else(|| expression_error(FilterExpressionErrorKind::InvalidStructure))?
            else {
                return Err(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                ));
            };
            let mut expressions = Vec::new();
            for node in nodes {
                let expression = match node.into_expression() {
                    Ok(expression) => expression,
                    Err(error) => ExprData::Invalid(error.kind()),
                };
                match (operator, expression) {
                    ("and", ExprData::And(nested)) | ("or", ExprData::Or(nested)) => {
                        expressions.extend(nested);
                    }
                    (_, expression) => expressions.push(expression),
                }
            }
            Ok(if operator == "and" {
                ExprData::And(expressions)
            } else {
                ExprData::Or(expressions)
            })
        }

        fn into_relation(self) -> Result<ExprData, FilterExpressionError> {
            let quantifier = match Self::take_string(self.quantifier)?.as_str() {
                "any" => RelationQuantifier::Any,
                "all" => RelationQuantifier::All,
                "none" => RelationQuantifier::None,
                "is" => RelationQuantifier::Is,
                _ => {
                    return Err(expression_error(
                        FilterExpressionErrorKind::UnknownQuantifier,
                    ));
                }
            };
            let field = Self::take_string(self.field)?;
            if !super::valid_wire_name(&field) {
                return Err(expression_error(FilterExpressionErrorKind::UnknownField));
            }
            let expression = match Self::take_nested(self.expression)?.into_expression() {
                Ok(expression) => expression,
                Err(error) => ExprData::Invalid(error.kind()),
            };
            Ok(ExprData::Predicate(super::__private::Predicate::from_wire(
                field,
                PredicateData::Relation(RelationPredicate {
                    quantifier,
                    expression: Box::new(expression),
                }),
            )))
        }

        fn into_scalar(self, operator: &str) -> Result<ExprData, FilterExpressionError> {
            let Some(wire_operator) = parse_scalar_operator(operator) else {
                return Err(expression_error(FilterExpressionErrorKind::UnknownOperator));
            };
            let field = Self::take_string(self.field)?;
            if !super::valid_wire_name(&field) {
                return Err(expression_error(FilterExpressionErrorKind::UnknownField));
            }
            let data = match self.value {
                Some(WireValue::String(value)) => PredicateData::WireString(WireStringPredicate {
                    operator: wire_operator,
                    values: vec![value],
                    resolved: super::OnceLock::new(),
                }),
                Some(WireValue::Strings(values)) => {
                    PredicateData::WireString(WireStringPredicate {
                        operator: wire_operator,
                        values,
                        resolved: super::OnceLock::new(),
                    })
                }
                Some(WireValue::Bool(value)) => PredicateData::WireBool(WireBoolPredicate {
                    operator: wire_operator.set_operator().ok_or_else(|| {
                        expression_error(FilterExpressionErrorKind::InvalidStructure)
                    })?,
                    values: vec![value],
                    resolved: super::OnceLock::new(),
                }),
                Some(WireValue::Bools(values)) => PredicateData::WireBool(WireBoolPredicate {
                    operator: wire_operator.set_operator().ok_or_else(|| {
                        expression_error(FilterExpressionErrorKind::InvalidStructure)
                    })?,
                    values,
                    resolved: super::OnceLock::new(),
                }),
                Some(WireValue::Empty) => PredicateData::WireEmpty(WireEmptyPredicate {
                    operator: wire_operator.set_operator().ok_or_else(|| {
                        expression_error(FilterExpressionErrorKind::InvalidStructure)
                    })?,
                    resolved: super::OnceLock::new(),
                }),
                Some(WireValue::Other) | None => {
                    return Err(expression_error(
                        FilterExpressionErrorKind::InvalidStructure,
                    ));
                }
            };
            Ok(ExprData::Predicate(super::__private::Predicate::from_wire(
                field, data,
            )))
        }

        fn into_expression(self) -> Result<ExprData, FilterExpressionError> {
            let operator = match self.op.as_ref() {
                Some(WireValue::String(operator)) => operator.clone(),
                _ => {
                    return Err(expression_error(
                        FilterExpressionErrorKind::InvalidStructure,
                    ));
                }
            };
            match operator.as_str() {
                "and" | "or" => self.into_junction(&operator),
                "not" => Ok(ExprData::Not(Box::new(
                    Self::take_nested(self.expression)?.into_expression()?,
                ))),
                "relation" => self.into_relation(),
                _ => self.into_scalar(&operator),
            }
        }
    }

    impl<'de> Visitor<'de> for RawNodeVisitor {
        type Value = RawNode;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a portable filter expression object")
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            RawNode::from_map(map)
        }

        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error> {
            consume_seq(sequence)?;
            Err(invalid_structure())
        }
    }

    impl<'de> Deserialize<'de> for RawNode {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_map(RawNodeVisitor)
        }
    }

    struct RawArgsVisitor;

    impl<'de> Visitor<'de> for RawArgsVisitor {
        type Value = RawArgs;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("an expression array")
        }

        fn visit_seq<A: SeqAccess<'de>>(self, mut sequence: A) -> Result<Self::Value, A::Error> {
            let mut nodes = Vec::new();
            let mut invalid = false;
            while let Some(expression) = sequence.next_element::<RawExpression>()? {
                match expression {
                    RawExpression::Node(node) => nodes.push(*node),
                    RawExpression::Other => invalid = true,
                }
            }
            Ok(if invalid {
                RawArgs::Other
            } else {
                RawArgs::Nodes(nodes)
            })
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            consume_map(map)?;
            Ok(RawArgs::Other)
        }

        fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_string<E: de::Error>(self, _: String) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(RawArgs::Other)
        }
    }

    impl<'de> Deserialize<'de> for RawArgs {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(RawArgsVisitor)
        }
    }

    struct RawExpressionVisitor;

    impl<'de> Visitor<'de> for RawExpressionVisitor {
        type Value = RawExpression;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("an expression object")
        }

        fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
            RawNode::from_map(map).map(|node| RawExpression::Node(Box::new(node)))
        }

        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error> {
            consume_seq(sequence)?;
            Ok(RawExpression::Other)
        }

        fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_string<E: de::Error>(self, _: String) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(RawExpression::Other)
        }
    }

    impl<'de> Deserialize<'de> for RawExpression {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(RawExpressionVisitor)
        }
    }

    struct RawEnvelope {
        invalid_member: bool,
        version: Option<WireVersion>,
        target: Option<WireValue>,
        expression: Option<RawExpression>,
    }

    struct EnvelopeVisitor<T>(PhantomData<fn() -> T>);

    impl<'de, T: Filterable> Visitor<'de> for EnvelopeVisitor<T> {
        type Value = FilterExpr<T>;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("a version 1 portable filter envelope")
        }

        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
            let mut raw = RawEnvelope {
                invalid_member: false,
                version: None,
                target: None,
                expression: None,
            };
            while let Some(key) = map.next_key::<String>()? {
                match key.as_str() {
                    "version" if raw.version.is_none() => raw.version = Some(map.next_value()?),
                    "target" if raw.target.is_none() => raw.target = Some(map.next_value()?),
                    "expr" if raw.expression.is_none() => {
                        raw.expression = Some(map.next_value()?);
                    }
                    _ => {
                        raw.invalid_member = true;
                        map.next_value::<IgnoredAny>()?;
                    }
                }
            }

            if raw.invalid_member
                || raw.version.is_none()
                || !matches!(raw.target, Some(WireValue::String(_)))
                || !matches!(raw.expression, Some(RawExpression::Node(_)))
            {
                return Err(invalid_structure());
            }
            let Some(RawExpression::Node(expression)) = raw.expression.as_ref() else {
                return Err(invalid_structure());
            };
            expression.validate_structure().map_err(A::Error::custom)?;

            match raw.version {
                Some(WireVersion::One) => {}
                Some(WireVersion::Unsupported) => {
                    return Err(A::Error::custom(expression_error(
                        FilterExpressionErrorKind::UnsupportedVersion,
                    )));
                }
                Some(WireVersion::Invalid) | None => return Err(invalid_structure()),
            }

            let Some(WireValue::String(target)) = raw.target else {
                return Err(invalid_structure());
            };
            if !super::valid_wire_name(&target) || target != T::FILTER_TARGET {
                return Err(A::Error::custom(expression_error(
                    FilterExpressionErrorKind::InvalidTarget,
                )));
            }
            let expression = match raw.expression {
                Some(RawExpression::Node(expression)) => *expression,
                Some(RawExpression::Other) | None => return Err(invalid_structure()),
            };
            let data = expression.into_expression().map_err(A::Error::custom)?;
            validate_expression::<T>(&data).map_err(A::Error::custom)?;
            if !expression_is_resolved(&data) {
                return Err(invalid_structure());
            }
            Ok(FilterExpr {
                data,
                marker: PhantomData,
            })
        }

        fn visit_seq<A: SeqAccess<'de>>(self, sequence: A) -> Result<Self::Value, A::Error> {
            consume_seq(sequence)?;
            Err(invalid_structure())
        }

        fn visit_str<E: de::Error>(self, _: &str) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_string<E: de::Error>(self, _: String) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_bool<E: de::Error>(self, _: bool) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_i64<E: de::Error>(self, _: i64) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_u64<E: de::Error>(self, _: u64) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_f64<E: de::Error>(self, _: f64) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }

        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Err(invalid_structure())
        }
    }

    impl<'de, T: Filterable> Deserialize<'de> for FilterExpr<T> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            deserializer.deserialize_any(EnvelopeVisitor(PhantomData))
        }
    }

    fn parse_scalar_operator(value: &str) -> Option<TextOperator> {
        Some(match value {
            "eq" => TextOperator::Eq,
            "eq_ignore_case" => TextOperator::EqIgnoreCase,
            "contains" => TextOperator::Contains,
            "contains_ignore_case" => TextOperator::ContainsIgnoreCase,
            "starts_with" => TextOperator::StartsWith,
            "starts_with_ignore_case" => TextOperator::StartsWithIgnoreCase,
            "ends_with" => TextOperator::EndsWith,
            "ends_with_ignore_case" => TextOperator::EndsWithIgnoreCase,
            "in" => TextOperator::In,
            "not_in" => TextOperator::NotIn,
            "regex" => TextOperator::Regex,
            "regex_ignore_case" => TextOperator::RegexIgnoreCase,
            "lt" => TextOperator::Lt,
            "lte" => TextOperator::Lte,
            "gt" => TextOperator::Gt,
            "gte" => TextOperator::Gte,
            _ => return None,
        })
    }

    struct ExpressionRef<'a>(&'a ExprData);

    impl Serialize for ExpressionRef<'_> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            match self.0 {
                ExprData::And(expressions) | ExprData::Or(expressions) => {
                    let mut state = serializer.serialize_struct("FilterJunction", 2)?;
                    state.serialize_field(
                        "op",
                        if matches!(self.0, ExprData::And(_)) {
                            "and"
                        } else {
                            "or"
                        },
                    )?;
                    state.serialize_field("args", &ExpressionList(expressions))?;
                    state.end()
                }
                ExprData::Not(expression) => {
                    let mut state = serializer.serialize_struct("FilterNot", 2)?;
                    state.serialize_field("op", "not")?;
                    state.serialize_field("expr", &ExpressionRef(expression))?;
                    state.end()
                }
                ExprData::Predicate(predicate) => {
                    if let Some(relation) = predicate.relation_internal() {
                        let mut state = serializer.serialize_struct("FilterRelation", 4)?;
                        state.serialize_field("op", "relation")?;
                        state.serialize_field("field", predicate.field())?;
                        state.serialize_field("quantifier", relation.quantifier.label())?;
                        state.serialize_field("expr", &ExpressionRef(&relation.expression))?;
                        state.end()
                    } else {
                        let scalar = predicate.scalar_internal().ok_or_else(|| {
                            S::Error::custom(expression_error(
                                FilterExpressionErrorKind::InvalidStructure,
                            ))
                        })?;
                        let mut state = serializer.serialize_struct("FilterScalar", 3)?;
                        state.serialize_field("op", predicate.operator_label())?;
                        state.serialize_field("field", predicate.field())?;
                        state.serialize_field("value", &ScalarValue(scalar))?;
                        state.end()
                    }
                }
                ExprData::Invalid(kind) => Err(S::Error::custom(expression_error(*kind))),
            }
        }
    }

    struct ExpressionList<'a>(&'a [ExprData]);

    impl Serialize for ExpressionList<'_> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
            for expression in self.0 {
                sequence.serialize_element(&ExpressionRef(expression))?;
            }
            sequence.end()
        }
    }

    struct ScalarValue<'a>(ResolvedScalar<'a>);

    impl Serialize for ScalarValue<'_> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            match self.0 {
                ResolvedScalar::Text(operator, values, _) => {
                    if matches!(operator, TextOperator::In | TextOperator::NotIn) {
                        values.serialize(serializer)
                    } else {
                        values
                            .first()
                            .ok_or_else(|| {
                                S::Error::custom(expression_error(
                                    FilterExpressionErrorKind::InvalidStructure,
                                ))
                            })?
                            .serialize(serializer)
                    }
                }
                ResolvedScalar::Bool(operator, values) => {
                    if matches!(operator, SetOperator::In | SetOperator::NotIn) {
                        values.serialize(serializer)
                    } else {
                        values
                            .first()
                            .ok_or_else(|| {
                                S::Error::custom(expression_error(
                                    FilterExpressionErrorKind::InvalidStructure,
                                ))
                            })?
                            .serialize(serializer)
                    }
                }
                ResolvedScalar::Signed(operator, values) => {
                    IntegerValue::Signed(operator, values).serialize(serializer)
                }
                ResolvedScalar::Unsigned(operator, values) => {
                    IntegerValue::Unsigned(operator, values).serialize(serializer)
                }
                ResolvedScalar::Enum(operator, values) => {
                    if matches!(operator, SetOperator::In | SetOperator::NotIn) {
                        values.serialize(serializer)
                    } else {
                        values
                            .first()
                            .ok_or_else(|| {
                                S::Error::custom(expression_error(
                                    FilterExpressionErrorKind::InvalidStructure,
                                ))
                            })?
                            .serialize(serializer)
                    }
                }
            }
        }
    }

    enum IntegerValue<'a> {
        Signed(SetOperator, &'a [i128]),
        Unsigned(SetOperator, &'a [u128]),
    }

    impl Serialize for IntegerValue<'_> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            match self {
                // A single-valued operator rides as a scalar; only `in` and
                // `not_in` carry a list.
                Self::Signed(operator, values) if !operator.takes_a_set() => values
                    .first()
                    .ok_or_else(|| {
                        S::Error::custom(expression_error(
                            FilterExpressionErrorKind::InvalidStructure,
                        ))
                    })?
                    .to_string()
                    .serialize(serializer),
                Self::Unsigned(operator, values) if !operator.takes_a_set() => values
                    .first()
                    .ok_or_else(|| {
                        S::Error::custom(expression_error(
                            FilterExpressionErrorKind::InvalidStructure,
                        ))
                    })?
                    .to_string()
                    .serialize(serializer),
                Self::Signed(_, values) => {
                    let mut sequence = serializer.serialize_seq(Some(values.len()))?;
                    for value in *values {
                        sequence.serialize_element(&value.to_string())?;
                    }
                    sequence.end()
                }
                Self::Unsigned(_, values) => {
                    let mut sequence = serializer.serialize_seq(Some(values.len()))?;
                    for value in *values {
                        sequence.serialize_element(&value.to_string())?;
                    }
                    sequence.end()
                }
            }
        }
    }

    impl<T: Filterable> Serialize for FilterExpr<T> {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            if !super::valid_wire_name(T::FILTER_TARGET) {
                return Err(S::Error::custom(expression_error(
                    FilterExpressionErrorKind::InvalidTarget,
                )));
            }
            super::validate_wire_targets(&self.data, Some(T::FILTER_TARGET))
                .map_err(S::Error::custom)?;
            super::validate_wire_fields(&self.data).map_err(S::Error::custom)?;
            validate_expression::<T>(&self.data).map_err(S::Error::custom)?;
            if !expression_is_resolved(&self.data) {
                return Err(S::Error::custom(expression_error(
                    FilterExpressionErrorKind::InvalidStructure,
                )));
            }
            let mut state = serializer.serialize_struct("FilterEnvelope", 3)?;
            state.serialize_field("version", &VERSION)?;
            state.serialize_field("target", T::FILTER_TARGET)?;
            state.serialize_field("expr", &ExpressionRef(&self.data))?;
            state.end()
        }
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error as _;
    #[cfg(feature = "serde")]
    use std::sync::OnceLock;

    #[cfg(feature = "serde")]
    use super::set_once_eq;
    use super::{
        __private, FieldId, FilterExpressionErrorKind, PredicateData, SetOperator, SetPredicate,
        TextOperator, TextPredicate,
    };

    const TEST_FIELD: FieldId = FieldId {
        target: "sentinel-target",
        field: "sentinel-field",
    };

    fn predicate(data: PredicateData) -> __private::Predicate {
        __private::Predicate::new(TEST_FIELD, data)
    }

    #[cfg(feature = "serde")]
    #[test]
    fn once_lock_set_failures_compare_the_installed_value() {
        let target = OnceLock::new();
        assert_eq!(
            set_once_eq(&target, "record", FilterExpressionErrorKind::InvalidTarget,),
            Ok(())
        );
        assert_eq!(
            set_once_eq(&target, "record", FilterExpressionErrorKind::InvalidTarget,),
            Ok(())
        );
        assert_eq!(
            set_once_eq(&target, "other", FilterExpressionErrorKind::InvalidTarget,)
                .map_err(|error| error.kind()),
            Err(FilterExpressionErrorKind::InvalidTarget)
        );

        let family = OnceLock::new();
        assert_eq!(
            set_once_eq(&family, 1_u8, FilterExpressionErrorKind::InvalidStructure,),
            Ok(())
        );
        assert_eq!(
            set_once_eq(&family, 1_u8, FilterExpressionErrorKind::InvalidStructure,),
            Ok(())
        );
        assert_eq!(
            set_once_eq(&family, 2_u8, FilterExpressionErrorKind::InvalidStructure,)
                .map_err(|error| error.kind()),
            Err(FilterExpressionErrorKind::InvalidStructure)
        );
    }

    fn assert_validation_error(
        result: Result<(), super::FilterExpressionError>,
        expected: FilterExpressionErrorKind,
    ) {
        assert_eq!(
            result.as_ref().map_err(super::FilterExpressionError::kind),
            Err(expected)
        );
        if let Err(error) = result {
            assert!(error.source().is_none());
            assert!(!format!("{error:?}").contains("sentinel"));
            assert!(!error.to_string().contains("sentinel"));
        }
    }

    #[test]
    fn scalar_validation_reports_wrong_predicate_families_as_unknown_operators() {
        let text = predicate(PredicateData::Text(TextPredicate {
            operator: TextOperator::Eq,
            values: vec![String::from("sentinel-text")],
            compiled_regex: None,
        }));
        let boolean = predicate(PredicateData::Bool(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![true],
        }));

        assert_validation_error(
            boolean.validate_text(),
            FilterExpressionErrorKind::UnknownOperator,
        );
        assert_validation_error(
            text.validate_bool(),
            FilterExpressionErrorKind::UnknownOperator,
        );
        assert_validation_error(
            text.validate_integer(__private::IntegerKind::I8),
            FilterExpressionErrorKind::UnknownOperator,
        );
        assert_validation_error(
            text.validate_enum(&["sentinel-text"]),
            FilterExpressionErrorKind::UnknownOperator,
        );
    }

    #[test]
    fn scalar_validation_reports_malformed_shapes_as_invalid_structure() {
        let boolean_eq_without_value = predicate(PredicateData::Bool(SetPredicate {
            operator: SetOperator::Eq,
            values: Vec::new(),
        }));
        let signed_eq_with_two_values = predicate(PredicateData::Signed(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![1, 2],
        }));
        let unsigned_eq_without_value = predicate(PredicateData::Unsigned(SetPredicate {
            operator: SetOperator::Eq,
            values: Vec::new(),
        }));
        let enum_eq_with_two_values = predicate(PredicateData::Enum(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![String::from("ready"), String::from("blocked")],
        }));
        let text_eq_without_value = predicate(PredicateData::Text(TextPredicate {
            operator: TextOperator::Eq,
            values: Vec::new(),
            compiled_regex: None,
        }));
        let regex_without_compiled_state = predicate(PredicateData::Text(TextPredicate {
            operator: TextOperator::Regex,
            values: vec![String::from("sentinel-pattern")],
            compiled_regex: None,
        }));

        for result in [
            boolean_eq_without_value.validate_bool(),
            signed_eq_with_two_values.validate_integer(__private::IntegerKind::I8),
            unsigned_eq_without_value.validate_integer(__private::IntegerKind::U8),
            enum_eq_with_two_values.validate_enum(&["ready", "blocked"]),
            text_eq_without_value.validate_text(),
            regex_without_compiled_state.validate_text(),
        ] {
            assert_validation_error(result, FilterExpressionErrorKind::InvalidStructure);
        }
    }

    #[test]
    fn scalar_validation_reports_literal_mismatches_as_invalid_literal() {
        let signed_for_unsigned = predicate(PredicateData::Signed(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![1],
        }));
        let signed_out_of_range = predicate(PredicateData::Signed(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![i128::from(i8::MAX) + 1],
        }));
        let unsigned_out_of_range = predicate(PredicateData::Unsigned(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![u128::from(u8::MAX) + 1],
        }));
        let unknown_enum_variant = predicate(PredicateData::Enum(SetPredicate {
            operator: SetOperator::Eq,
            values: vec![String::from("sentinel-variant")],
        }));

        for result in [
            signed_for_unsigned.validate_integer(__private::IntegerKind::U8),
            signed_out_of_range.validate_integer(__private::IntegerKind::I8),
            unsigned_out_of_range.validate_integer(__private::IntegerKind::U8),
            unknown_enum_variant.validate_enum(&["ready", "blocked"]),
        ] {
            assert_validation_error(result, FilterExpressionErrorKind::InvalidLiteral);
        }
    }
}