jetro-core 0.5.12

jetro-core: parser, compiler, and VM for the Jetro JSON query language
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
//! Per-method builtin definitions implementing the `Builtin` trait.
//!
//! One zero-sized struct per `BuiltinMethod` variant. Each struct's `impl Builtin` block
//! is the single source of truth for that method's identity, spec, and (future) runtime
//! behaviour. As migration proceeds, more methods move from the legacy `BuiltinMethod::spec()`
//! match into this file (or category-split children).

use super::{
    builtin::Builtin, BuiltinCancelGroup, BuiltinCancelSide, BuiltinCancellation,
    BuiltinCardinality, BuiltinCategory, BuiltinColumnarStage, BuiltinDemandLaw,
    BuiltinKeyedReducer, BuiltinMethod, BuiltinNumericReducer, BuiltinPipelineLowering,
    BuiltinPipelineMaterialization, BuiltinPipelineOrderEffect, BuiltinPipelineShape,
    BuiltinSelectionPosition, BuiltinSpec, BuiltinStageMerge, BuiltinStructural, BuiltinViewStage,
};

// ── Helpers shared across reducer family ─────────────────────────────────────

/// Numeric reducer (sum/avg/min/max) skeleton; same demand/lowering across the four.
#[inline]
fn numeric_reducer_spec(reducer: BuiltinNumericReducer) -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
        .view_native()
        .numeric_sink(reducer)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::NumericReducer)
        .lowering(BuiltinPipelineLowering::TerminalSink)
}

/// Arg-extreme reducer (`max_by` / `min_by`) skeleton.
#[inline]
fn arg_extreme_reducer_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
        .view_native()
        .cost(10.0)
        .lowering(BuiltinPipelineLowering::TerminalSink)
}

/// Predicate terminal sink skeleton for short-circuiting reducers.
#[inline]
fn predicate_terminal_sink_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
        .view_native()
        .cost(10.0)
        .lowering(BuiltinPipelineLowering::TerminalSink)
}

// ── Streaming filters ────────────────────────────────────────────────────────

/// Helper: shared spec body for the predicate filter family (Filter / Find / FindAll).
/// All three are streaming filters with identical pipeline characteristics; they only
/// differ in their parser-level surface (semantic aliasing).
#[inline]
fn filter_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
        .view_stage(BuiltinViewStage::Filter)
        .columnar_stage(BuiltinColumnarStage::Filter)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::FilterLike)
        .order_effect(BuiltinPipelineOrderEffect::PredicatePrefix)
        .lowering(BuiltinPipelineLowering::ExprArg)
}

/// Predicate filter: keeps elements for which the lambda yields a truthy value.
pub(crate) struct Filter;
impl Builtin for Filter {
    const METHOD: BuiltinMethod = BuiltinMethod::Filter;
    const NAME: &'static str = "filter";

    fn spec() -> BuiltinSpec {
        filter_spec()
    }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        let prog = body.expect("filter body");
        let keep = super::filter_one(&item, |v| {
            crate::exec::pipeline::eval_kernel_with_vm(ctx.kernel, v, ctx.vm, |it, vm| {
                crate::exec::pipeline::apply_item_in_env(vm, ctx.env, it, prog)
            })
        })?;
        Ok(if keep {
            crate::exec::pipeline::StageFlow::Continue(item)
        } else {
            crate::exec::pipeline::StageFlow::SkipRow
        })
    }
#[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::filter_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel_with_vm(ctx.kernel, v, ctx.vm, |item, vm| {
                crate::exec::pipeline::apply_item_in_env(vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(out) => { *buf = out; Some(Ok(())) }
            Err(err) => Some(Err(err)),
        }
    }
}

/// `find(pred)` — returns the first element for which `pred` is truthy,
/// or `null` when nothing matches. Matches the conventional first-match
/// semantics found in JavaScript / Rust / Python iterators. Use
/// `find_all` (filter alias) when every match is desired.
pub(crate) struct Find;
impl Builtin for Find {
    const METHOD: BuiltinMethod = BuiltinMethod::Find;
    const NAME: &'static str = "find";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FilterLike)
            .lowering(BuiltinPipelineLowering::TerminalExprArg {
                terminal: BuiltinMethod::First,
            })
    }
}

/// Surface alias of `Filter` (same semantics; user-facing v2 name).
pub(crate) struct FindAll;
impl Builtin for FindAll {
    const METHOD: BuiltinMethod = BuiltinMethod::FindAll;
    const NAME: &'static str = "find_all";

    fn spec() -> BuiltinSpec {
        filter_spec()
    }
}

/// Removes nullish elements; degenerate filter with no lambda.
pub(crate) struct Compact;
impl Builtin for Compact {
    const METHOD: BuiltinMethod = BuiltinMethod::Compact;
    const NAME: &'static str = "compact";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .view_stage(BuiltinViewStage::Compact)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FilterLike)
            .order_effect(BuiltinPipelineOrderEffect::PredicatePrefix)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::compact_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// Removes elements equal to the literal argument; degenerate equality filter.
pub(crate) struct Remove;
impl Builtin for Remove {
    const METHOD: BuiltinMethod = BuiltinMethod::Remove;
    const NAME: &'static str = "remove";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .view_stage(BuiltinViewStage::RemoveValue)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FilterLike)
            .order_effect(BuiltinPipelineOrderEffect::PredicatePrefix)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::remove_value_apply(recv, item).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

// ── Streaming one-to-one ─────────────────────────────────────────────────────

/// Per-element projection via lambda; preserves cardinality and order.
pub(crate) struct Map;
impl Builtin for Map {
    const METHOD: BuiltinMethod = BuiltinMethod::Map;
    const NAME: &'static str = "map";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingOneToOne, BuiltinCardinality::OneToOne)
            .indexed()
            .view_stage(BuiltinViewStage::Map)
            .columnar_stage(BuiltinColumnarStage::Map)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .lowering(BuiltinPipelineLowering::ExprArg)
            .element()
    }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        let prog = body.expect("map body");
        // Terminal-map collector short-circuit (avoid allocating intermediate Val).
        if Some(ctx.stage_idx) == ctx.terminal_map_idx {
            ctx.terminal_map_collect
                .as_mut()
                .expect("terminal map collector")
                .push_val_row(&item, ctx.kernel, |it| {
                    crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, it, prog)
                })?;
            return Ok(crate::exec::pipeline::StageFlow::TerminalCollected);
        }
        let mapped = super::map_one(&item, |v| {
            crate::exec::pipeline::eval_kernel_with_vm(ctx.kernel, v, ctx.vm, |it, vm| {
                crate::exec::pipeline::apply_item_in_env(vm, ctx.env, it, prog)
            })
        })?;
        Ok(crate::exec::pipeline::StageFlow::Continue(mapped))
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::map_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel_with_vm(ctx.kernel, v, ctx.vm, |item, vm| {
                crate::exec::pipeline::apply_item_in_env(vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(out) => { *buf = out; Some(Ok(())) }
            Err(err) => Some(Err(err)),
        }
    }
}

/// Expanding projection: each element produces an array; outputs are concatenated.
pub(crate) struct FlatMap;
impl Builtin for FlatMap {
    const METHOD: BuiltinMethod = BuiltinMethod::FlatMap;
    const NAME: &'static str = "flat_map";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingExpand, BuiltinCardinality::Expanding)
            .view_stage(BuiltinViewStage::FlatMap)
            .columnar_stage(BuiltinColumnarStage::FlatMap)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FlatMapLike)
            .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
            .lowering(BuiltinPipelineLowering::ExprArg)
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let mut out: Vec<crate::data::value::Val> = Vec::new();
        for v in buf.iter() {
            let inner = match crate::exec::pipeline::eval_kernel_with_vm(ctx.kernel, v, ctx.vm, |item, vm| {
                crate::exec::pipeline::apply_item_in_env(vm, ctx.env, item, prog)
            }) {
                Ok(inner) => inner,
                Err(err) => return Some(Err(err)),
            };
            if let Some(arr) = inner.as_vals() {
                out.extend(arr.iter().cloned());
            } else {
                out.push(inner);
            }
        }
        *buf = out;
        Some(Ok(()))
    }
}

// ── Bounded prefix / positional ──────────────────────────────────────────────

/// Take first N elements; bounded positional slice.
pub(crate) struct Take;
impl Builtin for Take {
    const METHOD: BuiltinMethod = BuiltinMethod::Take;
    const NAME: &'static str = "take";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Positional, BuiltinCardinality::Bounded)
            .view_native()
            .view_stage(BuiltinViewStage::Take)
            .stage_merge(BuiltinStageMerge::UsizeMin)
            .demand_law(BuiltinDemandLaw::Take)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .lowering(BuiltinPipelineLowering::UsizeArg { min: 0 })
    }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        _body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        let n = match ctx.stage.descriptor().and_then(|d| d.usize_arg) {
            Some(n) => n,
            None => return Ok(crate::exec::pipeline::StageFlow::Continue(item)),
        };
        if ctx.stage_taken[ctx.stage_idx] >= n {
            Ok(crate::exec::pipeline::StageFlow::Stop)
        } else {
            ctx.stage_taken[ctx.stage_idx] += 1;
            Ok(crate::exec::pipeline::StageFlow::Continue(item))
        }
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        _body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let n = ctx.stage.descriptor().and_then(|d| d.usize_arg)?;
        buf.truncate(n);
        Some(Ok(()))
    }

    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => super::take_apply(recv, *n),
            _ => None,
        }
    }
}

/// Skip first N elements; bounded positional offset.
pub(crate) struct Skip;
impl Builtin for Skip {
    const METHOD: BuiltinMethod = BuiltinMethod::Skip;
    const NAME: &'static str = "skip";
    const ALIASES: &'static [&'static str] = &["drop"];

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Positional, BuiltinCardinality::Bounded)
            .view_native()
            .view_stage(BuiltinViewStage::Skip)
            .stage_merge(BuiltinStageMerge::UsizeSaturatingAdd)
            .demand_law(BuiltinDemandLaw::Skip)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .lowering(BuiltinPipelineLowering::UsizeArg { min: 0 })
    }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        _body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        let n = match ctx.stage.descriptor().and_then(|d| d.usize_arg) {
            Some(n) => n,
            None => return Ok(crate::exec::pipeline::StageFlow::Continue(item)),
        };
        if ctx.stage_skipped[ctx.stage_idx] < n {
            ctx.stage_skipped[ctx.stage_idx] += 1;
            Ok(crate::exec::pipeline::StageFlow::SkipRow)
        } else {
            Ok(crate::exec::pipeline::StageFlow::Continue(item))
        }
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        _body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let n = ctx.stage.descriptor().and_then(|d| d.usize_arg)?;
        if buf.len() <= n {
            buf.clear();
        } else {
            buf.drain(..n);
        }
        Some(Ok(()))
    }

    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => super::skip_apply(recv, *n),
            _ => None,
        }
    }
}

/// Selects the first element; terminal positional sink.
pub(crate) struct First;
impl Builtin for First {
    const METHOD: BuiltinMethod = BuiltinMethod::First;
    const NAME: &'static str = "first";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Positional, BuiltinCardinality::Bounded)
            .view_native()
            .select_one_sink(BuiltinSelectionPosition::First)
            .demand_law(BuiltinDemandLaw::First)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::I64(n) => { super::first_apply(recv, *n) }
            _ => None,
        }
    }
}

/// Selects the last element; terminal positional sink.
pub(crate) struct Last;
impl Builtin for Last {
    const METHOD: BuiltinMethod = BuiltinMethod::Last;
    const NAME: &'static str = "last";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Positional, BuiltinCardinality::Bounded)
            .view_native()
            .select_one_sink(BuiltinSelectionPosition::Last)
            .demand_law(BuiltinDemandLaw::Last)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::I64(n) => { super::last_apply(recv, *n) }
            _ => None,
        }
    }
}

// ── Bounded prefix predicates ────────────────────────────────────────────────

/// Take elements while predicate holds; stops at first failure.
pub(crate) struct TakeWhile;
impl Builtin for TakeWhile {
    const METHOD: BuiltinMethod = BuiltinMethod::TakeWhile;
    const NAME: &'static str = "take_while";
    const ALIASES: &'static [&'static str] = &["takewhile"];

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .view_stage(BuiltinViewStage::TakeWhile)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::TakeWhile)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::Filtering,
                true,
                10.0,
                0.5,
            ))
            .order_effect(BuiltinPipelineOrderEffect::PredicatePrefix)
            .lowering(BuiltinPipelineLowering::ExprArg)
    }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        let prog = body.expect("take_while body");
        let pass = super::take_while_one(&item, |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |it| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, it, prog)
            })
        })?;
        Ok(if pass {
            crate::exec::pipeline::StageFlow::Continue(item)
        } else {
            crate::exec::pipeline::StageFlow::Stop
        })
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::take_while_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(out) => { *buf = out; Some(Ok(())) }
            Err(err) => Some(Err(err)),
        }
    }
}

/// Skip elements while predicate holds; emits the remainder.
pub(crate) struct DropWhile;
impl Builtin for DropWhile {
    const METHOD: BuiltinMethod = BuiltinMethod::DropWhile;
    const NAME: &'static str = "drop_while";
    const ALIASES: &'static [&'static str] = &["dropwhile"];

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .view_stage(BuiltinViewStage::DropWhile)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::DropWhile)
            .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::Filtering,
                true,
                10.0,
                0.5,
            ))
            .order_effect(BuiltinPipelineOrderEffect::Blocks)
            .lowering(BuiltinPipelineLowering::ExprArg)
    }

    /// DropWhile in the streaming loop is a no-op pass-through (the materialised
    /// barrier path handles the actual drop semantics in materialized_exec). Mirrors
    /// the original `PrefixWhile { take: false }` arm in val_stage_flow.
    #[inline]
    fn apply_stream(
        _ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        _body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        Ok(crate::exec::pipeline::StageFlow::Continue(item))
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::drop_while_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(out) => { *buf = out; Some(Ok(())) }
            Err(err) => Some(Err(err)),
        }
    }
}

// ── Reducer sinks ────────────────────────────────────────────────────────────

/// Element count via scalar view sink; degenerate non-numeric reducer.
pub(crate) struct Len;
impl Builtin for Len {
    const METHOD: BuiltinMethod = BuiltinMethod::Len;
    const NAME: &'static str = "len";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .indexed()
            .view_scalar()
            .count_sink()
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::len_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// Sum of numeric stream elements.
pub(crate) struct Sum;
impl Builtin for Sum {
    const METHOD: BuiltinMethod = BuiltinMethod::Sum;
    const NAME: &'static str = "sum";

    fn spec() -> BuiltinSpec {
        numeric_reducer_spec(BuiltinNumericReducer::Sum)
    }
}

/// Arithmetic mean of numeric stream elements.
pub(crate) struct Avg;
impl Builtin for Avg {
    const METHOD: BuiltinMethod = BuiltinMethod::Avg;
    const NAME: &'static str = "avg";

    fn spec() -> BuiltinSpec {
        numeric_reducer_spec(BuiltinNumericReducer::Avg)
    }
}

/// Smallest numeric element.
pub(crate) struct Min;
impl Builtin for Min {
    const METHOD: BuiltinMethod = BuiltinMethod::Min;
    const NAME: &'static str = "min";

    fn spec() -> BuiltinSpec {
        numeric_reducer_spec(BuiltinNumericReducer::Min)
    }
}

/// Largest numeric element.
pub(crate) struct Max;
impl Builtin for Max {
    const METHOD: BuiltinMethod = BuiltinMethod::Max;
    const NAME: &'static str = "max";

    fn spec() -> BuiltinSpec {
        numeric_reducer_spec(BuiltinNumericReducer::Max)
    }
}

/// Stream length count; differs from `Len` in being a streaming reducer (not scalar).
pub(crate) struct Count;
impl Builtin for Count {
    const METHOD: BuiltinMethod = BuiltinMethod::Count;
    const NAME: &'static str = "count";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_native()
            .count_sink()
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::Count)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
}

/// HyperLogLog-style approximate distinct count.
///
/// Backed by a register-array HyperLogLog estimator with 14-bit precision
/// (≈16 KiB state). Hashes each element via `val_to_key` + 64-bit FNV; the
/// algorithm is the canonical small-range corrected HLL, matching the
/// classic Flajolet et al. error bound (~1.04 / sqrt(2^14) ≈ 0.81% RSE).
/// Returns `Val::Int(estimate)`. For small arrays (< 16 distinct values)
/// the linear-counting correction makes the estimate exact, so simple
/// inputs converge to the same answer as `.unique().count()`.
pub(crate) struct ApproxCountDistinct;
impl Builtin for ApproxCountDistinct {
    const METHOD: BuiltinMethod = BuiltinMethod::ApproxCountDistinct;
    const NAME: &'static str = "approx_count_distinct";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_native()
            .approx_distinct_sink()
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::RowKeyedReducer)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        let items = recv.as_vals()?;
        Some(crate::data::value::Val::Int(super::hll_count_distinct(&items) as i64))
    }
}

/// Boolean reducer: true if any element matches predicate.
pub(crate) struct Any;
impl Builtin for Any {
    const METHOD: BuiltinMethod = BuiltinMethod::Any;
    const NAME: &'static str = "any";
    const ALIASES: &'static [&'static str] = &["exists"];

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_native()
            .cost(10.0)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
}

/// Boolean reducer: true if all elements match predicate.
pub(crate) struct All;
impl Builtin for All {
    const METHOD: BuiltinMethod = BuiltinMethod::All;
    const NAME: &'static str = "all";

    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_native()
            .cost(10.0)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
}

/// Index of the first element satisfying the predicate.
pub(crate) struct FindIndex;
impl Builtin for FindIndex {
    const METHOD: BuiltinMethod = BuiltinMethod::FindIndex;
    const NAME: &'static str = "find_index";

    fn spec() -> BuiltinSpec {
        predicate_terminal_sink_spec()
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let mut found: crate::data::value::Val = crate::data::value::Val::Null;
        for (i, v) in buf.iter().enumerate() {
            match super::filter_one(v, |item| {
                crate::exec::pipeline::eval_kernel(ctx.kernel, item, |it| {
                    crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, it, prog)
                })
            }) {
                Ok(true) => {
                    found = crate::data::value::Val::Int(i as i64);
                    break;
                }
                Ok(false) => {}
                Err(err) => return Some(Err(err)),
            }
        }
        *buf = vec![found];
        Some(Ok(()))
    }
}

/// Indices of all elements satisfying the predicate.
pub(crate) struct IndicesWhere;
impl Builtin for IndicesWhere {
    const METHOD: BuiltinMethod = BuiltinMethod::IndicesWhere;
    const NAME: &'static str = "indices_where";

    fn spec() -> BuiltinSpec {
        predicate_terminal_sink_spec()
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let mut out: Vec<i64> = Vec::new();
        for (i, v) in buf.iter().enumerate() {
            match super::filter_one(v, |item| {
                crate::exec::pipeline::eval_kernel(ctx.kernel, item, |it| {
                    crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, it, prog)
                })
            }) {
                Ok(true) => out.push(i as i64),
                Ok(false) => {}
                Err(err) => return Some(Err(err)),
            }
        }
        *buf = vec![crate::data::value::Val::int_vec(out)];
        Some(Ok(()))
    }
}

/// Shared barrier body for MaxBy / MinBy (ArgExtreme).
#[inline]
fn arg_extreme_apply_barrier(
    ctx: &mut super::builtin::BarrierCtx<'_>,
    buf: &mut Vec<crate::data::value::Val>,
    body: Option<&crate::vm::Program>,
    max: bool,
) -> Option<Result<(), crate::data::context::EvalError>> {
    let prog = body?;
    if buf.is_empty() {
        *buf = vec![crate::data::value::Val::Null];
        return Some(Ok(()));
    }
    let mut best_idx = 0usize;
    let mut best_key = match crate::exec::pipeline::eval_kernel(ctx.kernel, &buf[0], |item| {
        crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
    }) {
        Ok(key) => key,
        Err(err) => return Some(Err(err)),
    };
    for i in 1..buf.len() {
        let key = match crate::exec::pipeline::eval_kernel(ctx.kernel, &buf[i], |item| {
            crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
        }) {
            Ok(key) => key,
            Err(err) => return Some(Err(err)),
        };
        let cmp = crate::exec::pipeline::cmp_val_total(&key, &best_key);
        let take = if max {
            cmp == std::cmp::Ordering::Greater
        } else {
            cmp == std::cmp::Ordering::Less
        };
        if take {
            best_idx = i;
            best_key = key;
        }
    }
    let best = std::mem::take(buf).into_iter().nth(best_idx).unwrap();
    *buf = vec![best];
    Some(Ok(()))
}

/// Element with the largest projected key.
pub(crate) struct MaxBy;
impl Builtin for MaxBy {
    const METHOD: BuiltinMethod = BuiltinMethod::MaxBy;
    const NAME: &'static str = "max_by";

    fn spec() -> BuiltinSpec {
        arg_extreme_reducer_spec()
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        arg_extreme_apply_barrier(ctx, buf, body, true)
    }
}

/// Element with the smallest projected key.
pub(crate) struct MinBy;
impl Builtin for MinBy {
    const METHOD: BuiltinMethod = BuiltinMethod::MinBy;
    const NAME: &'static str = "min_by";

    fn spec() -> BuiltinSpec {
        arg_extreme_reducer_spec()
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        arg_extreme_apply_barrier(ctx, buf, body, false)
    }
}

// ── Indexed/element-only streaming ───────────────────────────────────────────

/// `enumerate` — pairs each element with its index. Operates on the
/// whole receiver array as one unit; NOT marked `.element()` because the
/// streaming pipeline would otherwise treat the receiver as a 1-element
/// stream and discard the pairing (visible as `[items]` not `[{index,
/// value}, ...]`).
pub(crate) struct Enumerate;
impl Builtin for Enumerate {
    const METHOD: BuiltinMethod = BuiltinMethod::Enumerate;
    const NAME: &'static str = "enumerate";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingOneToOne, BuiltinCardinality::OneToOne)
            .indexed()
            .cost(10.0)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::enumerate_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `pairwise` — yields adjacent pairs as `[a, b]` tuples. Like
/// `enumerate`, NOT marked `.element()` because the streaming pipeline
/// would treat the receiver as a 1-element stream and discard the pair
/// formation, returning the bare array instead of `[[a,b], ...]`.
pub(crate) struct Pairwise;
impl Builtin for Pairwise {
    const METHOD: BuiltinMethod = BuiltinMethod::Pairwise;
    const NAME: &'static str = "pairwise";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingOneToOne, BuiltinCardinality::OneToOne)
            .indexed()
            .cost(10.0)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::pairwise_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

// ── Expanding (no lambda) ────────────────────────────────────────────────────

#[inline]
fn expand_simple_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::StreamingExpand, BuiltinCardinality::Expanding)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::FlatMapLike)
}

/// `flatten` — concatenates nested arrays.
pub(crate) struct Flatten;
impl Builtin for Flatten {
    const METHOD: BuiltinMethod = BuiltinMethod::Flatten;
    const NAME: &'static str = "flatten";
    fn spec() -> BuiltinSpec { expand_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(depth) => { super::flatten_depth_apply(recv, *depth) }
            _ => None,
        }
    }
}

/// `explode` — same as flatten with object semantics.
pub(crate) struct Explode;
impl Builtin for Explode {
    const METHOD: BuiltinMethod = BuiltinMethod::Explode;
    const NAME: &'static str = "explode";
    fn spec() -> BuiltinSpec { expand_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(field) => { super::explode_apply(recv, field) }
            _ => None,
        }
    }
}

/// `split(sep)` — string-arg expansion stage.
pub(crate) struct Split;
impl Builtin for Split {
    const METHOD: BuiltinMethod = BuiltinMethod::Split;
    const NAME: &'static str = "split";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingExpand, BuiltinCardinality::Expanding)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FlatMapLike)
            .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::Expanding,
                true,
                2.0,
                1.0,
            ))
            .lowering(BuiltinPipelineLowering::StringArg)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::split_apply(recv, p) }
            _ => None,
        }
    }
}

#[inline]
fn expand_element_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::StreamingExpand, BuiltinCardinality::Expanding)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::FlatMapLike)
        .element()
}

/// `lines` — split string on newlines.
pub(crate) struct Lines;
impl Builtin for Lines {
    const METHOD: BuiltinMethod = BuiltinMethod::Lines;
    const NAME: &'static str = "lines";
    fn spec() -> BuiltinSpec { expand_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::lines_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `words` — whitespace-tokenise string.
pub(crate) struct Words;
impl Builtin for Words {
    const METHOD: BuiltinMethod = BuiltinMethod::Words;
    const NAME: &'static str = "words";
    fn spec() -> BuiltinSpec { expand_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::words_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `chars` — string char iterator.
pub(crate) struct Chars;
impl Builtin for Chars {
    const METHOD: BuiltinMethod = BuiltinMethod::Chars;
    const NAME: &'static str = "chars";
    fn spec() -> BuiltinSpec { expand_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::chars_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `chars_of` — chars at given positions.
pub(crate) struct CharsOf;
impl Builtin for CharsOf {
    const METHOD: BuiltinMethod = BuiltinMethod::CharsOf;
    const NAME: &'static str = "chars_of";
    fn spec() -> BuiltinSpec { expand_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::chars_of_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `bytes` — string byte iterator.
pub(crate) struct Bytes;
impl Builtin for Bytes {
    const METHOD: BuiltinMethod = BuiltinMethod::Bytes;
    const NAME: &'static str = "bytes";
    fn spec() -> BuiltinSpec { expand_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::bytes_of_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

// ── Find-first / find-one ────────────────────────────────────────────────────

/// `find_first(pred)` — terminal expr-arg returning first match with First demand.
pub(crate) struct FindFirst;
impl Builtin for FindFirst {
    const METHOD: BuiltinMethod = BuiltinMethod::FindFirst;
    const NAME: &'static str = "find_first";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::FilterLike)
            .lowering(BuiltinPipelineLowering::TerminalExprArg {
                terminal: BuiltinMethod::First,
            })
    }
}

/// `find_one(pred)` — terminal predicate sink requiring exactly one match.
pub(crate) struct FindOne;
impl Builtin for FindOne {
    const METHOD: BuiltinMethod = BuiltinMethod::FindOne;
    const NAME: &'static str = "find_one";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
            .cost(10.0)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
}

// ── Positional miscellaneous ─────────────────────────────────────────────────

#[inline]
fn positional_native_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Positional, BuiltinCardinality::Bounded).view_native()
}

/// `nth(i)` — positional select by index.
pub(crate) struct Nth;
impl Builtin for Nth {
    const METHOD: BuiltinMethod = BuiltinMethod::Nth;
    const NAME: &'static str = "nth";
    fn spec() -> BuiltinSpec {
        positional_native_spec()
            .demand_law(BuiltinDemandLaw::Nth)
            .lowering(BuiltinPipelineLowering::TerminalUsizeSink { min: 0 })
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::I64(n) => { super::nth_any_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `collect()` — materialise stream to Vec; positional pass-through.
pub(crate) struct Collect;
impl Builtin for Collect {
    const METHOD: BuiltinMethod = BuiltinMethod::Collect;
    const NAME: &'static str = "collect";
    fn spec() -> BuiltinSpec { positional_native_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::collect_apply(recv))
    }
}

// ── Barrier family ───────────────────────────────────────────────────────────

#[inline]
fn barrier_default_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Barrier, BuiltinCardinality::Barrier)
        .cost(20.0)
        .demand_law(BuiltinDemandLaw::OrderBarrier)
}

/// `sort` — full-barrier comparison sort, optional key.
pub(crate) struct Sort;
impl Builtin for Sort {
    const METHOD: BuiltinMethod = BuiltinMethod::Sort;
    const NAME: &'static str = "sort";
    const ALIASES: &'static [&'static str] = &["sort_by"];
    fn spec() -> BuiltinSpec {
        barrier_default_spec()
            .demand_law(BuiltinDemandLaw::OrderBarrier)
            .materialization(BuiltinPipelineMaterialization::ComposedBarrier)
            .lowering(BuiltinPipelineLowering::Sort)
    }
    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let _ = body;
        let _ = ctx;
        let crate::exec::pipeline::Stage::Sort(spec) = ctx.stage else {
            return None;
        };
        let descending = spec.descending;
        let strategy = ctx.strategy;
        let result = match &spec.key {
            None => crate::exec::pipeline::bounded_sort_by_key(
                std::mem::take(buf), descending, strategy, |v| Ok(v.clone()),
            ),
            Some(prog) => {
                let key_prog = prog.clone();
                crate::exec::pipeline::bounded_sort_by_key(
                    std::mem::take(buf), descending, strategy, |v| {
                        Ok(crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                            crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, &key_prog)
                        }).unwrap_or(crate::data::value::Val::Null))
                    },
                )
            }
        };
        match result {
            Ok(sorted) => { *buf = sorted; Some(Ok(())) }
            Err(err) => Some(Err(err)),
        }
    }
}

/// `group_shape()` — bucket an array of objects by their structural key
/// set (sorted, comma-joined). Output is `{shape_key: [items]}` with
/// first-occurrence order preserved. The 2-arg form `group_shape(key,
/// shape)` (key projection + per-group shape transform) dispatches via
/// the lambda-method runtime path.
pub(crate) struct GroupShape;
impl Builtin for GroupShape {
    const METHOD: BuiltinMethod = BuiltinMethod::GroupShape;
    const NAME: &'static str = "group_shape";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        super::group_shape_by_keys_apply(recv.clone())
    }
}

/// `partition` — splits stream by predicate; barrier.
pub(crate) struct Partition;
impl Builtin for Partition {
    const METHOD: BuiltinMethod = BuiltinMethod::Partition;
    const NAME: &'static str = "partition";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
}

/// `window(n)` — sliding window barrier.
pub(crate) struct Window;
impl Builtin for Window {
    const METHOD: BuiltinMethod = BuiltinMethod::Window;
    const NAME: &'static str = "window";
    fn spec() -> BuiltinSpec {
        barrier_default_spec()
            .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::Barrier,
                true,
                2.0,
                1.0,
            ))
            .demand_law(BuiltinDemandLaw::Window)
            .lowering(BuiltinPipelineLowering::UsizeArg { min: 1 })
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        _body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let n = ctx.stage.descriptor().and_then(|d| d.usize_arg)?;
        *buf = super::window_apply(buf, n);
        Some(Ok(()))
    }
}

/// `chunk(n)` — non-overlapping fixed-size buckets.
pub(crate) struct Chunk;
impl Builtin for Chunk {
    const METHOD: BuiltinMethod = BuiltinMethod::Chunk;
    const NAME: &'static str = "chunk";
    const ALIASES: &'static [&'static str] = &["batch"];
    fn spec() -> BuiltinSpec {
        barrier_default_spec()
            .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::Barrier,
                true,
                2.0,
                1.0,
            ))
            .demand_law(BuiltinDemandLaw::Chunk)
            .lowering(BuiltinPipelineLowering::UsizeArg { min: 1 })
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        _body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let n = ctx.stage.descriptor().and_then(|d| d.usize_arg)?;
        *buf = super::chunk_apply(buf, n);
        Some(Ok(()))
    }
}

/// `rolling_sum(n)` — windowed sum barrier.
pub(crate) struct RollingSum;
impl Builtin for RollingSum {
    const METHOD: BuiltinMethod = BuiltinMethod::RollingSum;
    const NAME: &'static str = "rolling_sum";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::rolling_sum_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `rolling_avg(n)` — windowed mean barrier.
pub(crate) struct RollingAvg;
impl Builtin for RollingAvg {
    const METHOD: BuiltinMethod = BuiltinMethod::RollingAvg;
    const NAME: &'static str = "rolling_avg";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::rolling_avg_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `rolling_min(n)` — windowed min barrier.
pub(crate) struct RollingMin;
impl Builtin for RollingMin {
    const METHOD: BuiltinMethod = BuiltinMethod::RollingMin;
    const NAME: &'static str = "rolling_min";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::rolling_min_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `rolling_max(n)` — windowed max barrier.
pub(crate) struct RollingMax;
impl Builtin for RollingMax {
    const METHOD: BuiltinMethod = BuiltinMethod::RollingMax;
    const NAME: &'static str = "rolling_max";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::rolling_max_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `accumulate` — running fold barrier.
pub(crate) struct Accumulate;
impl Builtin for Accumulate {
    const METHOD: BuiltinMethod = BuiltinMethod::Accumulate;
    const NAME: &'static str = "accumulate";
    fn spec() -> BuiltinSpec { barrier_default_spec() }
}

/// `fold(init, fn)` / `fold(fn)` — like `accumulate(...).last()` but
/// emits a single value instead of the running-trace array. Equivalent
/// to `Iterator::fold` (with init) or `Iterator::reduce` (without).
pub(crate) struct Fold;
impl Builtin for Fold {
    const METHOD: BuiltinMethod = BuiltinMethod::Fold;
    const NAME: &'static str = "fold";
    const ALIASES: &'static [&'static str] = &["reduce"];
    fn spec() -> BuiltinSpec { barrier_default_spec() }
}

// ── Keyed reducers ───────────────────────────────────────────────────────────

/// `group_by(key)` — keyed reducer collecting elements per key.
pub(crate) struct GroupBy;
impl Builtin for GroupBy {
    const METHOD: BuiltinMethod = BuiltinMethod::GroupBy;
    const NAME: &'static str = "group_by";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_stage(BuiltinViewStage::KeyedReduce)
            .keyed_reducer(BuiltinKeyedReducer::Group)
            .columnar_stage(BuiltinColumnarStage::GroupBy)
            .cost(20.0)
            .demand_law(BuiltinDemandLaw::RowKeyedReducer)
            .materialization(BuiltinPipelineMaterialization::ComposedBarrier)
            .lowering(BuiltinPipelineLowering::ExprArg)
    }
    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let _ = body;
        let _ = ctx;
        let prog = match body {
            Some(p) => p,
            None => return Some(Ok(())),
        };
        let result = super::group_by_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(out_obj) => {
                *buf = vec![crate::data::value::Val::Obj(std::sync::Arc::new(out_obj))];
                Some(Ok(()))
            }
            Err(err) => Some(Err(err)),
        }
    }
}

/// `count_by(key)` — keyed reducer counting per key.
pub(crate) struct CountBy;
impl Builtin for CountBy {
    const METHOD: BuiltinMethod = BuiltinMethod::CountBy;
    const NAME: &'static str = "count_by";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_stage(BuiltinViewStage::KeyedReduce)
            .keyed_reducer(BuiltinKeyedReducer::Count)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::KeyOnlyReducer)
            .materialization(BuiltinPipelineMaterialization::ComposedBarrier)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::OneToOne,
                true,
                1.0,
                1.0,
            ))
            .lowering(BuiltinPipelineLowering::TerminalExprArg {
                terminal: BuiltinMethod::First,
            })
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::count_by_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(map) => {
                *buf = vec![crate::data::value::Val::obj(map)];
                Some(Ok(()))
            }
            Err(err) => Some(Err(err)),
        }
    }
}

/// `index_by(key)` — keyed reducer with last-write-wins.
pub(crate) struct IndexBy;
impl Builtin for IndexBy {
    const METHOD: BuiltinMethod = BuiltinMethod::IndexBy;
    const NAME: &'static str = "index_by";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Reducer, BuiltinCardinality::Reducing)
            .view_stage(BuiltinViewStage::KeyedReduce)
            .keyed_reducer(BuiltinKeyedReducer::Index)
            .cost(10.0)
            .demand_law(BuiltinDemandLaw::RowKeyedReducer)
            .materialization(BuiltinPipelineMaterialization::ComposedBarrier)
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::OneToOne,
                true,
                1.0,
                1.0,
            ))
            .lowering(BuiltinPipelineLowering::TerminalExprArg {
                terminal: BuiltinMethod::First,
            })
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        let prog = body?;
        let result = super::index_by_apply(std::mem::take(buf), |v| {
            crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
            })
        });
        match result {
            Ok(map) => {
                *buf = vec![crate::data::value::Val::obj(map)];
                Some(Ok(()))
            }
            Err(err) => Some(Err(err)),
        }
    }
}

// ── Distinct / unique ────────────────────────────────────────────────────────

#[inline]
fn unique_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::StreamingFilter, BuiltinCardinality::Filtering)
        .view_stage(BuiltinViewStage::Distinct)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::UniqueLike)
        .pipeline_shape(BuiltinPipelineShape::new(
            BuiltinCardinality::Filtering,
            true,
            10.0,
            1.0,
        ))
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .materialization(BuiltinPipelineMaterialization::LegacyMaterialized)
}

/// Shared barrier body for Unique / UniqueBy.
#[inline]
fn unique_apply_barrier(
    ctx: &mut super::builtin::BarrierCtx<'_>,
    buf: &mut Vec<crate::data::value::Val>,
    body: Option<&crate::vm::Program>,
) -> Option<Result<(), crate::data::context::EvalError>> {
    match body {
        None => {
            let mut seen: std::collections::HashSet<String> = Default::default();
            buf.retain(|v| seen.insert(format!("{:?}", v)));
        }
        Some(prog) => {
            let mut seen: std::collections::HashSet<String> = Default::default();
            let mut keep: Vec<bool> = Vec::with_capacity(buf.len());
            for v in buf.iter() {
                let key = crate::exec::pipeline::eval_kernel(ctx.kernel, v, |item| {
                    crate::exec::pipeline::apply_item_in_env(ctx.vm, ctx.env, item, prog)
                })
                .unwrap_or(crate::data::value::Val::Null);
                keep.push(seen.insert(format!("{:?}", key)));
            }
            let mut out: Vec<crate::data::value::Val> = Vec::with_capacity(buf.len());
            for (i, v) in std::mem::take(buf).into_iter().enumerate() {
                if keep[i] {
                    out.push(v);
                }
            }
            *buf = out;
        }
    }
    Some(Ok(()))
}

/// `unique` — argument-free distinct.
pub(crate) struct Unique;
impl Builtin for Unique {
    const METHOD: BuiltinMethod = BuiltinMethod::Unique;
    const NAME: &'static str = "unique";
    const ALIASES: &'static [&'static str] = &["distinct"];
    fn spec() -> BuiltinSpec {
        unique_spec().lowering(BuiltinPipelineLowering::Nullary)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::unique_arr_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        unique_apply_barrier(ctx, buf, body)
    }
}

/// `unique_by(key)` — distinct by projected key.
pub(crate) struct UniqueBy;
impl Builtin for UniqueBy {
    const METHOD: BuiltinMethod = BuiltinMethod::UniqueBy;
    const NAME: &'static str = "unique_by";
    const ALIASES: &'static [&'static str] = &["distinct_by"];
    fn spec() -> BuiltinSpec {
        unique_spec().lowering(BuiltinPipelineLowering::ExprArg)
    }
    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        unique_apply_barrier(ctx, buf, body)
    }
}

// ── Reverse ──────────────────────────────────────────────────────────────────

/// `reverse` — full-barrier order reversal; cancels with adjacent reverse.
pub(crate) struct Reverse;
impl Builtin for Reverse {
    const METHOD: BuiltinMethod = BuiltinMethod::Reverse;
    const NAME: &'static str = "reverse";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Barrier, BuiltinCardinality::Barrier)
            .cost(10.0)
            .cancellation(BuiltinCancellation::SelfInverse(BuiltinCancelGroup::Reverse))
            .demand_law(BuiltinDemandLaw::Reverse)
            .materialization(BuiltinPipelineMaterialization::ComposedBarrier)
            .lowering(BuiltinPipelineLowering::Nullary)
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::reverse_any_apply(recv).unwrap_or_else(|| recv.clone()))
    }

    #[inline]
    fn apply_barrier(
        _ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        _body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        buf.reverse();
        Some(Ok(()))
    }
}

// ── Set / array combiners (barriers, no extra metadata) ──────────────────────

#[inline]
fn barrier_simple_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Barrier, BuiltinCardinality::Barrier)
        .cost(10.0)
        .demand_law(BuiltinDemandLaw::OrderBarrier)
}

/// `append(arr)` — concatenates barrier.
pub(crate) struct Append;
impl Builtin for Append {
    const METHOD: BuiltinMethod = BuiltinMethod::Append;
    const NAME: &'static str = "append";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::append_apply(recv, item).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

/// `prepend(arr)` — prepend barrier.
pub(crate) struct Prepend;
impl Builtin for Prepend {
    const METHOD: BuiltinMethod = BuiltinMethod::Prepend;
    const NAME: &'static str = "prepend";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::prepend_apply(recv, item).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

/// `diff(arr)` — set difference.
pub(crate) struct Diff;
impl Builtin for Diff {
    const METHOD: BuiltinMethod = BuiltinMethod::Diff;
    const NAME: &'static str = "diff";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::ValVec(other) => { let arr_recv = recv.clone().into_vec().map(crate::data::value::Val::arr)?; super::diff_apply(&arr_recv, other) }
            _ => None,
        }
    }
}

/// `intersect(arr)` — set intersection.
pub(crate) struct Intersect;
impl Builtin for Intersect {
    const METHOD: BuiltinMethod = BuiltinMethod::Intersect;
    const NAME: &'static str = "intersect";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::ValVec(other) => { let arr_recv = recv.clone().into_vec().map(crate::data::value::Val::arr)?; super::intersect_apply(&arr_recv, other) }
            _ => None,
        }
    }
}

/// `union(arr)` — set union.
pub(crate) struct Union;
impl Builtin for Union {
    const METHOD: BuiltinMethod = BuiltinMethod::Union;
    const NAME: &'static str = "union";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::ValVec(other) => { let arr_recv = recv.clone().into_vec().map(crate::data::value::Val::arr)?; super::union_apply(&arr_recv, other) }
            _ => None,
        }
    }
}

/// `join(sep)` — string join barrier.
pub(crate) struct Join;
impl Builtin for Join {
    const METHOD: BuiltinMethod = BuiltinMethod::Join;
    const NAME: &'static str = "join";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(sep) => Some(super::join_apply(recv, sep).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

/// `zip(arr)` — element pairing.
pub(crate) struct Zip;
impl Builtin for Zip {
    const METHOD: BuiltinMethod = BuiltinMethod::Zip;
    const NAME: &'static str = "zip";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
}

/// `zip_longest(arr)` — pad-shorter zip.
pub(crate) struct ZipLongest;
impl Builtin for ZipLongest {
    const METHOD: BuiltinMethod = BuiltinMethod::ZipLongest;
    const NAME: &'static str = "zip_longest";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
}

/// `fanout(...)` — multi-projection.
pub(crate) struct Fanout;
impl Builtin for Fanout {
    const METHOD: BuiltinMethod = BuiltinMethod::Fanout;
    const NAME: &'static str = "fanout";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
}

/// `zip_shape(...)` — two callable shapes:
///
/// - **No-arg, object receiver**: parallel-array interleave. Receiver is
///   `{k1: arr1, k2: arr2, ...}`; output is an array of objects, one per
///   index, with each key holding `arr_i[index]`. Non-array values are
///   broadcast to every row. Output length = min array length.
/// - **Named-args, any receiver**: build an object `{name0: expr0(recv),
///   name1: expr1(recv), ...}` (legacy form, dispatched separately).
pub(crate) struct ZipShape;
impl Builtin for ZipShape {
    const METHOD: BuiltinMethod = BuiltinMethod::ZipShape;
    const NAME: &'static str = "zip_shape";
    fn spec() -> BuiltinSpec { barrier_simple_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        super::zip_shape_obj_apply(recv)
    }
}

// ── Object operations ────────────────────────────────────────────────────────

#[inline]
fn object_element_spec() -> BuiltinSpec {
    // Note: NOT marked `.element()`. Methods that share this spec (`keys`,
    // `values`, `entries`) take a single object and produce a single array
    // — they are not per-element vectorisable. Marking them element-wise
    // caused the streaming pipeline to wrap their already-array result in
    // an outer `Val::Arr`, producing the `[[pairs]]` triple-wrap bug.
    BuiltinSpec::new(BuiltinCategory::Object, BuiltinCardinality::OneToOne)
        .view_scalar()
        .demand_law(BuiltinDemandLaw::MapLike)
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .lowering(BuiltinPipelineLowering::Nullary)
}

/// `keys` — extract keys of an object (element-wise).
pub(crate) struct Keys;
impl Builtin for Keys {
    const METHOD: BuiltinMethod = BuiltinMethod::Keys;
    const NAME: &'static str = "keys";
    fn spec() -> BuiltinSpec { object_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::keys_apply(recv))
    }
}

/// `values` — extract values of an object (element-wise).
pub(crate) struct Values;
impl Builtin for Values {
    const METHOD: BuiltinMethod = BuiltinMethod::Values;
    const NAME: &'static str = "values";
    fn spec() -> BuiltinSpec { object_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::values_apply(recv))
    }
}

/// `entries` — extract (key, value) pairs (element-wise).
pub(crate) struct Entries;
impl Builtin for Entries {
    const METHOD: BuiltinMethod = BuiltinMethod::Entries;
    const NAME: &'static str = "entries";
    fn spec() -> BuiltinSpec { object_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::entries_apply(recv))
    }
}

#[inline]
fn object_simple_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Object, BuiltinCardinality::OneToOne)
}

/// `to_pairs` — convert object to array of `[k, v]` pairs.
pub(crate) struct ToPairs;
impl Builtin for ToPairs {
    const METHOD: BuiltinMethod = BuiltinMethod::ToPairs;
    const NAME: &'static str = "to_pairs";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::to_pairs_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `from_pairs` — invert `to_pairs`.
pub(crate) struct FromPairs;
impl Builtin for FromPairs {
    const METHOD: BuiltinMethod = BuiltinMethod::FromPairs;
    const NAME: &'static str = "from_pairs";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::from_pairs_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `invert` — swap keys and values.
pub(crate) struct Invert;
impl Builtin for Invert {
    const METHOD: BuiltinMethod = BuiltinMethod::Invert;
    const NAME: &'static str = "invert";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::invert_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `pick(...keys)` — restrict object to given keys.
pub(crate) struct Pick;
impl Builtin for Pick {
    const METHOD: BuiltinMethod = BuiltinMethod::Pick;
    const NAME: &'static str = "pick";
    fn spec() -> BuiltinSpec {
        object_simple_spec()
            .view_scalar()
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .element()
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::StrVec(keys) => { super::pick_apply(recv, keys) }
            _ => None,
        }
    }
}

/// `omit(...keys)` — drop given keys from object.
pub(crate) struct Omit;
impl Builtin for Omit {
    const METHOD: BuiltinMethod = BuiltinMethod::Omit;
    const NAME: &'static str = "omit";
    fn spec() -> BuiltinSpec {
        object_simple_spec()
            .view_scalar()
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .element()
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::StrVec(keys) => { super::omit_apply(recv, keys) }
            _ => None,
        }
    }
}

/// `merge(...objs)` — shallow merge objects.
pub(crate) struct Merge;
impl Builtin for Merge {
    const METHOD: BuiltinMethod = BuiltinMethod::Merge;
    const NAME: &'static str = "merge";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(other) => { super::merge_apply(recv, other) }
            _ => None,
        }
    }
}

/// `deep_merge(...objs)` — recursive merge.
pub(crate) struct DeepMerge;
impl Builtin for DeepMerge {
    const METHOD: BuiltinMethod = BuiltinMethod::DeepMerge;
    const NAME: &'static str = "deep_merge";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(other) => { super::deep_merge_apply(recv, other) }
            _ => None,
        }
    }
}

/// `defaults(...objs)` — fill-in defaults without overwriting.
pub(crate) struct Defaults;
impl Builtin for Defaults {
    const METHOD: BuiltinMethod = BuiltinMethod::Defaults;
    const NAME: &'static str = "defaults";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(other) => { super::defaults_apply(recv, other) }
            _ => None,
        }
    }
}

/// `rename({...})` — rename object keys.
pub(crate) struct Rename;
impl Builtin for Rename {
    const METHOD: BuiltinMethod = BuiltinMethod::Rename;
    const NAME: &'static str = "rename";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(other) => { super::rename_apply(recv, other) }
            _ => None,
        }
    }
}

/// `pivot(...)` — reshape object axes.
pub(crate) struct Pivot;
impl Builtin for Pivot {
    const METHOD: BuiltinMethod = BuiltinMethod::Pivot;
    const NAME: &'static str = "pivot";
    fn spec() -> BuiltinSpec { object_simple_spec() }
}

/// `implode(sep)` — array-to-string with separator.
pub(crate) struct Implode;
impl Builtin for Implode {
    const METHOD: BuiltinMethod = BuiltinMethod::Implode;
    const NAME: &'static str = "implode";
    fn spec() -> BuiltinSpec { object_simple_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(field) => { super::implode_apply(recv, field) }
            _ => None,
        }
    }
}

#[inline]
fn object_lambda_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Object, BuiltinCardinality::OneToOne)
        .pipeline_shape(BuiltinPipelineShape::new(
            BuiltinCardinality::OneToOne,
            true,
            1.0,
            1.0,
        ))
        .demand_law(BuiltinDemandLaw::MapLike)
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .lowering(BuiltinPipelineLowering::ExprArg)
}

/// `transform_keys(lam)` — map over keys of an object.
pub(crate) struct TransformKeys;
impl Builtin for TransformKeys {
    const METHOD: BuiltinMethod = BuiltinMethod::TransformKeys;
    const NAME: &'static str = "transform_keys";
    fn spec() -> BuiltinSpec { object_lambda_spec() }

    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        object_lambda_apply_stream(ctx, item, body)
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        object_lambda_apply_barrier(ctx, buf, body)
    }
}

/// Helper used by all ObjectLambda variants — single body shared across
/// TransformKeys / TransformValues / FilterKeys / FilterValues.
#[inline]
fn object_lambda_apply_stream(
    ctx: &mut super::builtin::StreamCtx<'_, '_>,
    item: crate::data::value::Val,
    body: Option<&crate::vm::Program>,
) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
    let prog = body.expect("object lambda body");
    let result = crate::exec::pipeline::materialized_exec::apply_lambda_obj(
        ctx.stage, &item, ctx.vm, ctx.env, ctx.kernel, prog,
    )?;
    Ok(crate::exec::pipeline::StageFlow::Continue(result))
}

/// Helper used by all ObjectLambda variants for barrier (whole-buffer) execution.
#[inline]
fn object_lambda_apply_barrier(
    ctx: &mut super::builtin::BarrierCtx<'_>,
    buf: &mut Vec<crate::data::value::Val>,
    body: Option<&crate::vm::Program>,
) -> Option<Result<(), crate::data::context::EvalError>> {
    let prog = body?;
    let mut out: Vec<crate::data::value::Val> = Vec::with_capacity(buf.len());
    for v in std::mem::take(buf) {
        match crate::exec::pipeline::materialized_exec::apply_lambda_obj(
            ctx.stage, &v, ctx.vm, ctx.env, ctx.kernel, prog,
        ) {
            Ok(mapped) => out.push(mapped),
            Err(err) => {
                *buf = out;
                return Some(Err(err));
            }
        }
    }
    *buf = out;
    Some(Ok(()))
}

/// `transform_values(lam)` — map over values of an object.
pub(crate) struct TransformValues;
impl Builtin for TransformValues {
    const METHOD: BuiltinMethod = BuiltinMethod::TransformValues;
    const NAME: &'static str = "transform_values";
    fn spec() -> BuiltinSpec { object_lambda_spec() }
    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        object_lambda_apply_stream(ctx, item, body)
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        object_lambda_apply_barrier(ctx, buf, body)
    }
}

/// `filter_keys(pred)` — drop entries by key predicate.
pub(crate) struct FilterKeys;
impl Builtin for FilterKeys {
    const METHOD: BuiltinMethod = BuiltinMethod::FilterKeys;
    const NAME: &'static str = "filter_keys";
    fn spec() -> BuiltinSpec { object_lambda_spec() }
    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        object_lambda_apply_stream(ctx, item, body)
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        object_lambda_apply_barrier(ctx, buf, body)
    }
}

/// `filter_values(pred)` — drop entries by value predicate.
pub(crate) struct FilterValues;
impl Builtin for FilterValues {
    const METHOD: BuiltinMethod = BuiltinMethod::FilterValues;
    const NAME: &'static str = "filter_values";
    fn spec() -> BuiltinSpec { object_lambda_spec() }
    #[inline]
    fn apply_stream(
        ctx: &mut super::builtin::StreamCtx<'_, '_>,
        item: crate::data::value::Val,
        body: Option<&crate::vm::Program>,
    ) -> Result<crate::exec::pipeline::StageFlow<crate::data::value::Val>, crate::data::context::EvalError> {
        object_lambda_apply_stream(ctx, item, body)
    }

    #[inline]
    fn apply_barrier(
        ctx: &mut super::builtin::BarrierCtx<'_>,
        buf: &mut Vec<crate::data::value::Val>,
        body: Option<&crate::vm::Program>,
    ) -> Option<Result<(), crate::data::context::EvalError>> {
        object_lambda_apply_barrier(ctx, buf, body)
    }
}

// ── Path operations ──────────────────────────────────────────────────────────

#[inline]
fn path_element_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Path, BuiltinCardinality::OneToOne)
        .indexed()
        .demand_law(BuiltinDemandLaw::MapLike)
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .element()
}

/// `get_path(path)` — navigate path lookup.
pub(crate) struct GetPath;
impl Builtin for GetPath {
    const METHOD: BuiltinMethod = BuiltinMethod::GetPath;
    const NAME: &'static str = "get_path";
    fn spec() -> BuiltinSpec { path_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::get_path_apply(recv, p) }
            super::BuiltinArgs::Path(path) => Some(super::get_path_impl(recv, path)),
            _ => None,
        }
    }
}

/// `del_path(path)` — remove value at path.
pub(crate) struct DelPath;
impl Builtin for DelPath {
    const METHOD: BuiltinMethod = BuiltinMethod::DelPath;
    const NAME: &'static str = "del_path";
    fn spec() -> BuiltinSpec { path_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::del_path_apply(recv, p) }
            _ => None,
        }
    }
}

/// `has_path(path)` — existence test.
pub(crate) struct HasPath;
impl Builtin for HasPath {
    const METHOD: BuiltinMethod = BuiltinMethod::HasPath;
    const NAME: &'static str = "has_path";
    fn spec() -> BuiltinSpec { path_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::has_path_apply(recv, p) }
            super::BuiltinArgs::Path(path) => Some(crate::data::value::Val::Bool(!super::get_path_impl(recv, path).is_null())),
            _ => None,
        }
    }
}

#[inline]
fn path_indexed_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Path, BuiltinCardinality::OneToOne).indexed()
}

/// `set_path(path, val)` — write value at path.
pub(crate) struct SetPath;
impl Builtin for SetPath {
    const METHOD: BuiltinMethod = BuiltinMethod::SetPath;
    const NAME: &'static str = "set_path";
    fn spec() -> BuiltinSpec { path_indexed_spec() }
}

/// `del_paths([...])` — bulk path removal.
pub(crate) struct DelPaths;
impl Builtin for DelPaths {
    const METHOD: BuiltinMethod = BuiltinMethod::DelPaths;
    const NAME: &'static str = "del_paths";
    fn spec() -> BuiltinSpec { path_indexed_spec() }
}

/// `flatten_keys` — flatten nested object into dotted keys.
pub(crate) struct FlattenKeys;
impl Builtin for FlattenKeys {
    const METHOD: BuiltinMethod = BuiltinMethod::FlattenKeys;
    const NAME: &'static str = "flatten_keys";
    fn spec() -> BuiltinSpec { path_indexed_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::flatten_keys_apply(recv, p) }
            _ => None,
        }
    }
}

/// `unflatten_keys` — invert `flatten_keys`.
pub(crate) struct UnflattenKeys;
impl Builtin for UnflattenKeys {
    const METHOD: BuiltinMethod = BuiltinMethod::UnflattenKeys;
    const NAME: &'static str = "unflatten_keys";
    fn spec() -> BuiltinSpec { path_indexed_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => { super::unflatten_keys_apply(recv, p) }
            _ => None,
        }
    }
}

// ── Deep operations ──────────────────────────────────────────────────────────

#[inline]
fn deep_simple_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Deep, BuiltinCardinality::Expanding).cost(20.0)
}

/// `walk(fn)` — post-order walk.
pub(crate) struct Walk;
impl Builtin for Walk {
    const METHOD: BuiltinMethod = BuiltinMethod::Walk;
    const NAME: &'static str = "walk";
    fn spec() -> BuiltinSpec { deep_simple_spec() }
}

/// `walk_pre(fn)` — pre-order walk.
pub(crate) struct WalkPre;
impl Builtin for WalkPre {
    const METHOD: BuiltinMethod = BuiltinMethod::WalkPre;
    const NAME: &'static str = "walk_pre";
    fn spec() -> BuiltinSpec { deep_simple_spec() }
}

/// `rec(fn)` — recursive descent map.
pub(crate) struct Rec;
impl Builtin for Rec {
    const METHOD: BuiltinMethod = BuiltinMethod::Rec;
    const NAME: &'static str = "rec";
    fn spec() -> BuiltinSpec { deep_simple_spec() }
}

/// `trace_path()` — collect all paths.
pub(crate) struct TracePath;
impl Builtin for TracePath {
    const METHOD: BuiltinMethod = BuiltinMethod::TracePath;
    const NAME: &'static str = "trace_path";
    fn spec() -> BuiltinSpec { deep_simple_spec() }
}

/// `deep_find(pred)` — descend and collect all matches.
pub(crate) struct DeepFind;
impl Builtin for DeepFind {
    const METHOD: BuiltinMethod = BuiltinMethod::DeepFind;
    const NAME: &'static str = "deep_find";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Deep, BuiltinCardinality::Expanding)
            .structural(BuiltinStructural::DeepFind)
            .cost(20.0)
    }
}

/// `deep_shape({...})` — descend and collect by shape.
pub(crate) struct DeepShape;
impl Builtin for DeepShape {
    const METHOD: BuiltinMethod = BuiltinMethod::DeepShape;
    const NAME: &'static str = "deep_shape";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Deep, BuiltinCardinality::Expanding)
            .structural(BuiltinStructural::DeepShape)
            .cost(20.0)
    }
}

/// `deep_like({...})` — descend and collect by literal match.
pub(crate) struct DeepLike;
impl Builtin for DeepLike {
    const METHOD: BuiltinMethod = BuiltinMethod::DeepLike;
    const NAME: &'static str = "deep_like";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Deep, BuiltinCardinality::Expanding)
            .structural(BuiltinStructural::DeepLike)
            .cost(20.0)
    }
}

// ── Serialization / relational / mutation ────────────────────────────────────

#[inline]
fn serialization_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Serialization, BuiltinCardinality::OneToOne)
        .indexed()
        .cost(20.0)
}

/// `to_csv(headers?)` — CSV serialiser. Optional header-array argument
/// drives explicit column ordering with the headers as the first row.
pub(crate) struct ToCsv;
impl Builtin for ToCsv {
    const METHOD: BuiltinMethod = BuiltinMethod::ToCsv;
    const NAME: &'static str = "to_csv";
    fn spec() -> BuiltinSpec { serialization_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::to_csv_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        if let super::BuiltinArgs::StrVec(headers) = args {
            return super::to_csv_with_headers_apply(recv, headers);
        }
        None
    }
}

/// `to_tsv(headers?)` — TSV serialiser. Same header semantics as `to_csv`.
pub(crate) struct ToTsv;
impl Builtin for ToTsv {
    const METHOD: BuiltinMethod = BuiltinMethod::ToTsv;
    const NAME: &'static str = "to_tsv";
    fn spec() -> BuiltinSpec { serialization_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::to_tsv_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        if let super::BuiltinArgs::StrVec(headers) = args {
            return super::to_tsv_with_headers_apply(recv, headers);
        }
        None
    }
}

/// `equi_join(left, right, on)` — relational join barrier.
pub(crate) struct EquiJoin;
impl Builtin for EquiJoin {
    const METHOD: BuiltinMethod = BuiltinMethod::EquiJoin;
    const NAME: &'static str = "equi_join";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Relational, BuiltinCardinality::Barrier).cost(20.0)
    }
}

/// `set(path, val)` — element-wise mutation.
pub(crate) struct Set;
impl Builtin for Set {
    const METHOD: BuiltinMethod = BuiltinMethod::Set;
    const NAME: &'static str = "set";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Mutation, BuiltinCardinality::OneToOne)
            .indexed()
            .element()
    }
    #[inline]
    fn apply_args(_recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(item.clone()),
            _ => None,
        }
    }
}

/// `update(path, fn)` — mutation via lambda.
pub(crate) struct Update;
impl Builtin for Update {
    const METHOD: BuiltinMethod = BuiltinMethod::Update;
    const NAME: &'static str = "update";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Mutation, BuiltinCardinality::OneToOne).indexed()
    }
}

// ── Streaming OneToOne (no lambda, indexed, element) ─────────────────────────

#[inline]
fn streaming_one_to_one_element_spec() -> BuiltinSpec {
    // `lag`/`lead`/`cummax`/`cummin`/`diff_window`/`pct_change`/`zscore`
    // and friends are whole-array transforms (output[i] depends on
    // input[i] and input[i-k]), not per-element vectorisable. Marking
    // them `.element()` made the streaming pipeline treat the receiver
    // as a 1-element stream and discard the structural shift, returning
    // the bare input. Same fix pattern as `enumerate`/`pairwise`.
    BuiltinSpec::new(BuiltinCategory::StreamingOneToOne, BuiltinCardinality::OneToOne)
        .indexed()
        .cost(10.0)
}

/// `lag(n)` — element shifted by N positions.
pub(crate) struct Lag;
impl Builtin for Lag {
    const METHOD: BuiltinMethod = BuiltinMethod::Lag;
    const NAME: &'static str = "lag";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::lag_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `lead(n)` — element shifted forward by N positions.
pub(crate) struct Lead;
impl Builtin for Lead {
    const METHOD: BuiltinMethod = BuiltinMethod::Lead;
    const NAME: &'static str = "lead";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => { super::lead_apply(recv, *n) }
            _ => None,
        }
    }
}

/// `diff_window(n)` — pairwise diff at lag N.
pub(crate) struct DiffWindow;
impl Builtin for DiffWindow {
    const METHOD: BuiltinMethod = BuiltinMethod::DiffWindow;
    const NAME: &'static str = "diff_window";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::None => { Some(super::diff_window_apply(recv).unwrap_or_else(|| recv.clone())) }
            _ => None,
        }
    }
}

/// `pct_change(n)` — pairwise relative change at lag N.
pub(crate) struct PctChange;
impl Builtin for PctChange {
    const METHOD: BuiltinMethod = BuiltinMethod::PctChange;
    const NAME: &'static str = "pct_change";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::None => { Some(super::pct_change_apply(recv).unwrap_or_else(|| recv.clone())) }
            _ => None,
        }
    }
}

/// `cummax()` — running maximum.
pub(crate) struct CumMax;
impl Builtin for CumMax {
    const METHOD: BuiltinMethod = BuiltinMethod::CumMax;
    const NAME: &'static str = "cummax";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::None => { Some(super::cummax_apply(recv).unwrap_or_else(|| recv.clone())) }
            _ => None,
        }
    }
}

/// `cummin()` — running minimum.
pub(crate) struct CumMin;
impl Builtin for CumMin {
    const METHOD: BuiltinMethod = BuiltinMethod::CumMin;
    const NAME: &'static str = "cummin";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::None => { Some(super::cummin_apply(recv).unwrap_or_else(|| recv.clone())) }
            _ => None,
        }
    }
}

/// `zscore()` — element standardised by mean/std.
pub(crate) struct Zscore;
impl Builtin for Zscore {
    const METHOD: BuiltinMethod = BuiltinMethod::Zscore;
    const NAME: &'static str = "zscore";
    fn spec() -> BuiltinSpec { streaming_one_to_one_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::None => { Some(super::zscore_apply(recv).unwrap_or_else(|| recv.clone())) }
            _ => None,
        }
    }
}

// ── Scalar element-only (basic) ──────────────────────────────────────────────

#[inline]
fn scalar_native_element_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
        .indexed()
        .view_native()
        .demand_law(BuiltinDemandLaw::MapLike)
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .element()
}

#[inline]
fn scalar_view_scalar_element_spec() -> BuiltinSpec {
    BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
        .indexed()
        .view_native()
        .view_scalar()
        .demand_law(BuiltinDemandLaw::MapLike)
        .order_effect(BuiltinPipelineOrderEffect::Preserves)
        .element()
}

// Native-element (no view_scalar):
// `apply` clause wraps with recv.clone() fallback so trait dispatch fully owns this method
// (no fall-through to legacy match on type mismatch).
macro_rules! scalar_native_element {
    ( $( $ty:ident => $variant:ident, $name:literal
         $( , aliases: [ $( $alias:literal ),* $(,)? ] )?
         $( , apply: $apply:ident )? ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$variant;
                const NAME: &'static str = $name;
                $( const ALIASES: &'static [&'static str] = &[ $( $alias ),* ]; )?
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                $(
                    #[inline]
                    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
                        Some(super::$apply(recv).unwrap_or_else(|| recv.clone()))
                    }
                )?
            }
        )*
    };
}

// View-scalar element:
macro_rules! scalar_view_scalar_element {
    ( $( $ty:ident => $variant:ident, $name:literal
         $( , aliases: [ $( $alias:literal ),* $(,)? ] )?
         $( , apply: $apply:ident )? ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$variant;
                const NAME: &'static str = $name;
                $( const ALIASES: &'static [&'static str] = &[ $( $alias ),* ]; )?
                fn spec() -> BuiltinSpec { scalar_view_scalar_element_spec() }
                $(
                    #[inline]
                    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
                        Some(super::$apply(recv).unwrap_or_else(|| recv.clone()))
                    }
                )?
            }
        )*
    };
}

scalar_native_element! {
    Capitalize => Capitalize, "capitalize", apply: capitalize_apply;
    TitleCase => TitleCase, "title_case", apply: title_case_apply;
    SnakeCase => SnakeCase, "snake_case", apply: snake_case_apply;
    KebabCase => KebabCase, "kebab_case", apply: kebab_case_apply;
    CamelCase => CamelCase, "camel_case", apply: camel_case_apply;
    PascalCase => PascalCase, "pascal_case", apply: pascal_case_apply;
    ParseFloat => ParseFloat, "parse_float", apply: parse_float_apply;
    ParseBool => ParseBool, "parse_bool", apply: parse_bool_apply;
    Schema => Schema, "schema", apply: schema_apply;
    Type => Type, "type", apply: type_name_apply;
    ToString => ToString, "to_string", apply: to_string_apply;
    ToJson => ToJson, "to_json", apply: to_json_apply;
    Dedent => Dedent, "dedent", apply: dedent_apply;
}

/// `parse_int(radix)` — string → integer with optional radix (2–36).
/// Strips a leading `0b` / `0x` for binary / hex when the radix matches,
/// so both `"0xff".parse_int(16)` and `"ff".parse_int(16)` produce 255.
/// No-arg form is base 10.
pub(crate) struct ParseInt;
impl Builtin for ParseInt {
    const METHOD: BuiltinMethod = BuiltinMethod::ParseInt;
    const NAME: &'static str = "parse_int";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::parse_int_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        // Radix arrives via the static-args decoder as `BuiltinArgs::Usize`
        // for a positive integer literal, or via `BuiltinArgs::I64` if
        // the parser took a different path. Anything else falls through
        // to the no-arg `apply_one` semantics (decoder hands us a base-10
        // parse).
        let radix: u32 = match args {
            super::BuiltinArgs::Usize(n) => *n as u32,
            super::BuiltinArgs::I64(n) if *n > 0 => *n as u32,
            super::BuiltinArgs::None => return None,
            _ => return None,
        };
        if !(2..=36).contains(&radix) {
            return Some(crate::data::value::Val::Null);
        }
        super::ops::string::map_str_val(recv, |s| {
            let cleaned = strip_radix_prefix(s.trim(), radix);
            i64::from_str_radix(cleaned, radix)
                .map(crate::data::value::Val::Int)
                .unwrap_or(crate::data::value::Val::Null)
        })
    }
}

#[inline]
fn strip_radix_prefix(s: &str, radix: u32) -> &str {
    match radix {
        16 => s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s),
        2 => s.strip_prefix("0b").or_else(|| s.strip_prefix("0B")).unwrap_or(s),
        8 => s.strip_prefix("0o").or_else(|| s.strip_prefix("0O")).unwrap_or(s),
        _ => s,
    }
}

scalar_view_scalar_element! {
    Ceil => Ceil, "ceil";
    Floor => Floor, "floor";
    Round => Round, "round";
    Abs => Abs, "abs";
    Upper => Upper, "upper", apply: upper_apply;
    Lower => Lower, "lower", apply: lower_apply;
    Trim => Trim, "trim", apply: trim_apply;
    TrimLeft => TrimLeft, "trim_left", aliases: ["lstrip"], apply: trim_left_apply;
    TrimRight => TrimRight, "trim_right", aliases: ["rstrip"], apply: trim_right_apply;
    IsBlank => IsBlank, "is_blank";
    IsNumeric => IsNumeric, "is_numeric";
    IsAlpha => IsAlpha, "is_alpha";
    IsAscii => IsAscii, "is_ascii";
    ToNumber => ToNumber, "to_number";
    ToBool => ToBool, "to_bool";
    StartsWith => StartsWith, "starts_with";
    EndsWith => EndsWith, "ends_with";
    IndexOf => IndexOf, "index_of";
    LastIndexOf => LastIndexOf, "last_index_of";
    Matches => Matches, "matches";
    ByteLen => ByteLen, "byte_len";
}

// ── Scalar with pipeline lowerings ───────────────────────────────────────────

/// `slice(start, end?)` — int-range scalar element with pipeline lowering.
pub(crate) struct Slice;
impl Builtin for Slice {
    const METHOD: BuiltinMethod = BuiltinMethod::Slice;
    const NAME: &'static str = "slice";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::OneToOne,
                true,
                1.0,
                1.0,
            ))
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .demand_law(BuiltinDemandLaw::Slice)
            .lowering(BuiltinPipelineLowering::IntRangeArg)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::I64Opt { first, second } => { Some(super::slice_apply(recv.clone(), *first, *second)) }
            _ => None,
        }
    }
}

/// `replace(needle, with)` — single-replace string-pair scalar.
pub(crate) struct Replace;
impl Builtin for Replace {
    const METHOD: BuiltinMethod = BuiltinMethod::Replace;
    const NAME: &'static str = "replace";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::OneToOne,
                true,
                2.0,
                1.0,
            ))
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .lowering(BuiltinPipelineLowering::StringPairArg)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::StrPair { first, second } => { super::replace_apply(recv.clone(), first, second, false) }
            _ => None,
        }
    }
}

/// `replace_all(needle, with)` — replace-all string-pair scalar.
pub(crate) struct ReplaceAll;
impl Builtin for ReplaceAll {
    const METHOD: BuiltinMethod = BuiltinMethod::ReplaceAll;
    const NAME: &'static str = "replace_all";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .pipeline_shape(BuiltinPipelineShape::new(
                BuiltinCardinality::OneToOne,
                true,
                2.0,
                1.0,
            ))
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .lowering(BuiltinPipelineLowering::StringPairArg)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::StrPair { first, second } => { super::replace_apply(recv.clone(), first, second, true) }
            _ => None,
        }
    }
}

/// `unknown` — sentinel for unrecognised methods (impure).
/// Canonical name uses angle brackets so it can never collide with user-callable names.
pub(crate) struct Unknown;
impl Builtin for Unknown {
    const METHOD: BuiltinMethod = BuiltinMethod::Unknown;
    const NAME: &'static str = "<unknown>";
    fn spec() -> BuiltinSpec {
        BuiltinSpec {
            pure: false,
            ..BuiltinSpec::new(BuiltinCategory::Unknown, BuiltinCardinality::OneToOne)
        }
    }
}

/// `rows()` — source-lifting marker used by stream planners.
///
/// Runtime row-local dispatch intentionally leaves the receiver unchanged; the
/// planner is responsible for recognizing root `$.rows()` as a stream boundary.
pub(crate) struct Rows;
impl Builtin for Rows {
    const METHOD: BuiltinMethod = BuiltinMethod::Rows;
    const NAME: &'static str = "rows";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Object, BuiltinCardinality::OneToOne)
            .stream_source()
            .never_unwrap()
    }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(recv.clone())
    }
}

// ── Wildcard-default methods now made explicit (so all methods have defs entries) ──

/// `from_json` — string → JSON value (default scalar element).
pub(crate) struct FromJson;
impl Builtin for FromJson {
    const METHOD: BuiltinMethod = BuiltinMethod::FromJson;
    const NAME: &'static str = "from_json";
    fn spec() -> BuiltinSpec { default_scalar_spec(BuiltinMethod::FromJson) }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::from_json_apply(recv).unwrap_or_else(|| recv.clone()))
    }
}

/// `includes(item)` / `contains(item)` — array membership scalar.
pub(crate) struct Includes;
impl Builtin for Includes {
    const METHOD: BuiltinMethod = BuiltinMethod::Includes;
    const NAME: &'static str = "includes";
    const ALIASES: &'static [&'static str] = &["contains"];
    fn spec() -> BuiltinSpec {
        default_scalar_spec(BuiltinMethod::Includes)
            .view_scalar()
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::includes_apply(recv, item)),
            _ => None,
        }
    }
}

/// `index(item)` — first index of element.
pub(crate) struct Index;
impl Builtin for Index {
    const METHOD: BuiltinMethod = BuiltinMethod::Index;
    const NAME: &'static str = "index";
    fn spec() -> BuiltinSpec {
        default_scalar_spec(BuiltinMethod::Index).lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::index_value_apply(recv, item).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

/// `indices_of(item)` — all indices of element.
pub(crate) struct IndicesOf;
impl Builtin for IndicesOf {
    const METHOD: BuiltinMethod = BuiltinMethod::IndicesOf;
    const NAME: &'static str = "indices_of";
    fn spec() -> BuiltinSpec {
        default_scalar_spec(BuiltinMethod::IndicesOf)
            .lowering(BuiltinPipelineLowering::TerminalSink)
    }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(item) => Some(super::indices_of_apply(recv, item).unwrap_or_else(|| recv.clone())),
            _ => None,
        }
    }
}

/// `missing(...keys)` — variadic key-existence audit. With one key,
/// returns `Bool(true)` iff the key is absent (legacy form). With one or
/// more keys passed as a string list, returns `Val::Arr<Str>` containing
/// the subset of keys that are absent or null. Empty input → `[]`; all
/// keys present → `[]`.
pub(crate) struct Missing;
impl Builtin for Missing {
    const METHOD: BuiltinMethod = BuiltinMethod::Missing;
    const NAME: &'static str = "missing";
    fn spec() -> BuiltinSpec {
        default_scalar_spec(BuiltinMethod::Missing)
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(key) => Some(super::missing_apply(recv, key)),
            super::BuiltinArgs::StrVec(keys) => Some(super::missing_many_apply(recv, keys)),
            _ => None,
        }
    }
}

/// Default scalar fallback used by methods that previously fell to the wildcard arm.
/// Mirrors the `_ => { ... }` body in legacy `BuiltinMethod::spec()`.
fn default_scalar_spec(method: BuiltinMethod) -> BuiltinSpec {
    let spec = BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
        .indexed()
        .view_native();
    if method.is_view_scalar_method() {
        spec.view_scalar()
    } else {
        spec
    }
}

// ── Cancellation-aware encode/decode pairs ───────────────────────────────────
// Each is a scalar element with the same spec body as `scalar_native_element_spec`
// but advertises an algebraic cancellation rule used by the optimizer to fuse
// adjacent inverse pairs (e.g. `to_base64(from_base64(x))` → identity).

/// `to_base64` — Forward base64 encode.
pub(crate) struct ToBase64;
impl Builtin for ToBase64 {
    const METHOD: BuiltinMethod = BuiltinMethod::ToBase64;
    const NAME: &'static str = "to_base64";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::to_base64_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Base64,
            side: BuiltinCancelSide::Forward,
        })
    }
}

/// `from_base64` — Inverse of `to_base64`.
pub(crate) struct FromBase64;
impl Builtin for FromBase64 {
    const METHOD: BuiltinMethod = BuiltinMethod::FromBase64;
    const NAME: &'static str = "from_base64";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::from_base64_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Base64,
            side: BuiltinCancelSide::Backward,
        })
    }
}

/// `url_encode` — Forward URL percent-encode.
pub(crate) struct UrlEncode;
impl Builtin for UrlEncode {
    const METHOD: BuiltinMethod = BuiltinMethod::UrlEncode;
    const NAME: &'static str = "url_encode";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::url_encode_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Url,
            side: BuiltinCancelSide::Forward,
        })
    }
}

/// `url_decode` — Inverse of `url_encode`.
pub(crate) struct UrlDecode;
impl Builtin for UrlDecode {
    const METHOD: BuiltinMethod = BuiltinMethod::UrlDecode;
    const NAME: &'static str = "url_decode";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::url_decode_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Url,
            side: BuiltinCancelSide::Backward,
        })
    }
}

/// `html_escape` — Forward HTML-entity escape.
pub(crate) struct HtmlEscape;
impl Builtin for HtmlEscape {
    const METHOD: BuiltinMethod = BuiltinMethod::HtmlEscape;
    const NAME: &'static str = "html_escape";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::html_escape_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Html,
            side: BuiltinCancelSide::Forward,
        })
    }
}

/// `html_unescape` — Inverse of `html_escape`.
pub(crate) struct HtmlUnescape;
impl Builtin for HtmlUnescape {
    const METHOD: BuiltinMethod = BuiltinMethod::HtmlUnescape;
    const NAME: &'static str = "html_unescape";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::html_unescape_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::Inverse {
            group: BuiltinCancelGroup::Html,
            side: BuiltinCancelSide::Backward,
        })
    }
}

/// `reverse_str` — Self-inverse string reversal (cancels with adjacent reverse_str).
pub(crate) struct ReverseStr;
impl Builtin for ReverseStr {
    const METHOD: BuiltinMethod = BuiltinMethod::ReverseStr;
    const NAME: &'static str = "reverse_str";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_one(recv: &crate::data::value::Val) -> Option<crate::data::value::Val> {
        Some(super::reverse_str_apply(recv).unwrap_or_else(|| recv.clone()))
    }
    #[inline]
    fn cancellation() -> Option<BuiltinCancellation> {
        Some(BuiltinCancellation::SelfInverse(BuiltinCancelGroup::Reverse))
    }
}

// ── Re-export Builtin trait constants used by cancellation impls (already imported above) ──

/// `or(default)` — coalesce: returns recv unless null/missing, else default.
pub(crate) struct Or;
impl Builtin for Or {
    const METHOD: BuiltinMethod = BuiltinMethod::Or;
    const NAME: &'static str = "or";
    fn spec() -> BuiltinSpec { scalar_native_element_spec() }
    #[inline]
    fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(default) => Some(super::or_apply(recv, default)),
            _ => None,
        }
    }
}

// ── Multi-arg scalar element methods (need apply_args) ──

macro_rules! str_arg_scalar_native {
    ( $( $ty:ident, $name:literal $( , aliases: [ $( $alias:literal ),* $(,)? ] )?, $apply:ident ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$ty;
                const NAME: &'static str = $name;
                $( const ALIASES: &'static [&'static str] = &[ $( $alias ),* ]; )?
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                #[inline]
                fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
                    match args {
                        super::BuiltinArgs::Str(p) => {
                            Some(super::$apply(recv, p).unwrap_or_else(|| recv.clone()))
                        }
                        _ => None,
                    }
                }
            }
        )*
    };
}

str_arg_scalar_native! {
    StripPrefix, "strip_prefix", strip_prefix_apply;
    StripSuffix, "strip_suffix", strip_suffix_apply;
    Scan, "scan", scan_apply;
    ReMatch, "re_match", re_match_apply;
    ReMatchFirst, "match_first", re_match_first_apply;
    ReMatchAll, "match_all", re_match_all_apply;
    ReCaptures, "captures", re_captures_apply;
}

/// `has(key)` — scalar membership test. Object: key existence. Array:
/// element-wise equality. String: substring. Returns `Val::Bool` always.
/// Spec is non-element so the pipeline does not wrap the boolean result
/// in a single-element array (was the cause of `$.o.has("a")` →
/// `[true]`).
pub(crate) struct Has;
impl Builtin for Has {
    const METHOD: BuiltinMethod = BuiltinMethod::Has;
    const NAME: &'static str = "has";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => super::has_apply(recv, p),
            super::BuiltinArgs::Val(v) => {
                let key = crate::util::val_to_key(v);
                super::has_apply(recv, &key)
            }
            _ => None,
        }
    }
}

/// `has_all([a, b, ...])` — every literal needle is present in the receiver.
pub(crate) struct HasAll;
impl Builtin for HasAll {
    const METHOD: BuiltinMethod = BuiltinMethod::HasAll;
    const NAME: &'static str = "has_all";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .element()
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Val(v) => super::has_all_apply(recv, v),
            super::BuiltinArgs::StrVec(keys) => super::has_all_keys_apply(recv, keys),
            _ => None,
        }
    }
}

/// `has_key(key)` — object key existence test with a view/tape-native backend.
pub(crate) struct HasKey;
impl Builtin for HasKey {
    const METHOD: BuiltinMethod = BuiltinMethod::HasKey;
    const NAME: &'static str = "has_key";
    fn spec() -> BuiltinSpec {
        BuiltinSpec::new(BuiltinCategory::Scalar, BuiltinCardinality::OneToOne)
            .indexed()
            .view_native()
            .view_scalar()
            .demand_law(BuiltinDemandLaw::MapLike)
            .order_effect(BuiltinPipelineOrderEffect::Preserves)
            .element()
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Str(p) => Some(super::has_key_apply(recv, p)),
            _ => None,
        }
    }
}

// ── More multi-arg scalar element methods ──

// Str-arg cases that extend the str_arg_scalar_native pattern.
str_arg_scalar_native! {
    ReCapturesAll, "captures_all", re_captures_all_apply;
    ReSplit, "split_re", re_split_apply;
}

macro_rules! str_vec_arg_scalar_native {
    ( $( $ty:ident, $name:literal, $apply:ident ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$ty;
                const NAME: &'static str = $name;
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                #[inline]
                fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
                    match args {
                        super::BuiltinArgs::StrVec(v) => {
                            Some(super::$apply(recv, v).unwrap_or_else(|| recv.clone()))
                        }
                        _ => None,
                    }
                }
            }
        )*
    };
}
str_vec_arg_scalar_native! {
    ContainsAny, "contains_any", contains_any_apply;
    ContainsAll, "contains_all", contains_all_apply;
}

macro_rules! usize_arg_scalar_native {
    ( $( $ty:ident, $name:literal, $apply:ident $( , aliases: [ $( $alias:literal ),* $(,)? ] )? ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$ty;
                const NAME: &'static str = $name;
                $( const ALIASES: &'static [&'static str] = &[ $( $alias ),* ]; )?
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                #[inline]
                fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
                    match args {
                        super::BuiltinArgs::Usize(n) => {
                            Some(super::$apply(recv, *n).unwrap_or_else(|| recv.clone()))
                        }
                        _ => None,
                    }
                }
            }
        )*
    };
}
usize_arg_scalar_native! {
    Repeat, "repeat", repeat_apply, aliases: ["repeat_str"];
}

/// `indent(n_or_prefix)` — prepend each line with `n` spaces (when `n` is a
/// non-negative integer) or with the literal `prefix` string (when a string
/// is supplied). Both forms preserve trailing-newline semantics of `lines()`.
pub(crate) struct Indent;
impl Builtin for Indent {
    const METHOD: BuiltinMethod = BuiltinMethod::Indent;
    const NAME: &'static str = "indent";
    fn spec() -> BuiltinSpec {
        scalar_native_element_spec()
    }
    #[inline]
    fn apply_args(
        recv: &crate::data::value::Val,
        args: &super::BuiltinArgs,
    ) -> Option<crate::data::value::Val> {
        match args {
            super::BuiltinArgs::Usize(n) => {
                Some(super::indent_apply(recv, *n).unwrap_or_else(|| recv.clone()))
            }
            super::BuiltinArgs::Str(prefix) => Some(
                super::indent_with_prefix_apply(recv, prefix.as_ref())
                    .unwrap_or_else(|| recv.clone()),
            ),
            _ => None,
        }
    }
}

macro_rules! pad_arg_scalar_native {
    ( $( $ty:ident, $name:literal, $apply:ident ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$ty;
                const NAME: &'static str = $name;
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                #[inline]
                fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
                    match args {
                        super::BuiltinArgs::Pad { width, fill } => {
                            Some(super::$apply(recv, *width, *fill).unwrap_or_else(|| recv.clone()))
                        }
                        _ => None,
                    }
                }
            }
        )*
    };
}
pad_arg_scalar_native! {
    PadLeft, "pad_left", pad_left_apply;
    PadRight, "pad_right", pad_right_apply;
    Center, "center", center_apply;
}

macro_rules! str_pair_scalar_native {
    ( $( $ty:ident, $name:literal, $apply:expr ; )* ) => {
        $(
            pub(crate) struct $ty;
            impl Builtin for $ty {
                const METHOD: BuiltinMethod = BuiltinMethod::$ty;
                const NAME: &'static str = $name;
                fn spec() -> BuiltinSpec { scalar_native_element_spec() }
                #[inline]
                fn apply_args(recv: &crate::data::value::Val, args: &super::BuiltinArgs) -> Option<crate::data::value::Val> {
                    match args {
                        super::BuiltinArgs::StrPair { first, second } => {
                            Some($apply(recv, first, second).unwrap_or_else(|| recv.clone()))
                        }
                        _ => None,
                    }
                }
            }
        )*
    };
}
str_pair_scalar_native! {
    ReReplace, "replace_re", super::re_replace_apply;
    ReReplaceAll, "replace_all_re", super::re_replace_all_apply;
}