praxis-stdlib 0.2.0

Method catalog schema and the Praxis prelude.
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
//! The built-in method catalog (§16.2): one structured table of every built-in
//! method.
//!
//! This is the **single source of truth** the type checker, HIR lowering, and
//! code generator consume (rule 20.3). [`builtin_catalog`] returns a finalized,
//! duplicate-free [`MethodCatalog`]; the builder rejects any duplicate
//! `(receiver, name, arity)` triple so an accidental overload is impossible
//! ("make illegal states unrepresentable").

use crate::abi;
use crate::catalog::MethodCatalog;
use crate::type_pattern::{CollectionCtor, ScalarType};
use crate::{MethodEntry, MethodLowering, Purity, TypePattern};

/// The `Vec[T]` receiver pattern, used by every Vec method entry.
fn vec_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![TypePattern::var("T")],
    }
}

/// Build the finalized built-in method catalog.
///
/// # Panics
/// Panics if two entries share a `(receiver, name, arity)` triple — that is a
/// build-time catalog bug, never a user-facing condition.
#[must_use]
pub fn builtin_catalog() -> MethodCatalog {
    MethodCatalog::build()
        .entry(vec_push())
        .entry(vec_len())
        .entry(vec_get())
        .entry(vec_is_empty())
        .entry(vec_to_text())
        .entry(deque_push_front())
        .entry(deque_push_back())
        .entry(deque_pop_front())
        .entry(deque_pop_back())
        .entry(deque_len())
        .entry(deque_get())
        .entry(deque_is_empty())
        .entry(map_insert())
        .entry(map_get())
        .entry(map_contains())
        .entry(map_remove())
        .entry(map_len())
        .entry(map_is_empty())
        .entry(set_insert())
        .entry(set_remove())
        .entry(set_contains())
        .entry(set_len())
        .entry(set_is_empty())
        .entry(counter_get())
        .entry(counter_inc())
        .entry(counter_len())
        .entry(counter_is_empty())
        .entry(max_heap_push())
        .entry(max_heap_pop())
        .entry(max_heap_peek())
        .entry(max_heap_len())
        .entry(max_heap_is_empty())
        .entry(min_heap_push())
        .entry(min_heap_pop())
        .entry(min_heap_peek())
        .entry(min_heap_len())
        .entry(min_heap_is_empty())
        .entry(bitset_insert())
        .entry(bitset_remove())
        .entry(bitset_contains())
        .entry(bitset_len())
        .entry(bitset_is_empty())
        .entry(grid_width())
        .entry(grid_height())
        .entry(grid_get())
        .entry(grid_set())
        .entry(grid_contains())
        .entry(grid_neighbors4())
        .entry(grid_neighbors8())
        .entry(grid_around4())
        .entry(grid_around8())
        .entry(grid_count4())
        .entry(grid_count8())
        .entry(grid_count4_where())
        .entry(grid_count8_where())
        .entry(grid_positions())
        .entry(grid_cells())
        .entry(grid_row())
        .entry(grid_column())
        .entry(grid_find())
        .entry(grid_find_all())
        .entry(grid_transpose())
        .entry(grid_rotate_left())
        .entry(grid_rotate_right())
        // Pipeline combinators (§6.3, ADR-127). Intrinsics the compiler fuses
        // into a single loop over the source. **One row apiece**, on the generic
        // `Iterable` receiver: `capability::iter_item` already answers "what can
        // I iterate and what does it yield" for eleven collections plus `Text`,
        // and the pipeline reads that rather than keeping a second, smaller
        // answer of its own.
        .entry(seq_map())
        .entry(seq_filter())
        .entry(seq_fold())
        .entry(seq_sum())
        .entry(seq_count())
        .entry(seq_count_if())
        // The barrier combinators (§6.3). Runtime symbols rather than
        // intrinsics — see the block comment above their definitions.
        .entry(seq_sorted())
        .entry(seq_sorted_by_key())
        .entry(seq_unique())
        .entry(seq_reversed())
        .entry(seq_frequencies())
        .entry(seq_join())
        // The two groupings (ADR-149). Barriers too, and the only rows whose
        // result nests a collection inside a collection.
        .entry(seq_chunks())
        .entry(seq_windows())
        // The remaining non-barrier combinators. Each is an intrinsic fused by
        // the MIR pipeline recognizer.
        .entry(seq_take())
        .entry(seq_skip())
        .entry(seq_take_while())
        .entry(seq_enumerate())
        .entry(seq_zip())
        .entry(seq_flat_map())
        .entry(seq_filter_map())
        .entry(seq_product())
        .entry(seq_min())
        .entry(seq_max())
        .entry(seq_min_by())
        .entry(seq_max_by())
        .entry(seq_any())
        .entry(seq_all())
        .entry(seq_find())
        .entry(seq_position())
        .entry(seq_reduce())
        // The conversions (ADR-127 decision 4). Fused sinks, one per collection
        // with a constructor — a pipeline's currency is `Vec`, and a program
        // that wants a collection back says which one.
        .entry(seq_to_vec())
        .entry(seq_to_set())
        .entry(seq_to_map())
        .entry(seq_to_counter())
        .entry(seq_to_deque())
        .entry(seq_to_min_heap())
        .entry(seq_to_max_heap())
        .entry(seq_to_bitset())
        .entry(text_len())
        .entry(text_int())
        .entry(text_float())
        .entry(text_is_empty())
        .entry(text_get())
        // Float methods (§4.12). Pure unary math, predicates, conversions, and
        // binary min/max — all lower to `praxis_float_*` runtime wrappers.
        .entry(float_abs())
        .entry(float_sqrt())
        .entry(float_floor())
        .entry(float_ceil())
        .entry(float_round())
        .entry(float_sign())
        .entry(float_to_int())
        .entry(float_to_text())
        .entry(float_is_nan())
        .entry(float_is_infinite())
        .entry(float_min())
        .entry(float_max())
        // The explicit Int→Float widening method (§4.12).
        .entry(int_to_float())
        // The Char/Int conversion pair (ADR-086), written as a pair for the
        // reason §4.12 writes Float.to_int/Int.to_float as one.
        .entry(char_to_int())
        .entry(int_to_char())
        // The other two thirds of the `to_text` family (ADR-143). `Float`'s row
        // is above; all three share one renderer with `out`.
        .entry(int_to_text())
        .entry(char_to_text())
        .entry(int_wrapping_add())
        .entry(int_saturating_add())
        .entry(int_checked_add())
        .entry(int_wrapping_sub())
        .entry(int_saturating_sub())
        .entry(int_checked_sub())
        .entry(int_wrapping_mul())
        .entry(int_saturating_mul())
        .entry(int_checked_mul())
        // Subscripts (§4.7/§6.2/§6.4). Six collections read; five of those six
        // also store — every one but the immutable `Text`. See the block comment
        // above `vec_index` for why these are catalog rows.
        .entry(vec_index())
        .entry(vec_index_set())
        .entry(deque_index())
        .entry(deque_index_set())
        .entry(text_index())
        .entry(map_index())
        .entry(map_index_set())
        .entry(counter_index())
        .entry(counter_index_set())
        .entry(grid_index())
        .entry(grid_index_set())
        // …and the two updating stores §6.2 writes. Map only: they are the two
        // wrappers that exist, and an absent entry accepting the first value is
        // a semantics no read-modify-write over the rows above can express,
        // because a subscript read of an absent key faults (§4.7).
        .entry(map_index_min())
        .entry(map_index_max())
        // Keyed enumeration: §3.3's `counts.values()`, plus the `Map` siblings.
        .entry(counter_keys())
        .entry(counter_values())
        .entry(map_keys())
        .entry(map_values())
        .finish()
        .expect("built-in catalog must be duplicate-free")
}

// --- Keyed enumeration -------------------------------------------------------
//
// Each answers a `Vec`, so every §6.3 pipeline combinator applies to the result.
// The order is fixed and deterministic (by the key's rendered form), so `keys()`
// and `values()` are index-aligned and a program's *answer* cannot depend on a
// `HashMap`'s per-process seed.

fn counter_keys() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "keys",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("T")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterKeys),
        doc: "Every key, as a `Vec[T]`, ordered with `values()`.",
    }
}

fn counter_values() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "values",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::Scalar(ScalarType::Int)],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterValues),
        doc: "Every count, as a `Vec[Int]`, ordered with `keys()`.",
    }
}

fn map_keys() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "keys",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("K")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapKeys),
        doc: "Every key, as a `Vec[K]`, ordered with `values()`.",
    }
}

fn map_values() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "values",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("V")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapValues),
        doc: "Every value, as a `Vec[V]`, ordered with `keys()`.",
    }
}

// --- Subscript rows (§4.7/§6.2/§6.4) -----------------------------------------
//
// `m[key]`, `counts[key] += 1` and `grid[x, y]` dispatch through the catalog on
// the receiver's shape and the index count, which is what a method call already
// does. Their names — `[]`, `[]=` — are not identifiers, so no program can spell
// them; the subscript grammar is their only caller.
//
// Which collections index is a language decision and this table is where it is
// recorded. Six read: `Vec`, `Deque`, `Text`, `Map`, `Counter`, `Grid`. **Five
// store** — every reader but `Text`, which is immutable (§4.3), so `t[0] = c` is
// still the report `not_index_assignable` gives.
//
// The `Vec` and `Deque` stores go through `praxis_vec_set`/`praxis_deque_set`,
// and they **replace** and never append: `v[v.len()] = x` is `IndexOutOfBounds`
// rather than a push, so an off-by-one is reported instead of growing the
// vector (ADR-064).
//
// The read rows repeat their `get` sibling's symbol on purpose — except `Map`,
// whose two answers differ by design: `.get` returns Unit for an absent key and
// `map[key]` **faults** (§4.7), so it has its own wrapper.

fn vec_index() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: crate::catalog::INDEX_READ,
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecGet),
        doc: "`v[i]` — the element at `i`; faults if out of range.",
    }
}

fn vec_index_set() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: crate::catalog::INDEX_STORE,
        params: vec![TypePattern::Scalar(ScalarType::Int), TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecSet),
        doc: "`v[i] = value` — replace the element at `i`; faults if out of range \
              (it never appends — `push` is the spelling that grows a vector).",
    }
}

fn deque_index() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: crate::catalog::INDEX_READ,
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequeGet),
        doc: "`d[i]` — the element at `i` (0-based from the front); faults if out of range.",
    }
}

fn deque_index_set() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: crate::catalog::INDEX_STORE,
        params: vec![TypePattern::Scalar(ScalarType::Int), TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequeSet),
        doc: "`d[i] = value` — replace the element at `i` (0-based from the front); \
              faults if out of range (it never inserts).",
    }
}

fn text_index() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: crate::catalog::INDEX_READ,
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Char),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextGet),
        doc: "`t[i]` — the `Char` at `i`, indexing by Unicode scalar value and not \
              by byte; faults if out of range (ADR-086).",
    }
}

fn map_index() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: crate::catalog::INDEX_READ,
        params: vec![TypePattern::var("K")],
        result: TypePattern::var("V"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapIndex),
        doc: "`m[key]` — the value for `key`; **faults** if absent (§4.7; `.get` is the \
              spelling that answers with absence).",
    }
}

fn map_index_set() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: crate::catalog::INDEX_STORE,
        params: vec![TypePattern::var("K"), TypePattern::var("V")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapInsert),
        doc: "`m[key] = value` — set `key`, replacing any prior value.",
    }
}

/// The `Map[K, V]` receiver of `min=`/`max=`, whose value is bound to `Int`.
///
/// A **bound** rather than a literal `Int` argument: the bound *pins* an
/// unresolved value type instead of merely permitting it, so `var d = Map()`
/// followed by `d[k] min= 1` gives `d` an `Int` value type rather than
/// reporting. The bound is what the wrapper needs — `praxis_map_update_min`
/// compares through `int_payload`, so a `Map[Text, Text]` would read its values
/// as `i64`s.
fn map_of_k_int_value() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Map,
        args: vec![
            TypePattern::var("K"),
            TypePattern::is_scalar("V", ScalarType::Int),
        ],
    }
}

fn map_index_min() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_int_value(),
        name: crate::catalog::INDEX_STORE_MIN,
        params: vec![TypePattern::var("K"), TypePattern::var("V")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapUpdateMin),
        doc: "`d[key] min= candidate` — keep the smaller value; an absent entry \
              accepts the first value.",
    }
}

fn map_index_max() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_int_value(),
        name: crate::catalog::INDEX_STORE_MAX,
        params: vec![TypePattern::var("K"), TypePattern::var("V")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapUpdateMax),
        doc: "`b[key] max= score` — keep the larger value; an absent entry accepts \
              the first value.",
    }
}

fn counter_index() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: crate::catalog::INDEX_READ,
        params: vec![TypePattern::var("T")],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterGet),
        doc: "`c[key]` — the count for `key`, or zero if absent; never faults.",
    }
}

fn counter_index_set() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: crate::catalog::INDEX_STORE,
        params: vec![TypePattern::var("T"), TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterSet),
        doc: "`c[key] = n` — set the count for `key`.",
    }
}

fn grid_index() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: crate::catalog::INDEX_READ,
        params: vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::Scalar(ScalarType::Int),
        ],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridGet),
        doc: "`grid[x, y]` — the cell at (x, y); faults if out of range.",
    }
}

fn grid_index_set() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: crate::catalog::INDEX_STORE,
        params: vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::var("T"),
        ],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridSet),
        doc: "`grid[x, y] = value` — set the cell at (x, y); faults if out of range.",
    }
}

// --- Text methods --------------------------------------------------------

fn text_receiver() -> TypePattern {
    TypePattern::Scalar(ScalarType::Text)
}

fn text_len() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextLen),
        doc: "Number of Unicode scalar values (chars) in the text.",
    }
}

/// `Text.int() -> Option[Int]` — the one text-to-number conversion (ADR-136).
///
/// It is what `Y001`'s help on `var count: Int = raw` points at ("this is
/// `Text`; `.int()` answers `Option[Int]`, so take it apart with `match` (or
/// use `read lines(int)`)").
///
/// `Option[Int]` rather than `Int`, for §4.7's reason and `Map.get`'s: a text
/// that is not a number is *absence*, not a fault. Input is routinely not what a
/// program hoped, and a panicking conversion would leave `"abc".int()` a crash
/// with no way to ask first.
fn text_int() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: "int",
        params: vec![],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextInt),
        doc: "The Int this text spells as `Some(n)`, or `None` if it spells none.",
    }
}

/// `Text.float() -> Option[Float]` — [`text_int`]'s twin (ADR-136).
///
/// Same shape and the same reason: a text that is not a number is *absence*, not
/// a fault. The accepted set is §7.4's `float` atomic over the whole trimmed
/// text, so `t.float()` and `parse(t, float)` cannot disagree — which means
/// `"inf"` and `"nan"` are `None`, because neither is a token the input parser
/// reads.
fn text_float() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: "float",
        params: vec![],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Float))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextFloat),
        doc: "The Float this text spells as `Some(x)`, or `None` if it spells none.",
    }
}

fn text_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextIsEmpty),
        doc: "True iff the text has no chars.",
    }
}

fn text_get() -> MethodEntry {
    MethodEntry {
        receiver: text_receiver(),
        name: "get",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Char),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextGet),
        doc: "The `Char` at `index`; faults if out of range. `t[index]` is the \
              same row and the same answer (ADR-086).",
    }
}

// ---- Float methods (§4.12) --------------------------------------------------
//
// All Float method entries share a Float receiver pattern. The pure unary math
// methods (`abs`/`sqrt`/`floor`/`ceil`/`round`/`sign`) and predicates never
// fault; `to_int` is the sole faulting method (NaN/inf/out-of-range). `min`/
// `max` take a Float argument. Conversions return Int/Text.

fn float_receiver() -> TypePattern {
    TypePattern::Scalar(ScalarType::Float)
}

fn float_abs() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "abs",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatAbs),
        doc: "Absolute value.",
    }
}

fn float_sqrt() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "sqrt",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatSqrt),
        doc: "Square root. Negative inputs yield NaN (IEEE-754).",
    }
}

fn float_floor() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "floor",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatFloor),
        doc: "Round toward negative infinity.",
    }
}

fn float_ceil() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "ceil",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatCeil),
        doc: "Round toward positive infinity.",
    }
}

fn float_round() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "round",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatRound),
        doc: "Round half away from zero.",
    }
}

fn float_sign() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "sign",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatSign),
        doc: "Sign as -1.0 / 0.0 / 1.0. NaN yields NaN.",
    }
}

fn float_to_int() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "to_int",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatToInt),
        doc: "Truncate toward zero to an Int. Faults on NaN, ±inf, or out of i64 range.",
    }
}

fn float_to_text() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "to_text",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Text),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatToText),
        doc: "Format as Text (shortest round-trip form; inf/-inf/NaN as literals).",
    }
}

fn float_is_nan() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "is_nan",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatIsNan),
        doc: "True iff NaN.",
    }
}

fn float_is_infinite() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "is_infinite",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatIsInfinite),
        doc: "True iff ±infinity.",
    }
}

fn float_min() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "min",
        params: vec![TypePattern::Scalar(ScalarType::Float)],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatMin),
        doc: "The smaller of two floats. If either is NaN, returns the other.",
    }
}

fn float_max() -> MethodEntry {
    MethodEntry {
        receiver: float_receiver(),
        name: "max",
        params: vec![TypePattern::Scalar(ScalarType::Float)],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::FloatMax),
        doc: "The larger of two floats. If either is NaN, returns the other.",
    }
}

fn int_to_float() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "to_float",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Float),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntToFloat),
        doc: "Widen to Float (explicit Int→Float conversion, §4.12).",
    }
}

// --- the `to_text` family (ADR-143) -----------------------------------------
//
// Three rows — `Int`, `Float`, `Char` — and the family is closed at three.
//
// **Each answers the characters `out` writes, by construction.** The wrapper
// behind each row calls the same `scalars::write_*` function the type
// descriptor's `format` callback calls, so there is one renderer per scalar with
// two callers rather than two renderers that have to be kept in agreement. A
// program that prints a value and a program that builds a `Text` from it
// disagreeing is the defect this shape makes unrepresentable; §4.12's
// shortest-round-trip rule for `Float` is the one that would have drifted first.
//
// **Deliberately absent, each for its own reason**, in the convention the Char
// conversion block below uses:
//
// - **`Bool.to_text()`.** No design-doc surface asks for one, and the catalog
//   invents no rows past what one asks for. `if b { "true" } else { "false" }`
//   says it, and says which spelling the program wanted.
// - **A universal `T.to_text()`.** That is §8.1 interpolation's question, not
//   this one: a hole that stringifies *any* value needs a rendering conversion
//   defined on every type, which is the implicit conversion to `Text` that
//   ADR-085 decision 2 refused for `+`. It wants its own decision.
//
// §8.1's interpolation itself stays specified and unimplemented. These rows make
// it cheaper rather than redundant — with `Int`, `Float`, `Char` and `Text` all
// covered, `"a{n}b"` can desugar to `"a" + n.to_text() + "b"` and needs no new
// runtime path.

fn int_to_text() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "to_text",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Text),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntToText),
        doc: "Format as Text — the same digits `out` writes (ADR-143).",
    }
}

// --- Char conversions (ADR-086) ----------------------------------------------
//
// The `Char`/`Int` pair, written as a pair for the reason §4.12 writes
// `Float.to_int`/`Int.to_float` as one: a one-way conversion is a one-way door.
// With `to_int` alone a program could take a `Char` apart and never build one,
// so `Grid[Char]`, `Vec[Char]` and `Map[Char, _]` would stay write-only from the
// language's side.
//
// `to_int` is required and not a nicety. A text index answers a `Char`, and
// `capability::supports_numeric` excludes `Char` on purpose ("a `Char` is a
// scalar value and not an arithmetic one"), so `t[i] - 48`, `t[i] >= 97` and a
// `Map[Int, _]` keyed on a character are all spelled by inserting `.to_int()`.
//
// **Deliberately absent, each for its own reason** — the same convention the
// `_add` trio's comment below uses, so an omission is recorded where a reader
// looks for it rather than only in a commit message:
//
// - **`is_digit`, `is_alpha`, `to_upper`, `to_lower`.** No design-doc surface
//   asks for any of them and `to_int()` expresses every one.
// - **`Text.chars()`.** `for c in text` **is** the spelling (ADR-099): a `Text`
//   is iterable and yields the same `Char` `t[i]` answers, through the same
//   `praxis_text_len`/`praxis_text_get` pair. A `chars()` row would be a second
//   spelling for one question, which is what ADR-077 refused.

fn char_to_int() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Char),
        name: "to_int",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CharToInt),
        doc: "The Unicode scalar value, as an `Int`. Never faults (ADR-086).",
    }
}

fn char_to_text() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Char),
        name: "to_text",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Text),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CharToText),
        doc: "The one-character Text holding this scalar — the same character \
              `out` writes. Never faults (ADR-143).",
    }
}

fn int_to_char() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "to_char",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Char),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntToChar),
        doc: "The `Char` with this Unicode scalar value; **faults** \
              (`InvalidChar`) if it is negative, above `0x10FFFF`, or a \
              surrogate. The narrowing half of the pair, as `Float.to_int` is \
              (ADR-086).",
    }
}

// §4.12's explicit overflow alternatives — the way out of the checked default.
//
// **The family is three modes over three operators** — `wrapping_`,
// `saturating_`, `checked_` × `add`, `sub`, `mul`. §4.12 states that shape and
// both of its closures (no `_div`/`_rem`, no `_neg`/`_abs`) and is the only
// place the rule is written; `the_overflow_alternative_family_is_three_modes_over_three_operators`
// below is what enforces it against this table.

fn int_wrapping_add() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "wrapping_add",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntWrappingAdd),
        doc: "Add with two's-complement wraparound instead of a fault.",
    }
}

fn int_saturating_add() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "saturating_add",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntSaturatingAdd),
        doc: "Add, clamping to Int's ends instead of faulting.",
    }
}

fn int_checked_add() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "checked_add",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntCheckedAdd),
        doc: "Add, answering None where the checked `+` would fault.",
    }
}

fn int_wrapping_sub() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "wrapping_sub",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntWrappingSub),
        doc: "Subtract with two's-complement wraparound instead of a fault.",
    }
}

fn int_saturating_sub() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "saturating_sub",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntSaturatingSub),
        doc: "Subtract, clamping to Int's ends instead of faulting.",
    }
}

fn int_checked_sub() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "checked_sub",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntCheckedSub),
        doc: "Subtract, answering None where the checked `-` would fault.",
    }
}

fn int_wrapping_mul() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "wrapping_mul",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntWrappingMul),
        doc: "Multiply with two's-complement wraparound instead of a fault. The \
              one row here a program could not write for itself: every arithmetic \
              operator is checked and the language has no bitwise operators.",
    }
}

fn int_saturating_mul() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "saturating_mul",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntSaturatingMul),
        doc: "Multiply, clamping to Int's ends instead of faulting.",
    }
}

fn int_checked_mul() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::Scalar(ScalarType::Int),
        name: "checked_mul",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::IntCheckedMul),
        doc: "Multiply, answering None where the checked `*` would fault.",
    }
}

fn vec_push() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: "push",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecPush),
        doc: "Append a value to the end; returns Unit.",
    }
}

fn vec_len() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecLen),
        doc: "Number of elements in the vector.",
    }
}

fn vec_get() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: "get",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecGet),
        doc: "The element at `index`; faults `IndexOutOfBounds` if out of range.",
    }
}

fn vec_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecIsEmpty),
        doc: "True iff the vector has no elements.",
    }
}

/// The `Vec[Char]` receiver pattern of `to_text` (ADR-144).
///
/// The element is a **bounded variable** rather than a literal `Char`, for
/// `map_of_k_int_value`'s reason: the bound pins an unresolved element type
/// instead of merely permitting it, so `var v = Vec()` followed by `v.to_text()`
/// gives `v` a `Char` element type, and `[1, 2].to_text()` reports `expected
/// Char, found Int` at the method name rather than "no method `to_text`".
fn vec_of_char() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![TypePattern::is_scalar("T", ScalarType::Char)],
    }
}

/// `chars.to_text()` — a sequence of `Char`s as one `Text` (ADR-144), which is
/// what renders `g.row(y)` back as the line it was read from.
///
/// **On `Vec[Char]` and not on the generic `Iterable` receiver**, which is the
/// one thing about this row a reader cannot re-derive. `Text` is one of the ten
/// pipeline receivers, so an `Iterable.to_text/0` row would sit at `(name,
/// arity)` beside every scalar `to_text` the catalog has and beside any future
/// `Text.to_text` — and `MethodCatalogBuilder::finish` answers
/// `AmbiguousWithIterable` to exactly that. A concrete `Vec` receiver is safe
/// against all of them, and a `Set[Char]` or a `Grid[Char]` row would be
/// answering a different question anyway: a sequence of characters becomes a
/// line because it has an *order*.
fn vec_to_text() -> MethodEntry {
    MethodEntry {
        receiver: vec_of_char(),
        name: "to_text",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Text),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecToText),
        doc: "These Chars as one Text, with nothing between them (ADR-144).",
    }
}

// --- Deque methods (§6.1) ------------------------------------------------

/// The `Deque[T]` receiver pattern, used by every Deque method entry.
fn deque_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Deque,
        args: vec![TypePattern::var("T")],
    }
}

fn deque_push_front() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "push_front",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequePushFront),
        doc: "Prepend a value to the front; returns Unit.",
    }
}

fn deque_push_back() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "push_back",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequePushBack),
        doc: "Append a value to the back; returns Unit.",
    }
}

fn deque_pop_front() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "pop_front",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequePopFront),
        doc: "Remove and return the front element; faults if empty.",
    }
}

fn deque_pop_back() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "pop_back",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequePopBack),
        doc: "Remove and return the back element; faults if empty.",
    }
}

fn deque_len() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequeLen),
        doc: "Number of elements in the deque.",
    }
}

fn deque_get() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "get",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequeGet),
        doc: "The element at `index` (0-based from the front); faults if out of range.",
    }
}

fn deque_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: deque_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::DequeIsEmpty),
        doc: "True iff the deque has no elements.",
    }
}

// --- Map / Set / Counter methods (§6.1, §11.3) ---------------------------

/// The `Map[K, V]` receiver pattern: two type args (key, value).
fn map_of_k_v() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Map,
        args: vec![TypePattern::var("K"), TypePattern::var("V")],
    }
}

/// The `Set[T]` receiver pattern.
fn set_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Set,
        args: vec![TypePattern::var("T")],
    }
}

/// The `Counter[T]` receiver pattern (key type only; values are Int).
fn counter_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Counter,
        args: vec![TypePattern::var("T")],
    }
}

fn map_insert() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "insert",
        params: vec![TypePattern::var("K"), TypePattern::var("V")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapInsert),
        doc: "Set `key` to `value`, replacing any prior value; returns Unit.",
    }
}

fn map_get() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "get",
        params: vec![TypePattern::var("K")],
        // §5.7 writes this signature literally: `Map[K,V].get(K) -> Option[V]`.
        // §4.7: absence is `Option`, and `map[key]` is the assertion-like half
        // that faults.
        result: TypePattern::Option(Box::new(TypePattern::var("V"))),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapGet),
        doc: "The value for `key` as `Some(value)`, or `None` if absent.",
    }
}

fn map_contains() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "contains",
        params: vec![TypePattern::var("K")],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapContains),
        doc: "True iff `key` is present in the map.",
    }
}

fn map_remove() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "remove",
        params: vec![TypePattern::var("K")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapRemove),
        doc: "Remove `key` if present; returns Unit.",
    }
}

fn map_len() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapLen),
        doc: "Number of entries in the map.",
    }
}

fn map_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: map_of_k_v(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MapIsEmpty),
        doc: "True iff the map has no entries.",
    }
}

fn set_insert() -> MethodEntry {
    MethodEntry {
        receiver: set_of_t(),
        name: "insert",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::SetInsert),
        doc: "Add `value` to the set; returns Unit.",
    }
}

fn set_remove() -> MethodEntry {
    MethodEntry {
        receiver: set_of_t(),
        name: "remove",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::SetRemove),
        doc: "Remove `value` if present; returns Unit.",
    }
}

fn set_contains() -> MethodEntry {
    MethodEntry {
        receiver: set_of_t(),
        name: "contains",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::SetContains),
        doc: "True iff `value` is in the set.",
    }
}

fn set_len() -> MethodEntry {
    MethodEntry {
        receiver: set_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::SetLen),
        doc: "Number of elements in the set.",
    }
}

fn set_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: set_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::SetIsEmpty),
        doc: "True iff the set has no elements.",
    }
}

fn counter_get() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "get",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterGet),
        doc: "The count for `key`, or zero if absent (never faults).",
    }
}

fn counter_inc() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "inc",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterInc),
        doc: "Increment the count for `key` by one; returns Unit.",
    }
}

fn counter_len() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterLen),
        doc: "Number of distinct keys in the counter.",
    }
}

fn counter_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: counter_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::CounterIsEmpty),
        doc: "True iff the counter has no keys.",
    }
}

// --- MinHeap[T] / MaxHeap[T] methods (§6.1) -----------------------------

fn min_heap_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::MinHeap,
        args: vec![TypePattern::var("T")],
    }
}

fn max_heap_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::MaxHeap,
        args: vec![TypePattern::var("T")],
    }
}

fn max_heap_push() -> MethodEntry {
    MethodEntry {
        receiver: max_heap_of_t(),
        name: "push",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MaxHeapPush),
        doc: "Push a value onto the max-heap; returns Unit.",
    }
}

fn max_heap_pop() -> MethodEntry {
    MethodEntry {
        receiver: max_heap_of_t(),
        name: "pop",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MaxHeapPop),
        doc: "Remove and return the largest element; faults if empty.",
    }
}

fn max_heap_peek() -> MethodEntry {
    MethodEntry {
        receiver: max_heap_of_t(),
        name: "peek",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MaxHeapPeek),
        doc: "The largest element without removing it; faults if empty.",
    }
}

fn max_heap_len() -> MethodEntry {
    MethodEntry {
        receiver: max_heap_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MaxHeapLen),
        doc: "Number of elements in the max-heap.",
    }
}

fn max_heap_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: max_heap_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MaxHeapIsEmpty),
        doc: "True iff the max-heap has no elements.",
    }
}

fn min_heap_push() -> MethodEntry {
    MethodEntry {
        receiver: min_heap_of_t(),
        name: "push",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MinHeapPush),
        doc: "Push a value onto the min-heap; returns Unit.",
    }
}

fn min_heap_pop() -> MethodEntry {
    MethodEntry {
        receiver: min_heap_of_t(),
        name: "pop",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MinHeapPop),
        doc: "Remove and return the smallest element; faults if empty.",
    }
}

fn min_heap_peek() -> MethodEntry {
    MethodEntry {
        receiver: min_heap_of_t(),
        name: "peek",
        params: vec![],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MinHeapPeek),
        doc: "The smallest element without removing it; faults if empty.",
    }
}

fn min_heap_len() -> MethodEntry {
    MethodEntry {
        receiver: min_heap_of_t(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MinHeapLen),
        doc: "Number of elements in the min-heap.",
    }
}

fn min_heap_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: min_heap_of_t(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::MinHeapIsEmpty),
        doc: "True iff the min-heap has no elements.",
    }
}

// --- BitSet methods (§6.1) ----------------------------------------------

/// The `BitSet` receiver pattern (nullary — no type args).
fn bitset_receiver() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::BitSet,
        args: vec![],
    }
}

fn bitset_insert() -> MethodEntry {
    MethodEntry {
        receiver: bitset_receiver(),
        name: "insert",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::BitsetInsert),
        doc: "Set the bit for a non-negative integer; returns Unit.",
    }
}

fn bitset_remove() -> MethodEntry {
    MethodEntry {
        receiver: bitset_receiver(),
        name: "remove",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::BitsetRemove),
        doc: "Clear the bit for an integer; returns Unit.",
    }
}

fn bitset_contains() -> MethodEntry {
    MethodEntry {
        receiver: bitset_receiver(),
        name: "contains",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        // The one `ScalarPrimitive` row in the catalog (ADR-118 decision 6):
        // `bs.contains(x)` lowers to `Inst::BitsetContains`, whose result is a
        // `Scalar(Bool)` and whose out-of-line form is this wrapper.
        lowering: MethodLowering::ScalarPrimitive(abi::RuntimeSymbol::BitsetContains),
        doc: "True iff the bit for the integer is set.",
    }
}

fn bitset_len() -> MethodEntry {
    MethodEntry {
        receiver: bitset_receiver(),
        name: "len",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::BitsetLen),
        doc: "Number of set bits (popcount).",
    }
}

fn bitset_is_empty() -> MethodEntry {
    MethodEntry {
        receiver: bitset_receiver(),
        name: "is_empty",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::BitsetIsEmpty),
        doc: "True iff no bits are set.",
    }
}

// --- Grid[T] methods (§6.4) ---------------------------------------------

/// The `Grid[T]` receiver pattern.
fn grid_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Grid,
        args: vec![TypePattern::var("T")],
    }
}

/// A `(x, y)` point: the `(Int, Int)` tuple shape returned by grid methods.
fn point_pattern() -> TypePattern {
    TypePattern::Tuple(vec![
        TypePattern::Scalar(ScalarType::Int),
        TypePattern::Scalar(ScalarType::Int),
    ])
}

fn grid_width() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "width",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridWidth),
        doc: "The number of columns.",
    }
}

fn grid_height() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "height",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridHeight),
        doc: "The number of rows.",
    }
}

fn grid_get() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "get",
        params: vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::Scalar(ScalarType::Int),
        ],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridGet),
        doc: "The cell at (x, y); faults if out of range.",
    }
}

fn grid_set() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "set",
        params: vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::var("T"),
        ],
        result: TypePattern::Unit,
        purity: Purity::Impure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridSet),
        doc: "Set the cell at (x, y); faults if out of range.",
    }
}

fn grid_contains() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "contains",
        params: vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::Scalar(ScalarType::Int),
        ],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridContains),
        doc: "True iff (x, y) is within the grid.",
    }
}

fn grid_neighbors4() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "neighbors4",
        params: vec![point_pattern()],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![point_pattern()],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridNeighbors4),
        doc: "The 4 orthogonal in-bounds neighbors of a point, as a Vec of (x, y).",
    }
}

fn grid_neighbors8() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "neighbors8",
        params: vec![point_pattern()],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![point_pattern()],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridNeighbors8),
        doc: "The 8 in-bounds neighbors of a point, as a Vec of (x, y).",
    }
}

/// `Option[(Int, Int)]` — one direction of a neighbourhood record. `None` is a
/// direction that leaves the grid, which is exactly what a clipped `Vec`
/// cannot say.
fn maybe_point() -> TypePattern {
    TypePattern::Option(Box::new(point_pattern()))
}

/// `Around4 { up, left, right, down }` — the plus, read off the page with the
/// centre skipped (§6.4).
///
/// **The field order written here is the runtime's layout order.** A field read
/// compiles to a slot index taken from this list, and
/// `praxis_runtime::records::AROUND4_DIRECTIONS` is what the value is assembled
/// in; the record is nominal so ADR-152's canonicalization leaves both alone,
/// which means nothing derives one order from the other and the two are simply
/// required to agree. `around_schemas_match_the_catalog` is what holds them
/// together — a disagreement reads the wrong direction and says nothing.
fn around4_pattern() -> TypePattern {
    TypePattern::Record {
        name: "Around4",
        fields: vec![
            ("up", maybe_point()),
            ("left", maybe_point()),
            ("right", maybe_point()),
            ("down", maybe_point()),
        ],
    }
}

/// `Around8` — the eight cells of a 3×3 block in reading order, centre skipped.
/// See [`around4_pattern`] on why the order is load-bearing.
fn around8_pattern() -> TypePattern {
    TypePattern::Record {
        name: "Around8",
        fields: vec![
            ("up_left", maybe_point()),
            ("up", maybe_point()),
            ("up_right", maybe_point()),
            ("left", maybe_point()),
            ("right", maybe_point()),
            ("down_left", maybe_point()),
            ("down", maybe_point()),
            ("down_right", maybe_point()),
        ],
    }
}

/// `around4(p)` — the four orthogonal neighbours by name (§6.4).
///
/// **Not a replacement for `neighbors4`.** That row answers a `Vec` clipped to
/// what is in bounds, which is the shape a graph walk takes —
/// `bfs(start, |p| g.neighbors4(p))` is ADR-060's own spelling and the walk's
/// neighbours closure is typed `(T) -> Vec[T]`. What it cannot express is
/// *which* direction each neighbour was, and off the edge of the grid, that
/// there was a direction at all. Every field here is an `Option`, so both
/// survive.
fn grid_around4() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "around4",
        params: vec![point_pattern()],
        result: around4_pattern(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridAround4),
        doc: "The 4 orthogonal neighbors by name: { up, left, right, down }, \
              each Some((x, y)) or None off the grid.",
    }
}

/// `around8(p)` — all eight neighbours by name. See [`grid_around4`].
fn grid_around8() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "around8",
        params: vec![point_pattern()],
        result: around8_pattern(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridAround8),
        doc: "The 8 neighbors by name, in reading order: { up_left, up, up_right, \
              left, right, down_left, down, down_right }, each Some((x, y)) or None.",
    }
}

/// `count4(p, v)` — the orthogonal in-bounds neighbours holding `v`.
///
/// The receiver's `T` is unbounded, exactly as `find(T)` and `find_all(T)` are:
/// equality goes through the value's own descriptor callback at run time, and a
/// type without one answers "not equal" rather than being refused here. A
/// `CapKind` bound would refuse `Grid[T]` receivers that never call this.
fn grid_count4() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "count4",
        params: vec![point_pattern(), TypePattern::var("T")],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridCount4),
        doc: "How many of the 4 orthogonal neighbors hold `value`. \
              A neighbor off the grid has no cell and is not counted.",
    }
}

/// `count8(p, v)` — the eight in-bounds neighbours holding `v`. See
/// [`grid_count4`].
fn grid_count8() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "count8",
        params: vec![point_pattern(), TypePattern::var("T")],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridCount8),
        doc: "How many of the 8 neighbors hold `value`. \
              A neighbor off the grid has no cell and is not counted.",
    }
}

/// `count4_where(p, f)` — the orthogonal in-bounds neighbours whose cell `f`
/// accepts.
///
/// The predicate is never called for a direction that leaves the grid: there is
/// no cell to hand it, and inventing one would mean choosing a value the cell
/// type may not have.
fn grid_count4_where() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "count4_where",
        params: vec![
            point_pattern(),
            TypePattern::Function {
                params: vec![TypePattern::var("T")],
                result: Box::new(TypePattern::Scalar(ScalarType::Bool)),
            },
        ],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridCount4Where),
        doc: "How many of the 4 orthogonal neighbors hold a cell the closure accepts. \
              A neighbor off the grid has no cell, so the closure never sees one.",
    }
}

/// `count8_where(p, f)` — the eight in-bounds neighbours whose cell `f`
/// accepts. See [`grid_count4_where`].
fn grid_count8_where() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "count8_where",
        params: vec![
            point_pattern(),
            TypePattern::Function {
                params: vec![TypePattern::var("T")],
                result: Box::new(TypePattern::Scalar(ScalarType::Bool)),
            },
        ],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridCount8Where),
        doc: "How many of the 8 neighbors hold a cell the closure accepts. \
              A neighbor off the grid has no cell, so the closure never sees one.",
    }
}

fn grid_positions() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "positions",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![point_pattern()],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridPositions),
        doc: "All (x, y) positions in row-major order, as a Vec.",
    }
}

fn grid_cells() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "cells",
        params: vec![],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("T")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridCells),
        doc: "All cells in row-major order, as a Vec.",
    }
}

fn grid_row() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "row",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("T")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridRow),
        doc: "Row `y` as a Vec; faults if out of range.",
    }
}

fn grid_column() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "column",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![TypePattern::var("T")],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridColumn),
        doc: "Column `x` as a Vec; faults if out of range.",
    }
}

fn grid_find() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "find",
        params: vec![TypePattern::var("T")],
        // Absence is `Option`, not the Unit sentinel under a `(Int, Int)`
        // static type (§4.7). `find_all` needs no such thing — a `Vec` already
        // encodes "nothing matched" as emptiness.
        result: TypePattern::Option(Box::new(point_pattern())),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridFind),
        doc: "The first (x, y) whose cell equals `value` as `Some((x, y))`, or `None`.",
    }
}

fn grid_find_all() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "find_all",
        params: vec![TypePattern::var("T")],
        result: TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![point_pattern()],
        },
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridFindAll),
        doc: "All (x, y) positions whose cell equals `value`, as a Vec.",
    }
}

fn grid_transpose() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "transpose",
        params: vec![],
        result: grid_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridTranspose),
        doc: "A transposed copy (rows ↔ columns).",
    }
}

fn grid_rotate_left() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "rotate_left",
        params: vec![],
        result: grid_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridRotateLeft),
        doc: "A copy rotated 90° counter-clockwise.",
    }
}

fn grid_rotate_right() -> MethodEntry {
    MethodEntry {
        receiver: grid_of_t(),
        name: "rotate_right",
        params: vec![],
        result: grid_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::GridRotateRight),
        doc: "A copy rotated 90° clockwise.",
    }
}

// --- Pipeline combinators (§6.3, ADR-127) ---------------------------------
// The functional-sequence pipeline: intrinsics the compiler fuses into a single
// loop over the source. Sinks (sum/count/fold) terminate, and a chain that ends
// without one materializes anyway (ADR-126).
//
// **A pipeline's receiver is anything a `for` loop can walk**, and it yields
// what the `for` loop's variable would bind (ADR-127 decision 1). One row per
// combinator, on `TypePattern::Iterable`, whose ten accepted receivers are
// `PIPELINE_RECEIVERS` plus `Text`.
//
// The receiver generalizes; **two parameters deliberately do not.** `zip`'s
// argument is a `Vec[U]` and `flat_map`'s closure answers one, because the fused
// loop indexes each of them with `praxis_vec_len`/`praxis_vec_get` directly and
// neither has an `IterPlan` in scope. `m.zip(s)` on a `Set` is a unification
// failure at the argument and the spelling is `m.zip(s.to_vec())`;
// `MethodCatalogBuilder::finish` refuses a row that generalizes either.

/// The generic pipeline receiver at an unconstrained item — `map`, `filter`,
/// `count` and the rest of the twenty-three fused rows.
fn iterable_of_t() -> TypePattern {
    TypePattern::iterable(TypePattern::var("T"))
}

/// `(T) -> U` — the shape of `map`'s closure argument.
fn t_to_u() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T")],
        result: Box::new(TypePattern::var("U")),
    }
}

/// `(T) -> Bool` — the shape of `filter`'s predicate.
fn t_to_bool() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T")],
        result: Box::new(TypePattern::Scalar(ScalarType::Bool)),
    }
}

/// `(T) -> Option[U]` — the shape of `filter_map`'s closure argument.
///
/// `Option[U]` and not `map`'s `(T) -> U`: with an unconstrained `U` there is
/// nothing at runtime that says "this element mapped to nothing", so no
/// filtering would be possible. `Option` (ADR-076) makes the distinction
/// representable — absence is a variant, so the drop test is a tag compare.
fn t_to_option_u() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T")],
        result: Box::new(TypePattern::Option(Box::new(TypePattern::var("U")))),
    }
}

/// `(Acc, T) -> Acc` — the shape of `fold`'s combining closure.
fn acc_t_to_acc() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("Acc"), TypePattern::var("T")],
        result: Box::new(TypePattern::var("Acc")),
    }
}

/// `(T, T) -> T` — the shape of `reduce`'s combining closure.
///
/// **`reduce` is `fold` without the seed**, so its accumulator *is* the element
/// type; there is no second variable for it to be. Sharing [`acc_t_to_acc`]
/// with `fold` would leave the closure's first parameter untied to the element,
/// so `["ab", "c"].reduce(|a, b| a.len())` would type-check with `a` unpinned —
/// the closure answering `Int` while `reduce` answers `Text`, a disagreement
/// MIR's pipeline recognizer then asserts on.
fn t_t_to_t() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T"), TypePattern::var("T")],
        result: Box::new(TypePattern::var("T")),
    }
}

fn seq_map() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "map",
        params: vec![t_to_u()],
        result: vec_of_u(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_map"),
        doc: "Apply a function to each element, collecting into a Vec.",
    }
}

/// `Vec[U]` — the result of a `map` (a fresh element variable U). The pipeline
/// is eager (ADR-028 decision 2): a stage materializes a `Vec`.
fn vec_of_u() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![TypePattern::var("U")],
    }
}

fn seq_filter() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "filter",
        params: vec![t_to_bool()],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_filter"),
        doc: "Keep elements satisfying a predicate, collecting into a Vec.",
    }
}

fn seq_fold() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "fold",
        params: vec![TypePattern::var("Acc"), acc_t_to_acc()],
        result: TypePattern::var("Acc"),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_fold"),
        doc: "Reduce elements left-to-right with an accumulator and combining closure.",
    }
}

fn seq_sum() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_int_elem(),
        name: "sum",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_sum"),
        doc: "Sum the (Int) elements.",
    }
}

fn seq_count() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "count",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_count"),
        doc: "Number of elements.",
    }
}

/// `v.count(pred)` — §6.3's `count` with a predicate, which is what §3.3 writes.
///
/// A second *arity* of one name, which the catalog's `(receiver, name, arity)`
/// key allows: `count()` is the element count and `count(pred)` the
/// matching-element count.
fn seq_count_if() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "count",
        params: vec![t_to_bool()],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_count"),
        doc: "Number of elements satisfying the predicate.",
    }
}

// **There is no `collect` row, and ADR-126 is why.** A chain that ends on a
// streaming stage already materializes: `recognize_pipeline` appends the
// `Collect` sink itself, so `v.map(f)` *is* a `Vec[U]`. This pipeline is eager
// (ADR-028 decision 2), so a `collect` row would name a step the compiler takes
// whether or not it is written.

// --- the barrier combinators (§6.3) ---------------------------------------
//
// A barrier needs the whole sequence before it can answer anything, so it
// cannot be fused into the loop feeding it. That makes it the opposite kind of
// row from everything above: a `RuntimeSymbol`, not an `Intrinsic`. That is the
// MIR fuser's guardrail and not a style preference — an `Intrinsic` with no
// `classify_link`/`classify_sink` arm is a row with no lowering at all, which
// `intrinsics_are_all_recognized_so_there_is_no_second_lowering` refuses.
//
// `recognize_pipeline` already ends a fused chain at an unclassified
// `MethodCall` and starts a fresh one from its result, which is exactly what a
// barrier means: `pairs.map(f).sorted()` fuses the map into a collect, calls the
// wrapper, and `sorted(…).zip(…)` starts again.
//
// **The receiver is `Iterable` like everything else (ADR-127 decision 3), and
// the lowering materializes it first.** A wrapper needs a real `VecPayload`, so
// `build::emit_iter_vec` puts the plan's snapshot — or, for a receiver with no
// snapshot symbol, a materializing walk — in front of the call. A `Vec[T]`
// receiver is the rejected alternative: it makes `set.map(f).sorted()` legal
// and `set.sorted()` a `Y110`, which is a rule nobody can hold in their head.
//
// **`reversed` is a barrier for the definition's own reason** (ADR-145): it
// cannot answer its first element until it has seen the last one. A
// `classify_link` arm would be classified on name and arity alone and applied
// wherever the name appears in a chain, and `v.filter(p).reversed()` does not
// know the filtered length up front — so a fused reverse would be unsound
// anywhere but immediately adjacent to the source. Walking `emit_iter_item` at
// `len - 1 - idx` for that source-adjacent case is a real optimization and a
// deliberate non-goal here: a row has exactly one `MethodLowering`, and the
// general case has to keep working.
//
// **`join` is one row, on the generic receiver, with its item bounded to
// `Text`** (ADR-144). The bound is on the item and not on a second row because
// two `Iterable` rows differing only in their item bound are not duplicates —
// `finish` accepts them, and dispatch would then resolve by insertion order,
// which is the precedence rule ADR-127 decision 6 refuses. A concrete
// `Vec[Char].join/1` beside the generic row is refused outright as
// `AmbiguousWithIterable`. So the sequence-of-`Char` case is a differently-named
// row — `Vec[Char].to_text()`, defined beside `vec_is_empty` — and a
// sequence-of-`Int` joins by rendering first: `ns.map(|n| n.to_text()).join(",")`.
//
// **`chunks` and `windows` answer `Vec[Vec[T]]`** (ADR-149). Their wrappers
// label the *outer* `Vec` with `collections::VEC` while the inner ones keep the
// element descriptor: `outer.push(inner)` builds a `Vec[Vec[T]]` and
// `adopt_or_reject` labels it `VEC`, so a wrapper answering anything else would
// disagree with `push`. Naming a label its receiver cannot supply is what
// `praxis_grid_positions` and three siblings do with `&tuples::TUPLE`.
//
// They are barriers for `reversed`'s reason and not for a new one: a grouping
// is a fact about positions in the whole sequence, so neither can answer its
// first group from one element. And they are the two rows in the catalog that
// fault on an *argument* — see [`seq_chunks`].

/// `sorted` — a new `Vec` in ascending order (§6.3).
///
/// The `Ord` bound is the row's own, and it has to be: the wrapper orders
/// through the element descriptor's `compare` callback, and
/// `require_collection_invariants` — which is where the language's other
/// ordering rule lives — is applied to the receiver *type*, where it would be
/// wrong. A `Vec` of unorderable things is a perfectly good `Vec` right up until
/// someone sorts it.
fn seq_sorted() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::Ord)),
        name: "sorted",
        params: vec![],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecSorted),
        doc: "A new Vec holding these elements in ascending order.",
    }
}

/// `unique` — a new `Vec` with later duplicates dropped, in first-occurrence
/// order (§6.3).
///
/// `HashStable` and not `Hash`: sameness is decided by the descriptor's `hash`
/// and `equals`, so an element that can change after it has been seen would not
/// be recognized the second time (D4).
fn seq_unique() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::HashStable)),
        name: "unique",
        params: vec![],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecUnique),
        doc: "A new Vec with duplicate elements removed, keeping first occurrences.",
    }
}

/// `reversed` — a new `Vec` holding these elements back to front (ADR-145).
///
/// **No capability bound at all**, and that is the row's own claim rather than
/// an omission: reversal reads no descriptor callback, so where `sorted` needs
/// `Ord` and `unique` needs `HashStable`, a `Vec` of closures reverses. The
/// wrapper cannot fail either, which is why its manifest row is `Allocates`.
///
/// It answers `Vec[T]` on every one of the ten receivers — including a `Range`,
/// so `for y in (0..n).reversed()` is the countdown. That does *not* reopen
/// ADR-059 decision 3: no descending `Range` value exists, `RangeVal::new` still
/// clamps, and a pipeline's currency is `Vec` (ADR-127 decision 6).
fn seq_reversed() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "reversed",
        params: vec![],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecReversed),
        doc: "A new Vec holding these elements in reverse order.",
    }
}

/// `Vec[Vec[T]]` — what `chunks` and `windows` answer (ADR-149).
///
/// The one result pattern in the catalog that nests a collection inside a
/// collection, and it is written once for both rows so the two cannot come to
/// disagree about their shape. `pattern_to_type` recurses, so nothing else is
/// needed to instantiate it.
fn vec_of_vec_of_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![vec_of_t()],
    }
}

/// `chunks(n)` — these elements in consecutive runs of `n`, the last short if
/// the length does not divide (ADR-149).
///
/// **No capability bound, for `reversed`'s reason**: a grouping reads no
/// descriptor callback — not `compare`, not `equals`, not `hash` — so a `Vec` of
/// closures chunks. What it *does* have that `reversed` has not is a fault, and
/// the fault is on the argument rather than on an element: `n <= 0` is refused
/// with `InvalidSize` before the receiver is walked. A run of zero elements is
/// not a short run, it is not a run — chunking any non-empty sequence into them
/// has no finite answer — and a negative one names nothing at all. That is the
/// row's whole faulting surface, which is why its manifest row is
/// `AllocatesAndFaults` and `reversed`'s is `Allocates`.
///
/// A *short last chunk* is not that fault and must not be confused with it:
/// `[1, 2, 3].chunks(2)` is `[[1, 2], [3]]`, because the question "which
/// consecutive runs of two are there" has an answer for a sequence of three and
/// the trailing element is part of it. `windows` is where a group that does not
/// fit is dropped instead, and the two differ there because they are asking
/// different questions.
fn seq_chunks() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "chunks",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: vec_of_vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecChunks),
        doc: "Consecutive non-overlapping runs of n; the last may be shorter. \
              Faults if n is not positive.",
    }
}

/// `windows(n)` — every consecutive run of exactly `n`, each starting one element
/// after the last (ADR-149).
///
/// Plural, like `chunks` beside it and like every other row that answers many
/// things — `frequencies`, `positions`, `cells`, `keys`, `items`. It is Rust's
/// spelling too, and it is what §6.3 and ADR-029 have called this row since
/// before it existed.
///
/// **A window that does not fit is dropped, and that is not the `chunks` fault
/// arriving late.** `[1, 2].windows(5)` is `[]`: "which runs of five are there"
/// is a perfectly good question about a sequence of two, and its answer is
/// none. What has no answer is a run of `n <= 0`, which is the same
/// `InvalidSize` [`seq_chunks`] raises and for the same reason.
fn seq_windows() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "windows",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: vec_of_vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecWindows),
        doc: "Every consecutive run of exactly n, sliding by one. Empty if n \
              exceeds the length; faults if n is not positive.",
    }
}

/// An iterable of `Text`s, spelled as a bounded variable for
/// [`iterable_of_int_elem`]'s reason: the row still *matches* a receiver whose
/// item is a `Char` and rejects it with `expected Text, found Char` at the
/// method name, rather than "no method `join` on this type".
fn iterable_of_text_elem() -> TypePattern {
    TypePattern::iterable(TypePattern::is_scalar("T", ScalarType::Text))
}

/// `join` — these `Text` elements concatenated with a separator between them
/// (ADR-144).
///
/// The separator is a required argument and not an optional one, because the
/// catalog has no optional arguments: a row is `(receiver, name, arity)`, and
/// `join()` beside `join(Text)` would be two rows for one question. `join("")`
/// is the no-separator spelling and says so where it is written.
///
/// **It renders nothing.** A `Vec[Int]` is a type error at the item, not a
/// sequence quietly stringified — which is what keeps `join` from being a back
/// door around ADR-143's decision about which types have a `to_text`. The
/// spelling is `ns.map(|n| n.to_text()).join(", ")`, and it says that it renders.
fn seq_join() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_text_elem(),
        name: "join",
        params: vec![TypePattern::Scalar(ScalarType::Text)],
        result: TypePattern::Scalar(ScalarType::Text),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecJoin),
        doc: "These Text items concatenated with `sep` between them.",
    }
}

/// `frequencies` — a `Counter[T]` of how often each element occurs (§6.3, §6.2).
///
/// The **first** catalog row whose result is a keyed collection, and the reason
/// `Bound::Kind` exists. `require_collection_invariants` asks the key rule of a
/// method's receiver only; here the receiver is an ordinary `Vec` that is
/// allowed to hold anything, and it is the *result* that has keys. So the bound
/// is written on the row, where `MethodCatalogBuilder::finish` will refuse it if
/// it ever contradicts another.
fn seq_frequencies() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::HashStable)),
        name: "frequencies",
        params: vec![],
        result: counter_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecFrequencies),
        doc: "A Counter holding how many times each element occurs.",
    }
}

// --- the remaining non-barrier combinators (§6.3) -------------------------
// Each is an intrinsic lowered by the MIR fuser (`recognize_pipeline` +
// `lower_pipeline`) into a single fused loop, on the generic `Iterable`
// receiver like every other combinator (ADR-127 decision 1).

/// `(T, T) -> Bool` — the shape of `min_by`/`max_by`'s comparator ("less-than").
fn t_t_to_bool() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T"), TypePattern::var("T")],
        result: Box::new(TypePattern::Scalar(ScalarType::Bool)),
    }
}

/// `(T) -> Vec<U>` — the shape of `flat_map`'s closure.
fn t_to_vec_u() -> TypePattern {
    TypePattern::Function {
        params: vec![TypePattern::var("T")],
        result: Box::new(vec_of_u()),
    }
}

// Streaming stages ---------------------------------------------------------

fn seq_take() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "take",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_take"),
        doc: "Keep at most the first n elements.",
    }
}

fn seq_skip() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "skip",
        params: vec![TypePattern::Scalar(ScalarType::Int)],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_skip"),
        doc: "Drop the first n elements.",
    }
}

fn seq_take_while() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "take_while",
        params: vec![t_to_bool()],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_take_while"),
        doc: "Keep elements until the predicate is false.",
    }
}

/// `Vec[(Int, T)]` — the index/element pairs `enumerate`'s fused loop builds.
fn vec_of_index_and_t() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![TypePattern::Tuple(vec![
            TypePattern::Scalar(ScalarType::Int),
            TypePattern::var("T"),
        ])],
    }
}

/// `Vec[(T, U)]` — what `zip` yields, pairing the receiver's element with the
/// argument sequence's. The two element types are independent.
fn vec_of_t_and_u() -> TypePattern {
    TypePattern::Collection {
        ctor: CollectionCtor::Vec,
        args: vec![TypePattern::Tuple(vec![
            TypePattern::var("T"),
            TypePattern::var("U"),
        ])],
    }
}

fn seq_enumerate() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "enumerate",
        params: vec![],
        result: vec_of_index_and_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_enumerate"),
        doc: "Pair each element with its index.",
    }
}

fn seq_zip() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "zip",
        params: vec![vec_of_u()],
        result: vec_of_t_and_u(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_zip"),
        doc: "Pair elements with another sequence, stopping at the shorter length.",
    }
}

fn seq_flat_map() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "flat_map",
        params: vec![t_to_vec_u()],
        result: vec_of_u(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_flat_map"),
        doc: "Map each element to a Vec and concatenate the results.",
    }
}

fn seq_filter_map() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "filter_map",
        params: vec![t_to_option_u()],
        result: vec_of_u(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_filter_map"),
        doc: "Map each element to an Option and keep the Some payloads.",
    }
}

// Aggregating sinks (scalar result) ---------------------------------------
//
// `sum`, `product`, `min` and `max` are **Int** operations. Each one lowers to
// an `ExtractScalar` at `ScalarKind::Int` followed by an `IntBinOp` or an
// `IntCmp`, and the row's own result says `Int`. The element bound therefore has
// to be `Int` and not `Numeric`: a `Numeric` bound would bless `Float`, and
// `Vec[Float].sum()` would reinterpret each float's bits as an integer and
// return nonsense. `Bool` is excluded for the same reason.
//
// The bound is discharged by unification, so an element type that is *not yet
// known* is pinned to `Int` rather than merely allowed: `v.map(f).sum()` pins the
// closure's result.

/// An iterable of `Int`s, spelled as a bounded variable so the entry still
/// *matches* a receiver whose item is `Bool` or `Float` and rejects it with
/// `expected Int, found …` instead of "no method `sum` on this type".
///
/// Written once for all ten receivers rather than once per receiver, which is
/// what keeps the bound from drifting between them (ADR-127 decision 1).
fn iterable_of_int_elem() -> TypePattern {
    TypePattern::iterable(TypePattern::is_scalar("T", ScalarType::Int))
}

fn seq_product() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_int_elem(),
        name: "product",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_product"),
        doc: "Multiply the (Int) elements.",
    }
}

fn seq_min() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_int_elem(),
        name: "min",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_min"),
        doc: "Smallest (Int) element. Faults on an empty sequence (D1).",
    }
}

fn seq_max() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_int_elem(),
        name: "max",
        params: vec![],
        result: TypePattern::Scalar(ScalarType::Int),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_max"),
        doc: "Largest (Int) element. Faults on an empty sequence (D1).",
    }
}

fn seq_min_by() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "min_by",
        params: vec![t_t_to_bool()],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_min_by"),
        doc: "Smallest element per a (T,T)->Bool \"less-than\" comparator.",
    }
}

fn seq_max_by() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "max_by",
        params: vec![t_t_to_bool()],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_max_by"),
        doc: "Largest element per a (T,T)->Bool \"less-than\" comparator.",
    }
}

fn seq_any() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "any",
        params: vec![t_to_bool()],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_any"),
        doc: "True if any element satisfies the predicate (short-circuits).",
    }
}

fn seq_all() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "all",
        params: vec![t_to_bool()],
        result: TypePattern::Scalar(ScalarType::Bool),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_all"),
        doc: "True if all elements satisfy the predicate (short-circuits).",
    }
}

fn seq_find() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "find",
        params: vec![t_to_bool()],
        result: TypePattern::Option(Box::new(TypePattern::var("T"))),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_find"),
        doc: "The first matching element, or None.",
    }
}

fn seq_position() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "position",
        params: vec![t_to_bool()],
        result: TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int))),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_position"),
        doc: "The index of the first matching element, or None.",
    }
}

fn seq_reduce() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "reduce",
        params: vec![t_t_to_t()],
        result: TypePattern::var("T"),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_reduce"),
        doc: "Reduce left-to-right, seeded with the first element.",
    }
}

/// `sorted_by_key(f)` — a new `Vec` ordered by the key `f` extracts (ADR-127
/// decision 5).
///
/// **A keyed collection cannot order its own items.** ADR-045 decided that no
/// composite is orderable, because MIR had one integer compare and `(1, 2) < (1,
/// 3)` would have compared two schema pointers — so the moment a pipeline's item
/// is a pair, which is the moment its source is a `Map` or a `Counter`, `sorted`
/// is unavailable and "the five most common values" has no spelling.
///
/// So the `Ord` bound is on the **extracted key** rather than on the element,
/// and the composite-ordering question ADR-045 deferred stays deferred.
///
/// A barrier like `sorted`, and for the same reason: it needs the whole sequence
/// before it can answer its first element. Its receiver is `Iterable`, so
/// `build::emit_iter_vec` materializes it in front of the wrapper.
fn seq_sorted_by_key() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "sorted_by_key",
        params: vec![TypePattern::Function {
            params: vec![TypePattern::var("T")],
            result: Box::new(TypePattern::of_kind("K", crate::CapKind::Ord)),
        }],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecSortedByKey),
        doc: "A new Vec ordered by the key the closure extracts.",
    }
}

// --- the conversions (ADR-127 decision 4) ---------------------------------
//
// **A pipeline's currency is `Vec`**: every streaming stage answers one,
// whatever the receiver was, and a program that wants a collection back says
// which one. `set.filter(p)` is a `Vec[T]`; `set.filter(p).to_set()` is a
// `Set[T]`. One sentence answers "what does `filter` return" for all ten
// receivers, and it is answerable without knowing which receiver you are on —
// which is what decision 6 declined `map_values` and the shape-preserving family
// to keep.
//
// Each is a **fused sink**, not a barrier: `Sink::CollectInto`'s accumulator is
// the target collection, so `v.map(f).to_set()` is one loop with no intermediate
// `Vec`. The per-element step is one wrapper that already exists.
//
// **The set is closed at "every collection with a constructor", and that is the
// point.** The ask named `Set`/`Map`/`Counter`; the last four are here because
// leaving them out is what creates an asymmetry decision 6 would then have to
// defend — `deque.filter(p)` answering a `Vec` with no way back to a `Deque`,
// and no way to build a heap from a sequence without a `while` loop. `Grid` is
// the one collection with no row: a grid needs a width, and a flat item sequence
// does not carry one.

/// `to_vec()` — the item sequence as a `Vec`.
///
/// **This is not `collect` coming back.** ADR-126 deleted `collect` because it
/// "named a step the compiler takes anyway" — a chain ending on a stage already
/// materializes. For nine of `to_vec`'s ten receivers it names a step the
/// compiler does **not** take: `s.to_vec()` is the only way to get a `Vec[T]` out
/// of a `Set`, and `m.to_vec()` the only way to get `Vec[(K, V)]` out of a `Map`,
/// where `keys()` and `values()` answer two aligned halves and nothing joins
/// them.
///
/// On a `Vec` receiver it degenerates to the identity, and it answers **the same
/// reference**, not a copy. That is the second half of ADR-126 decision 2 kept:
/// that decision declined to leave a shallow copy behind "under a name that does
/// not mention it", and this name does not mention one either.
fn seq_to_vec() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "to_vec",
        params: vec![],
        result: vec_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_vec"),
        doc: "The items as a Vec. On a Vec receiver this is the receiver itself.",
    }
}

/// `to_set()` — a `Set[T]`, duplicates dropped and no order kept.
///
/// `HashStable` for the reason every key rule is: an element that can change
/// after it is stored moves its own bucket without moving the entry, and cannot
/// be found again (D4). The bound is the row's own because
/// `require_collection_invariants` asks about the *receiver*, and here it is the
/// **result** that has the keys — the same shape `frequencies` established.
///
/// Not the same question as `unique()`, and the reason is worth writing next to
/// both: `unique` answers a `Vec` in first-occurrence order, and a `Set` has no
/// order to preserve.
fn seq_to_set() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::HashStable)),
        name: "to_set",
        params: vec![],
        result: set_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_set"),
        doc: "A Set holding these items, duplicates dropped.",
    }
}

/// `to_map()` — a `Map[K, V]`, on a pipeline whose item is a pair.
///
/// **The receiver pattern says "a pair" rather than prose saying it**, so
/// `[1, 2].to_map()` is a unification failure at the method name — "expected
/// `(K, V)`, found `Int`" — and not a row that resolves and then faults. That is
/// the whole of why `TypePattern::Iterable` carries an item pattern at all.
///
/// Duplicate keys resolve last-wins, which is `insert`'s existing rule.
fn seq_to_map() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::Tuple(vec![
            TypePattern::of_kind("K", crate::CapKind::HashStable),
            TypePattern::var("V"),
        ])),
        name: "to_map",
        params: vec![],
        result: map_of_k_v(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_map"),
        doc: "A Map built from (key, value) pairs. Duplicate keys: last wins.",
    }
}

/// `to_counter()` — a `Counter[T]` from `(T, Int)` pairs, taking each pair's
/// count.
///
/// `frequencies()` is the other direction and neither expresses the other:
/// `v.frequencies()` *counts* occurrences of each element, `pairs.to_counter()`
/// *assigns* the count each pair carries. They are the two directions of one type
/// change, so both stay.
fn seq_to_counter() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::Tuple(vec![
            TypePattern::of_kind("T", crate::CapKind::HashStable),
            TypePattern::Scalar(ScalarType::Int),
        ])),
        name: "to_counter",
        params: vec![],
        result: counter_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_counter"),
        doc: "A Counter built from (key, count) pairs. Duplicate keys: last wins.",
    }
}

fn seq_to_deque() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_t(),
        name: "to_deque",
        params: vec![],
        result: deque_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_deque"),
        doc: "A Deque holding these items, in order.",
    }
}

/// `to_min_heap()` — and [`seq_to_max_heap`], its dual.
///
/// The `Ord` bound is on the row for `to_set`'s reason: the heap being built is
/// the *result*, and a heap orders its elements as it pushes them.
fn seq_to_min_heap() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::Ord)),
        name: "to_min_heap",
        params: vec![],
        result: min_heap_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_min_heap"),
        doc: "A MinHeap holding these items.",
    }
}

fn seq_to_max_heap() -> MethodEntry {
    MethodEntry {
        receiver: TypePattern::iterable(TypePattern::of_kind("T", crate::CapKind::Ord)),
        name: "to_max_heap",
        params: vec![],
        result: max_heap_of_t(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_max_heap"),
        doc: "A MaxHeap holding these items.",
    }
}

/// `to_bitset()` — a `BitSet` of `Int` members.
///
/// The receiver says `Int` the way `to_map` says "a pair", so a non-`Int` item is
/// a type error at the method name. `praxis_bitset_insert` still faults on a
/// negative or oversized member, which is a *value* question no type can answer.
fn seq_to_bitset() -> MethodEntry {
    MethodEntry {
        receiver: iterable_of_int_elem(),
        name: "to_bitset",
        params: vec![],
        result: bitset_receiver(),
        purity: Purity::Pure,
        lowering: MethodLowering::Intrinsic("seq_to_bitset"),
        doc: "A BitSet holding these (Int) items. Faults on a negative or oversized member.",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// **Every catalog row describes itself.** The `doc` field is what hover,
    /// completion and signature help put in front of a reader, so a row added
    /// with an empty or placeholder one ships a method the editor can name and
    /// cannot explain — and nothing else in the build would notice, because the
    /// field is a `&'static str` that `""` satisfies.
    ///
    /// The sentence rule is the half that catches a placeholder: `"TODO"` and
    /// `"len"` are both long enough to pass a length floor alone.
    #[test]
    fn every_catalog_row_documents_itself() {
        for e in builtin_catalog().entries() {
            let what = format!("{}.{}/{}", e.receiver, e.name, e.arity());
            assert!(e.doc.len() > 8, "{what} has no real documentation");
            assert!(
                e.doc.ends_with('.') || e.doc.ends_with(')'),
                "{what}'s doc is not a sentence: {:?}",
                e.doc
            );
            // A backtick opens a sentence too: the subscript rows lead with the
            // syntax they are about (`` `v[i]` — the element at `i` ``), which
            // is the clearest thing they could say and not a placeholder.
            assert!(
                e.doc
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_uppercase() || c == '`'),
                "{what}'s doc does not open a sentence: {:?}",
                e.doc
            );
        }
    }

    #[test]
    fn builtin_catalog_has_vec_methods() {
        let cat = builtin_catalog();
        assert!(cat.len() >= 4);
        let vec_pat = vec_of_t();
        let push_hits: Vec<_> = cat.by_receiver_and_name(&vec_pat, "push").collect();
        assert_eq!(push_hits.len(), 1);
        assert_eq!(
            push_hits[0].lowering,
            MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecPush)
        );
    }

    #[test]
    fn builtin_catalog_get_can_fault() {
        let cat = builtin_catalog();
        let vec_pat = vec_of_t();
        let get = cat
            .by_receiver_and_name(&vec_pat, "get")
            .next()
            .expect("vec.get exists");
        assert!(get.can_fault());
        // Derived from the manifest, not restated on the row:
        // `praxis_bitset_insert` raises `InvalidSize` for a member outside
        // `BitIndex`'s range, so `bitset.insert` can fault.
        let bitset_pat = bitset_receiver();
        let insert = cat
            .by_receiver_and_name(&bitset_pat, "insert")
            .next()
            .expect("bitset.insert exists");
        assert!(insert.can_fault());
    }

    /// A keyed collection can be enumerated, `count` has two arities, and every
    /// enumeration answers a `Vec` so §6.3 applies to it — which is what makes
    /// §3.3's `counts.values().count(|n| n >= 2)` spellable.
    ///
    /// The second arity is not a language decision: the catalog's key is
    /// `(receiver, name, arity)`, and `count` is the row that uses it.
    #[test]
    fn a_keyed_collection_enumerates_and_count_has_two_arities() {
        let cat = builtin_catalog();
        let map_pat = map_of_k_v();
        let counter_pat = counter_of_t();

        // Both collections enumerate both ways, and each answers a `Vec`.
        for (pat, what) in [(map_pat.clone(), "Map"), (counter_pat.clone(), "Counter")] {
            for name in ["keys", "values"] {
                let hits: Vec<_> = cat.by_receiver_and_name(&pat, name).collect();
                assert_eq!(hits.len(), 1, "{what}.{name}()");
                assert_eq!(hits[0].arity(), 0, "{what}.{name}() takes no arguments");
                assert!(
                    matches!(
                        hits[0].result,
                        TypePattern::Collection {
                            ctor: CollectionCtor::Vec,
                            ..
                        }
                    ),
                    "{what}.{name}() answers a Vec so every §6.3 combinator applies"
                );
            }
        }

        // A `Counter`'s values are its counts, whatever its key type is (§6.2),
        // where a `Map`'s are its value type. The two are not the same row written
        // twice.
        let counter_values = cat
            .by_receiver_and_name(&counter_pat, "values")
            .next()
            .expect("Counter.values");
        assert_eq!(
            counter_values.result,
            TypePattern::Collection {
                ctor: CollectionCtor::Vec,
                args: vec![TypePattern::Scalar(ScalarType::Int)]
            }
        );
        let map_values = cat
            .by_receiver_and_name(&map_pat, "values")
            .next()
            .expect("Map.values");
        assert_eq!(
            map_values.result,
            TypePattern::Collection {
                ctor: CollectionCtor::Vec,
                args: vec![TypePattern::var("V")]
            }
        );
        // …and `keys()` is the *key* type, which is what makes `m[ks[i]]` legal.
        let map_keys = cat
            .by_receiver_and_name(&map_pat, "keys")
            .next()
            .expect("Map.keys");
        assert_eq!(
            map_keys.result,
            TypePattern::Collection {
                ctor: CollectionCtor::Vec,
                args: vec![TypePattern::var("K")]
            }
        );

        // `count` at two arities — one pair of rows, on the generic receiver
        // every pipeline starts from (ADR-127).
        let arities: Vec<usize> = cat
            .by_receiver_and_name(&iterable_of_t(), "count")
            .map(|e| e.arity())
            .collect();
        assert_eq!(arities.len(), 2, "count has two rows");
        assert!(arities.contains(&0) && arities.contains(&1));
    }

    /// **ADR-127 decision 1.** Every §6.3 combinator is **one** row, on the
    /// generic pipeline receiver.
    ///
    /// The assertion is two-sided: each name is on `Iterable` and on nothing
    /// else, and no `Seq`-receiver row exists anywhere in the table — nothing
    /// produces or consumes a `Seq`, so a row on one would be unreachable.
    #[test]
    fn every_pipeline_combinator_is_one_row_on_the_generic_receiver() {
        let cat = builtin_catalog();
        // The twenty-three fused stages and sinks, six of the eight barriers
        // (`chunks` and `windows` are not listed), and the eight conversions.
        // `count` is here once and checked at both arities by
        // `a_keyed_collection_enumerates_and_count_has_two_arities`.
        //
        // `to_text` is deliberately *not* in this list: it has no generic row,
        // and the reason is written on `vec_to_text` (ADR-144).
        let combinators = [
            "map",
            "filter",
            "filter_map",
            "flat_map",
            "take",
            "skip",
            "take_while",
            "enumerate",
            "zip",
            "fold",
            "reduce",
            "sum",
            "product",
            "count",
            "any",
            "all",
            "find",
            "position",
            "min",
            "max",
            "min_by",
            "max_by",
            "sorted",
            "sorted_by_key",
            "unique",
            "reversed",
            "frequencies",
            "join",
            "to_vec",
            "to_set",
            "to_map",
            "to_counter",
            "to_deque",
            "to_min_heap",
            "to_max_heap",
            "to_bitset",
        ];
        for name in combinators {
            let rows: Vec<_> = cat.entries().iter().filter(|e| e.name == name).collect();
            assert!(!rows.is_empty(), "`{name}` has no row at all");
            // One row per *arity*: `count()` is the element count and
            // `count(pred)` the matching-element count, which the catalog's key
            // allows. Two at one arity would be a duplicated surface.
            let mut generic: Vec<usize> = rows
                .iter()
                .filter(|e| matches!(e.receiver, TypePattern::Iterable { .. }))
                .map(|e| e.arity())
                .collect();
            assert!(!generic.is_empty(), "`{name}` has no generic row");
            let seen = generic.len();
            generic.sort_unstable();
            generic.dedup();
            assert_eq!(
                generic.len(),
                seen,
                "`{name}` has two generic rows at one arity — one receiver \
                 getting a feature ten should have"
            );
            // A row that shares the *name* must be on a receiver the generic one
            // does not accept, which the builder's collision check enforces and
            // this restates from the reader's side. `Grid[T].find(value)` is the
            // live example: §6.4's "where is this cell" is a different question
            // from §6.3's "which element matches", and they can coexist because a
            // `Grid` is not one of the ten.
            for row in rows {
                assert!(
                    matches!(row.receiver, TypePattern::Iterable { .. })
                        || !crate::is_pipeline_receiver(&row.receiver),
                    "`{name}` also has a row on {}, which the generic row \
                     accepts — both would match, and which one a call resolves \
                     to would be insertion order",
                    row.receiver
                );
            }
        }

        // `Grid[T].map` is the row §6.4 still owes, and the *absence* of a
        // generic row claiming the name is what leaves room for it. The builder's
        // collision check is the other half; this is the half that says the
        // exclusion was deliberate.
        assert!(
            !crate::PIPELINE_RECEIVERS.contains(&CollectionCtor::Grid),
            "a generic `map` would claim §6.4's name and answer a `Vec`"
        );

        // Nothing is registered on a `Seq`, which has no values.
        for e in cat.entries() {
            assert!(
                !matches!(
                    e.receiver,
                    TypePattern::Collection {
                        ctor: CollectionCtor::Seq,
                        ..
                    }
                ),
                "`{}` is still on a `Seq`, which has no values",
                e.name
            );
        }
    }

    /// **ADR-127 decision 4.** There is a conversion for every collection with a
    /// constructor, and exactly one collection with none.
    ///
    /// The set is closed at that boundary on purpose: the ask named
    /// `Set`/`Map`/`Counter`, and leaving the other four out is what would create
    /// the asymmetry decision 6 then has to defend — `deque.filter(p)` answering
    /// a `Vec` with no way back to a `Deque`. `Grid` is the exception because a
    /// grid needs a width and a flat item sequence does not carry one.
    #[test]
    fn a_conversion_exists_for_every_collection_that_can_be_constructed() {
        let cat = builtin_catalog();
        for (name, ctor) in [
            ("to_vec", CollectionCtor::Vec),
            ("to_set", CollectionCtor::Set),
            ("to_map", CollectionCtor::Map),
            ("to_counter", CollectionCtor::Counter),
            ("to_deque", CollectionCtor::Deque),
            ("to_min_heap", CollectionCtor::MinHeap),
            ("to_max_heap", CollectionCtor::MaxHeap),
            ("to_bitset", CollectionCtor::BitSet),
        ] {
            let row = cat
                .entries()
                .iter()
                .find(|e| e.name == name)
                .unwrap_or_else(|| panic!("`{name}` has no row"));
            assert_eq!(row.arity(), 0, "`{name}` takes no arguments");
            let built = match &row.result {
                TypePattern::Collection { ctor, .. } => *ctor,
                other => panic!("`{name}` answers {other}, not a collection"),
            };
            assert_eq!(built, ctor, "`{name}` builds the collection it names");
        }
        assert!(
            cat.entries().iter().all(|e| e.name != "to_grid"),
            "a grid needs a width, and an item sequence does not carry one"
        );

        // **The pair shape is in the receiver, not in prose.** That is what makes
        // `[1, 2].to_map()` "expected `(K, V)`, found `Int`" at the method name
        // rather than a row that resolves and then faults at runtime.
        for name in ["to_map", "to_counter"] {
            let row = cat.entries().iter().find(|e| e.name == name).unwrap();
            let TypePattern::Iterable { item } = &row.receiver else {
                panic!("`{name}` is not on the generic receiver")
            };
            assert!(
                matches!(**item, TypePattern::Tuple(ref els) if els.len() == 2),
                "`{name}` accepts a `Map` or a `Counter` by saying its item is a pair"
            );
        }
    }

    /// The subscript rows are the closed set the language documents, and their
    /// names cannot be written in source.
    ///
    /// Two properties in one test because they are both about the same decision.
    /// Which collections index is a *language* answer (§4.7/§6.2/§6.4), so a row
    /// added or dropped by accident should fail here rather than surface as a
    /// program that mysteriously compiles. And a row whose name is an identifier
    /// would be callable as `m.foo(k)`, which no design section describes.
    #[test]
    fn the_subscript_rows_are_a_closed_set_no_program_can_name() {
        let cat = builtin_catalog();
        let of = |ctor: CollectionCtor, args: usize| TypePattern::Collection {
            ctor,
            args: (0..args).map(|_| TypePattern::var("T")).collect(),
        };
        let map_pat = map_of_k_v();

        // Six read. `Text` is a scalar receiver, so it is spelled differently.
        for (pat, indices, what) in [
            (of(CollectionCtor::Vec, 1), 1, "Vec"),
            (of(CollectionCtor::Deque, 1), 1, "Deque"),
            (map_pat.clone(), 1, "Map"),
            (of(CollectionCtor::Counter, 1), 1, "Counter"),
            (of(CollectionCtor::Grid, 1), 2, "Grid"),
            (text_receiver(), 1, "Text"),
        ] {
            let hits: Vec<_> = cat
                .by_receiver_and_name(&pat, crate::catalog::INDEX_READ)
                .collect();
            assert_eq!(hits.len(), 1, "{what} reads through exactly one row");
            assert_eq!(hits[0].arity(), indices, "{what} indexes at {indices}");
        }

        // Five store — every reader but `Text`. The asymmetry the `Y020` message
        // has to describe is now `Text`'s alone: it reads a `Char` out and is
        // immutable (§4.3), so there is nothing to write back through.
        for (pat, args, what) in [
            (of(CollectionCtor::Vec, 1), 2, "Vec"),
            (of(CollectionCtor::Deque, 1), 2, "Deque"),
            (map_pat.clone(), 2, "Map"),
            (of(CollectionCtor::Counter, 1), 2, "Counter"),
            (of(CollectionCtor::Grid, 1), 3, "Grid"),
        ] {
            let hits: Vec<_> = cat
                .by_receiver_and_name(&pat, crate::catalog::INDEX_STORE)
                .collect();
            assert_eq!(hits.len(), 1, "{what} stores through exactly one row");
            assert_eq!(
                hits[0].arity(),
                args,
                "{what}'s store takes its indices and then the value"
            );
        }

        // Nothing else has either row.
        for (pat, what) in [
            (of(CollectionCtor::Set, 1), "Set"),
            (of(CollectionCtor::MinHeap, 1), "MinHeap"),
            (of(CollectionCtor::MaxHeap, 1), "MaxHeap"),
            (of(CollectionCtor::BitSet, 0), "BitSet"),
        ] {
            for name in [crate::catalog::INDEX_READ, crate::catalog::INDEX_STORE] {
                assert_eq!(
                    cat.by_receiver_and_name(&pat, name).count(),
                    0,
                    "{what} has no `{name}`"
                );
            }
        }
        assert_eq!(
            cat.by_receiver_and_name(&text_receiver(), crate::catalog::INDEX_STORE)
                .count(),
            0,
            "a `Text` is immutable: it reads through a subscript and has \
             no element store"
        );

        // A `Vec`/`Deque` store is a **replacement**, and the wrapper it names is
        // the assertion of that: `praxis_vec_set` faults on an index the vector
        // does not hold, where `praxis_vec_push` would have grown it. A row that
        // pointed at the push would spell `v[i] = x` and mean `v.push(x)`.
        for (pat, push, what) in [
            (of(CollectionCtor::Vec, 1), "push", "Vec"),
            (of(CollectionCtor::Deque, 1), "push_back", "Deque"),
        ] {
            let store = cat
                .by_receiver_and_name(&pat, crate::catalog::INDEX_STORE)
                .next()
                .unwrap_or_else(|| panic!("{what}'s store"));
            let appender = cat
                .by_receiver_and_name(&pat, push)
                .next()
                .unwrap_or_else(|| panic!("{what}.{push}"));
            assert_ne!(
                store.lowering, appender.lowering,
                "{what}'s store replaces; `{push}` appends"
            );
            assert!(
                store.can_fault(),
                "{what}'s store reports an index it does not hold"
            );
        }

        // A `Map`'s two reads are two *different* wrappers: §4.7 gives `.get` and
        // `map[key]` different answers about an absent key, so pointing both rows
        // at one wrapper would take the choice away from the user.
        let get = cat
            .by_receiver_and_name(&map_pat, "get")
            .next()
            .expect("Map.get");
        let index = cat
            .by_receiver_and_name(&map_pat, crate::catalog::INDEX_READ)
            .next()
            .expect("Map's subscript");
        assert_ne!(get.lowering, index.lowering);
        assert!(
            index.can_fault() && !get.can_fault(),
            "indexing faults where `.get` answers"
        );

        // The two **updating** stores: `Map` only, at the same arity as its
        // plain store, and pointing at wrappers of their own — a row that
        // reused `MapInsert` would spell `min=` and mean `=`.
        let map_int_value = map_of_k_int_value();
        let plain_store = cat
            .by_receiver_and_name(&map_pat, crate::catalog::INDEX_STORE)
            .next()
            .expect("Map's store")
            .lowering
            .clone();
        for (name, what) in [
            (crate::catalog::INDEX_STORE_MIN, "min="),
            (crate::catalog::INDEX_STORE_MAX, "max="),
        ] {
            let hits: Vec<_> = cat.by_receiver_and_name(&map_int_value, name).collect();
            assert_eq!(hits.len(), 1, "`{what}` is one row on a Map");
            assert_eq!(hits[0].arity(), 2, "`{what}` takes its key and its value");
            assert_ne!(
                hits[0].lowering, plain_store,
                "`{what}` must not lower to the plain store"
            );
            // …and no other receiver has one, including the collections that do
            // have a plain store.
            for (pat, other) in [
                (of(CollectionCtor::Counter, 1), "Counter"),
                (of(CollectionCtor::Grid, 1), "Grid"),
                (of(CollectionCtor::Vec, 1), "Vec"),
                (of(CollectionCtor::Set, 1), "Set"),
            ] {
                assert_eq!(
                    cat.by_receiver_and_name(&pat, name).count(),
                    0,
                    "{other} has no `{what}`"
                );
            }
        }
        // The two are different rows from each other, or one of them computes
        // the other's answer.
        assert_ne!(
            cat.by_receiver_and_name(&map_int_value, crate::catalog::INDEX_STORE_MIN)
                .next()
                .expect("min=")
                .lowering,
            cat.by_receiver_and_name(&map_int_value, crate::catalog::INDEX_STORE_MAX)
                .next()
                .expect("max=")
                .lowering,
        );

        // No subscript name is an identifier, so the subscript grammar is their
        // only caller: the parser accepts only an `Ident` after `.`.
        for name in [
            crate::catalog::INDEX_READ,
            crate::catalog::INDEX_STORE,
            crate::catalog::INDEX_STORE_MIN,
            crate::catalog::INDEX_STORE_MAX,
        ] {
            assert!(
                !name
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_alphabetic() || c == '_'),
                "`{name}` must not be spellable as a method name"
            );
        }
    }

    /// Closed-catalog check: every §6.1 collection has at least the
    /// `len`/`is_empty` pair, plus its type-specific methods. This guards against
    /// an accidental catalog gap where a collection ships without its methods.
    #[test]
    fn catalog_covers_every_collection_kind() {
        let cat = builtin_catalog();
        // Each collection must have a `len` and `is_empty` method (or the
        // type-specific equivalent — heaps have len/is_empty; bitset has them too).
        for (ctor, name) in [
            (CollectionCtor::Vec, "Vec"),
            (CollectionCtor::Deque, "Deque"),
            (CollectionCtor::Set, "Set"),
            (CollectionCtor::Counter, "Counter"),
            (CollectionCtor::MinHeap, "MinHeap"),
            (CollectionCtor::MaxHeap, "MaxHeap"),
            (CollectionCtor::BitSet, "BitSet"),
        ] {
            let args: Vec<TypePattern> = match ctor.arity() {
                0 => Vec::new(),
                n => (0..n).map(|_| TypePattern::var("T")).collect(),
            };
            let pat = TypePattern::Collection { ctor, args };
            let len = cat.by_receiver_and_name(&pat, "len").count();
            let is_empty = cat.by_receiver_and_name(&pat, "is_empty").count();
            assert!(len >= 1, "{name} missing len method");
            assert!(is_empty >= 1, "{name} missing is_empty method");
        }
        // Map has two type args with distinct var names (K, V), so the loop's
        // `T`-repeated shape above does not describe it.
        let map_pat = map_of_k_v();
        assert!(cat.by_receiver_and_name(&map_pat, "len").count() >= 1);
        assert!(cat.by_receiver_and_name(&map_pat, "is_empty").count() >= 1);
        // Grid has width/height (its dimension methods).
        let grid_pat = grid_of_t();
        assert!(cat.by_receiver_and_name(&grid_pat, "width").count() >= 1);
        assert!(cat.by_receiver_and_name(&grid_pat, "neighbors4").count() >= 1);
    }

    /// **The neighbourhood record's field order is written down twice**, and
    /// the runtime holds the other copy.
    ///
    /// A field read compiles to a slot index taken from *this* list, so what
    /// this pins is the sequence itself: row order, spelling and arity.
    /// `praxis_runtime::records::tests::around_schemas_match_the_catalog` is
    /// the far end of the same assertion — it can see both lists at once, and
    /// this one is what tells an author editing the catalog that the order is
    /// not theirs alone to change.
    ///
    /// Every field is an `Option`: `None` is a direction that leaves the grid,
    /// which is the one thing `neighbors4`'s clipped `Vec` cannot say.
    #[test]
    fn the_neighbourhood_records_field_order_is_reading_order() {
        let cat = builtin_catalog();
        let grid_pat = grid_of_t();
        for (method, expected) in [
            ("around4", &["up", "left", "right", "down"][..]),
            (
                "around8",
                &[
                    "up_left",
                    "up",
                    "up_right",
                    "left",
                    "right",
                    "down_left",
                    "down",
                    "down_right",
                ][..],
            ),
        ] {
            let rows: Vec<_> = cat.by_receiver_and_name(&grid_pat, method).collect();
            assert_eq!(rows.len(), 1, "`Grid[T].{method}` is one row");
            let TypePattern::Record { name, fields } = &rows[0].result else {
                panic!("`Grid[T].{method}` answers a nominal record");
            };
            assert_eq!(
                *name,
                if method == "around4" {
                    "Around4"
                } else {
                    "Around8"
                }
            );
            let names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
            assert_eq!(names, expected, "`{name}`'s fields are its slot order");
            for (fname, fpat) in fields {
                assert_eq!(
                    *fpat,
                    TypePattern::Option(Box::new(point_pattern())),
                    "`{name}.{fname}` is an Option[(Int, Int)]"
                );
            }
            // The display is the name alone — a nominal record *is* its name,
            // and that is what hover and completion read.
            assert_eq!(rows[0].result.to_string(), *name);
        }
    }

    /// **`neighbors4`/`neighbors8` are unchanged**, and that is a decision
    /// rather than an omission.
    ///
    /// The graph walks take a neighbours closure typed `(T) -> Vec[T]` —
    /// `bfs(start, |p| g.neighbors4(p))` is ADR-060's own spelling, and
    /// `docs/book/examples/grid-graphs/neighbours-must-be-a-vec.px` gates the
    /// refusal when it is not a `Vec`. Retyping these rows to the record would
    /// break every walk in the book; the record is an addition beside them.
    #[test]
    fn the_clipped_vec_rows_still_answer_a_vec() {
        let cat = builtin_catalog();
        let grid_pat = grid_of_t();
        let vec_of_points = TypePattern::Collection {
            ctor: CollectionCtor::Vec,
            args: vec![point_pattern()],
        };
        for method in ["neighbors4", "neighbors8"] {
            let rows: Vec<_> = cat.by_receiver_and_name(&grid_pat, method).collect();
            assert_eq!(rows.len(), 1);
            assert_eq!(
                rows[0].result, vec_of_points,
                "`{method}` answers the clipped Vec a graph walk consumes"
            );
        }
    }

    /// The four counts: two compare a value, two run a closure, all four answer
    /// an `Int`, and only the closure pair can fault.
    ///
    /// The effect is the assertion. `MethodEntry::can_fault` reads the manifest,
    /// and a `_where` row marked `Allocates` would emit no `CheckFault` — a
    /// predicate that divided by zero would set a fault nothing reads and hand
    /// the program a Unit sentinel typed as an `Int` (ADR-088). The
    /// value-comparing pair is the contrast: it calls nothing, so a declared
    /// fault there would be a dead check after every call.
    #[test]
    fn only_the_counts_that_run_a_closure_can_fault() {
        let cat = builtin_catalog();
        let grid_pat = grid_of_t();
        let predicate = TypePattern::Function {
            params: vec![TypePattern::var("T")],
            result: Box::new(TypePattern::Scalar(ScalarType::Bool)),
        };
        for (method, second, can_fault) in [
            ("count4", TypePattern::var("T"), false),
            ("count8", TypePattern::var("T"), false),
            ("count4_where", predicate.clone(), true),
            ("count8_where", predicate, true),
        ] {
            let rows: Vec<_> = cat.by_receiver_and_name(&grid_pat, method).collect();
            assert_eq!(rows.len(), 1, "`Grid[T].{method}` is one row");
            let row = rows[0];
            assert_eq!(
                row.params,
                vec![point_pattern(), second],
                "`{method}` takes the position and then what to count"
            );
            assert_eq!(row.result, TypePattern::Scalar(ScalarType::Int));
            assert_eq!(
                row.can_fault(),
                can_fault,
                "`{method}`: only a row that calls back into the program \
                 needs a fault check after it"
            );
        }
    }

    /// **A standing invariant.** Every catalog row that lowers to a runtime
    /// wrapper declares a `Unit` result if and only if that wrapper's manifest
    /// return is `AbiRet::GcUnit`.
    ///
    /// A value whose *static* type is `V` and whose *runtime descriptor* is
    /// `Unit` is the defect this rules out. The **absence of a third `AbiRet`
    /// arm** is the load-bearing part rather than this test: "may be Unit, may
    /// be a value" cannot be spelled, so an author reaching for a Unit sentinel
    /// has to write either `GcUnit` — which this test refuses beside a `V`
    /// result — or `Gc`, which is then a claim the wrapper must honour and which
    /// `absent_map_get_does_not_return_an_untyped_unit_sentinel` checks in the
    /// runtime.
    ///
    /// **What this does not prove**, stated plainly: the manifest row is
    /// hand-asserted, at exactly the trust level `Effect` already is, so what
    /// this catches is a *catalog row disagreeing with its manifest row*, not a
    /// manifest row that lies about its wrapper. Setting `map_get`'s result to
    /// `TypePattern::var("V")` and leaving `MapGet` at `-> Gc` passes here, and
    /// is caught in `praxis-runtime` instead.
    ///
    /// The sweep runs over *every* such row, faulting ones included. A faulting
    /// wrapper's Unit is the ABI's universal unwind answer, which is a different
    /// thing from its declared result — so the biconditional holds there too,
    /// and restricting the sweep would only make it weaker.
    #[test]
    fn a_non_faulting_row_with_a_value_result_cannot_answer_the_unit_sentinel() {
        let cat = builtin_catalog();
        let mut checked = 0;
        for entry in cat.entries() {
            // An intrinsic has no wrapper: it expands to MIR instructions whose
            // effects are their own (`MethodEntry::can_fault` says the same).
            let MethodLowering::RuntimeSymbol(sym) = entry.lowering else {
                continue;
            };
            checked += 1;
            let ret = sym.sig().ret;
            let result_is_unit = entry.result == TypePattern::Unit;
            match (ret, result_is_unit) {
                (abi::AbiRet::GcUnit, true) | (abi::AbiRet::Gc, false) => {}
                _ => panic!(
                    "{}.{} declares `{}` and lowers to `{}`, whose manifest return is \
                     {ret:?}. A wrapper answers either a value (`AbiRet::Gc`, \
                     non-`Unit` result) or nothing (`AbiRet::GcUnit`, `Unit` \
                     result); an answer that is sometimes absent is spelled \
                     `Option[T]`, never a Unit sentinel under a value type.",
                    entry.receiver,
                    entry.name,
                    entry.result,
                    sym.name(),
                ),
            }
        }
        // A guard against the sweep silently covering nothing — every row being
        // faulting, or `entries()` being empty, would otherwise pass.
        assert!(
            checked >= 40,
            "expected the sweep to reach most of the catalog, it reached {checked} rows"
        );
    }

    /// The sweep above skips [`MethodLowering::ScalarPrimitive`] rows, because
    /// its biconditional is about wrappers that answer a `GcRef` and those
    /// answer the scalar channel. This is their half of it (ADR-118 decision 6).
    ///
    /// **Skipping a row is how a sweep quietly stops covering anything**, so
    /// the arm that made them skippable owes this test the day it is added.
    /// What it rules out is the state that would matter: a row marked
    /// `ScalarPrimitive` while its wrapper still returns a `GcRef`, which MIR
    /// would take at its word and put a raw integer into a rootable slot. The
    /// complementary refusal is in `praxis-mir`'s `lower_scalar_primitive`,
    /// whose fallthrough is an ICE naming the symbol: a `-> RawI64` wrapper
    /// reachable from a method call with no instruction to produce it is a
    /// compiler bug, not a program's.
    #[test]
    fn a_scalar_primitive_row_answers_the_scalar_channel_and_a_scalar_type() {
        let cat = builtin_catalog();
        let mut rows = 0;
        for entry in cat.entries() {
            let MethodLowering::ScalarPrimitive(sym) = entry.lowering else {
                continue;
            };
            rows += 1;
            assert_eq!(
                sym.sig().ret,
                abi::AbiRet::RawI64,
                "{}.{} lowers as a scalar primitive, so `{}` must answer the \
                 scalar channel; a `-> Gc` row here is a box the caller would \
                 have to unwrap again, which is the whole thing this arm exists \
                 to remove",
                entry.receiver,
                entry.name,
                sym.name(),
            );
            assert!(
                matches!(entry.result, TypePattern::Scalar(_)),
                "{}.{} answers `{}`, which the scalar channel cannot carry",
                entry.receiver,
                entry.name,
                entry.result,
            );
            // A scalar primitive is not a safepoint in MIR, so a row that
            // allocates would be one the collector is never shown a frame at.
            assert!(
                !entry.allocates(),
                "{}.{} allocates, so it cannot be a non-safepoint instruction",
                entry.receiver,
                entry.name,
            );
        }
        assert_eq!(
            rows, 1,
            "`BitSet.contains` is the only scalar-primitive row today; a second \
             one wants an arm in `praxis-mir`'s `lower_scalar_primitive` before \
             this number moves"
        );
    }

    /// `Map.get` and `Grid.find` answer an `Option`, spelled out by name so an
    /// edit that puts either back to a bare value type fails here as well as
    /// through the sweep above.
    #[test]
    fn map_get_and_grid_find_answer_an_option() {
        let cat = builtin_catalog();
        let map_pat = map_of_k_v();
        let get = cat
            .by_receiver_and_name(&map_pat, "get")
            .next()
            .expect("map.get exists");
        assert_eq!(
            get.result,
            TypePattern::Option(Box::new(TypePattern::var("V"))),
            "§5.7 writes `Map[K,V].get(K) -> Option[V]`"
        );

        let grid_pat = grid_of_t();
        let find = cat
            .by_receiver_and_name(&grid_pat, "find")
            .next()
            .expect("grid.find exists");
        assert_eq!(find.result, TypePattern::Option(Box::new(point_pattern())));

        // …and `Counter.get` keeps its zero default, which is not absence at
        // all: §6.2 says a counter's absent values *read as zero*.
        let counter_pat = counter_of_t();
        let counter_get = cat
            .by_receiver_and_name(&counter_pat, "get")
            .next()
            .expect("counter.get exists");
        assert_eq!(
            counter_get.result,
            TypePattern::Scalar(ScalarType::Int),
            "§6.2: a Counter's absent values read as zero, deliberately"
        );
    }

    /// **ADR-136, the catalog half.** `Text.int()` and `Text.float()` exist and
    /// each answers an `Option`.
    ///
    /// `Y001`'s help on the most common mistake in a puzzle program points at
    /// `.int()`, so the row has to be here. Pure data, so this goes red on the
    /// catalog edit alone.
    ///
    /// The two are asserted together because the pair is the decision: a
    /// language with a text-to-`Int` conversion and no text-to-`Float` one is a
    /// language where "read a number out of text" has a different answer per
    /// type, which is the asymmetry `parse(t, int)`/`parse(t, float)` does not
    /// have.
    #[test]
    fn text_int_and_float_answer_options() {
        let cat = builtin_catalog();
        for (name, scalar) in [("int", ScalarType::Int), ("float", ScalarType::Float)] {
            let entry = cat
                .by_receiver_and_name(&TypePattern::Scalar(ScalarType::Text), name)
                .next()
                .unwrap_or_else(|| panic!("`Text.{name}()` exists"));
            assert_eq!(
                entry.result,
                TypePattern::Option(Box::new(TypePattern::Scalar(scalar))),
                "a text that is not a number is absence, not a fault (\u{00a7}4.7)"
            );
            assert!(entry.params.is_empty(), "`{name}` takes no arguments");
        }
    }

    /// **ADR-086, the catalog half.** `t[i]` and `t.get(i)` answer a `Char`.
    ///
    /// This is pure data, so it goes red on the catalog edit alone and stays red
    /// whatever the runtime does — which is what makes it the *catalog's* gate.
    /// Its runtime twin is `text_get_answers_a_char_object` in
    /// `praxis-runtime`'s `abi.rs`, and neither can see the other's half.
    #[test]
    fn the_two_text_reads_answer_a_char() {
        let cat = builtin_catalog();
        let text = text_receiver();

        for name in [crate::catalog::INDEX_READ, "get"] {
            let row = cat
                .by_receiver_and_name(&text, name)
                .next()
                .unwrap_or_else(|| panic!("Text.{name} exists"));
            assert_eq!(
                row.result,
                TypePattern::Scalar(ScalarType::Char),
                "ADR-086: `Text.{name}` answers a Char, not the char's scalar value"
            );
            // The two spellings are one answer, so they are one wrapper — unlike
            // `Map`, whose two reads are two wrappers on purpose (§4.7).
            assert_eq!(
                row.lowering,
                MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::TextGet),
                "`Text.{name}` lowers through the one text read"
            );
        }
    }

    /// **ADR-086, the conversion pair.** A one-way conversion would make
    /// `Grid[Char]`, `Vec[Char]` and `Map[Char, _]` write-only from the
    /// language's side, so the pair is asserted as a pair — the same shape
    /// §4.12 gives `Float.to_int`/`Int.to_float`.
    #[test]
    fn char_and_int_convert_both_ways() {
        let cat = builtin_catalog();

        let to_int = cat
            .by_receiver_and_name(&TypePattern::Scalar(ScalarType::Char), "to_int")
            .next()
            .expect("Char.to_int exists");
        assert_eq!(to_int.result, TypePattern::Scalar(ScalarType::Int));
        assert_eq!(to_int.purity, Purity::Pure);

        let to_char = cat
            .by_receiver_and_name(&TypePattern::Scalar(ScalarType::Int), "to_char")
            .next()
            .expect("Int.to_char exists");
        assert_eq!(to_char.result, TypePattern::Scalar(ScalarType::Char));

        // The narrowing direction is the one that can fail — `Int.to_char` is to
        // `Char.to_int` what `Float.to_int` is to `Int.to_float`. The manifest is
        // where that is enforced, so read it there rather than restating it.
        assert!(
            to_char.can_fault(),
            "not every Int is a Unicode scalar value, so the narrowing faults"
        );
        assert!(
            !to_int.can_fault(),
            "every Unicode scalar value fits an Int, so the widening cannot"
        );
    }

    /// **ADR-143.** The `to_text` family is `Int`, `Float` and `Char`, and it is
    /// closed at three.
    ///
    /// The closure is the half worth asserting: a reader arriving with a
    /// `Bool.to_text()` or a universal one should meet a failing test rather
    /// than an empty space. Adding either is a decision, not a completion.
    #[test]
    fn the_to_text_family_is_int_float_and_char() {
        let cat = builtin_catalog();
        for scalar in [ScalarType::Int, ScalarType::Float, ScalarType::Char] {
            let receiver = TypePattern::Scalar(scalar);
            let row = cat
                .by_receiver_and_name(&receiver, "to_text")
                .next()
                .unwrap_or_else(|| panic!("{scalar:?}.to_text exists"));
            assert_eq!(row.result, TypePattern::Scalar(ScalarType::Text));
            assert_eq!(row.purity, Purity::Pure);
            assert!(row.allocates(), "{scalar:?}.to_text answers a fresh Text");
            // Each renders a payload that was validated at construction, so
            // there is nothing left to fault on — and a faulting row would put a
            // `CheckFault` after every call site that can never fire.
            assert!(!row.can_fault(), "{scalar:?}.to_text cannot fail");
        }
        for scalar in [ScalarType::Bool, ScalarType::Byte, ScalarType::Text] {
            let receiver = TypePattern::Scalar(scalar);
            assert_eq!(
                cat.by_receiver_and_name(&receiver, "to_text").count(),
                0,
                "the `to_text` family is three scalars; {scalar:?} is not one of \
                 them, and a universal `to_text` is §8.1 interpolation's question"
            );
        }
    }

    /// **ADR-144.** `join` is one row on the generic receiver bounded to `Text`
    /// items; the sequence-of-`Char` case is `Vec[Char].to_text()` under a
    /// different name.
    ///
    /// The two negatives are the point. A concrete `Vec[Char].join/1` beside the
    /// generic row is refused by `finish` as `AmbiguousWithIterable`, and a
    /// second `Iterable` row differing only in its item bound would resolve by
    /// insertion order — so the surface has to be one `join` plus a different
    /// name.
    #[test]
    fn join_is_one_row_and_a_sequence_of_chars_has_its_own_name() {
        let cat = builtin_catalog();

        let join: Vec<_> = cat.entries().iter().filter(|e| e.name == "join").collect();
        assert_eq!(join.len(), 1, "`join` is one row");
        assert_eq!(join[0].receiver, iterable_of_text_elem());
        assert_eq!(join[0].params, vec![TypePattern::Scalar(ScalarType::Text)]);
        assert_eq!(join[0].result, TypePattern::Scalar(ScalarType::Text));

        // No `to_text` row generalizes. It cannot: `Text` is one of the ten
        // pipeline receivers, so an `Iterable.to_text/0` would shadow every
        // scalar row of ADR-143's family at once.
        assert!(
            !cat.entries()
                .iter()
                .any(|e| e.name == "to_text" && matches!(e.receiver, TypePattern::Iterable { .. })),
            "an `Iterable.to_text` would collide with the scalar `to_text` rows"
        );
        let chars_pat = vec_of_char();
        let chars = cat
            .by_receiver_and_name(&chars_pat, "to_text")
            .next()
            .expect("Vec[Char].to_text exists");
        assert_eq!(chars.result, TypePattern::Scalar(ScalarType::Text));
        assert!(chars.params.is_empty());
    }

    /// **ADR-145.** `reversed` carries no capability bound, and that is the
    /// row's claim rather than an oversight.
    ///
    /// `sorted` needs `Ord` because it calls `compare`, `unique` needs
    /// `HashStable` because it calls `hash` and `equals`. Reversal calls
    /// nothing, so a `Vec` of closures reverses — and a later edit that "tidies
    /// up" by giving it a bound to match its neighbours would take that away
    /// with no wrapper behaviour to justify it.
    #[test]
    fn reversed_is_a_barrier_with_no_bound_on_its_element() {
        let cat = builtin_catalog();
        let receiver = iterable_of_t();
        let row = cat
            .by_receiver_and_name(&receiver, "reversed")
            .next()
            .expect("Iterable.reversed exists");
        assert_eq!(row.result, vec_of_t());
        assert_eq!(row.purity, Purity::Pure);
        assert!(row.bounds().is_empty(), "reversal reads no callback");
        assert!(
            !row.can_fault(),
            "there is no element `reversed` can be handed that it cannot reverse"
        );
        assert!(
            matches!(
                row.lowering,
                MethodLowering::RuntimeSymbol(abi::RuntimeSymbol::VecReversed)
            ),
            "a barrier is a runtime call, not a fused stage: reversal cannot \
             answer its first element until it has seen the last"
        );
    }

    /// **ADR-149.** The two groupings are barriers that answer `Vec[Vec[T]]`,
    /// carry no capability bound, and fault.
    ///
    /// Three claims, each of which a later edit could undo for a plausible
    /// reason, so each is asserted rather than described:
    ///
    /// * **The nesting.** A row declaring `Vec[T]` would flatten the answer and
    ///   nothing in the row's own text would look wrong.
    /// * **The absent bound.** `sorted` and `unique` sit beside these with one
    ///   each, and a tidying edit that gave these one to match would take away
    ///   the `Vec` of closures that groups today — with no wrapper behaviour to
    ///   justify it, because a grouping calls no descriptor callback.
    /// * **The fault.** It is the one place these differ from `reversed`, and it
    ///   is what makes `chunks(0)` observable at all: MIR emits a `CheckFault`
    ///   after a call only when the wrapper declares one, so an `Allocates` row
    ///   here would set `InvalidSize` into a context nothing reads and hand the
    ///   program a Unit sentinel typed as a `Vec[Vec[T]]` (ADR-088).
    #[test]
    fn a_grouping_answers_a_nested_vec_with_no_bound_and_can_fault() {
        let cat = builtin_catalog();
        let receiver = iterable_of_t();
        for (name, symbol) in [
            ("chunks", abi::RuntimeSymbol::VecChunks),
            ("windows", abi::RuntimeSymbol::VecWindows),
        ] {
            let row = cat
                .by_receiver_and_name(&receiver, name)
                .next()
                .unwrap_or_else(|| panic!("Iterable.{name} exists"));
            assert_eq!(
                row.result,
                vec_of_vec_of_t(),
                "`{name}` groups without flattening"
            );
            assert_eq!(row.params, vec![TypePattern::Scalar(ScalarType::Int)]);
            assert_eq!(row.purity, Purity::Pure);
            assert!(
                row.bounds().is_empty(),
                "a grouping reads no descriptor callback ({name})"
            );
            assert!(
                row.can_fault(),
                "`{name}(0)` names no run, and the program has to be able to see that"
            );
            assert!(
                matches!(row.lowering, MethodLowering::RuntimeSymbol(s) if s == symbol),
                "a grouping is a barrier: it cannot answer its first group from \
                 one element ({name})"
            );
        }
    }

    /// §4.12's overflow alternatives are three modes over three operators, and
    /// the table says exactly that — no more and no fewer.
    ///
    /// This is the enforcement of a rule §4.12 states and nothing else should
    /// restate. It asserts the closures as well as the members, because the
    /// closures are the half a reader is most likely to undo by adding the
    /// "obviously missing" `checked_div` — which would contradict §4.12's own
    /// next sentence, "Division by zero always faults".
    ///
    /// It pins the *shape* of the family, not the behaviour of any row: the
    /// gates for the behaviour are in `jit.rs`, at the boundaries where the
    /// ordinary operator faults.
    #[test]
    fn the_overflow_alternative_family_is_three_modes_over_three_operators() {
        let cat = builtin_catalog();
        let int = TypePattern::Scalar(ScalarType::Int);

        for mode in ["wrapping", "saturating", "checked"] {
            for op in ["add", "sub", "mul"] {
                let name = format!("{mode}_{op}");
                let row = cat
                    .by_receiver_and_name(&int, &name)
                    .next()
                    .unwrap_or_else(|| panic!("§4.12's family includes `Int.{name}`"));
                assert_eq!(row.params, vec![TypePattern::Scalar(ScalarType::Int)]);
                // None of the nine may fault: that is what an *alternative* to a
                // faulting operator means, and ADR-088's verifier rule turns it
                // into "no `CheckFault` follows the call".
                assert!(!row.can_fault(), "`{name}` is an alternative to faulting");

                let want = if mode == "checked" {
                    TypePattern::Option(Box::new(TypePattern::Scalar(ScalarType::Int)))
                } else {
                    TypePattern::Scalar(ScalarType::Int)
                };
                assert_eq!(row.result, want, "`{name}`'s result");
            }
        }

        // The two closures §4.12 draws, asserted as absences.
        for absent in [
            "wrapping_div",
            "saturating_div",
            "checked_div",
            "wrapping_rem",
            "checked_rem",
            "wrapping_neg",
            "checked_neg",
            "saturating_abs",
        ] {
            assert!(
                cat.by_receiver_and_name(&int, absent).next().is_none(),
                "§4.12 closes the family before `{absent}`: division's escape \
                 hatch is closed by \"Division by zero always faults\", and \
                 `_neg`/`_abs` are spelled with `0.wrapping_sub(x)`"
            );
        }
    }
}