miruscriptx 2.1.0

MiruScriptX: a complete, general-purpose scripting language written from scratch in Rust.
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
//! Native builtins that every program can call.
//!
//! Each builtin matches [`crate::value::BuiltinFn`]. Errors are returned as
//! plain strings; the virtual machine attaches the source line and column of
//! the call before surfacing them.

use std::cmp::Ordering;
use std::rc::Rc;

use crate::globals::Globals;
use crate::value::{
    Ambient, AmbientFn, Builtin, BuiltinFn, HostBuiltin, HostFn, Input, NativeFn, Output, System,
    SystemFn, Value,
};

/// Register every builtin into a program's globals.
pub fn register(globals: &mut Globals) {
    define(globals, "print", print);
    define(globals, "eprint", eprint);
    define(globals, "exit", exit);
    define(globals, "len", len);
    define(globals, "push", push);
    define(globals, "insert", insert);
    define(globals, "str", to_str);
    define(globals, "type", type_of);
    define(globals, "is_error", is_error);
    define(globals, "range", range);
    define(globals, "keys", keys);
    define(globals, "values", values);
    define(globals, "has", has);
    define(globals, "remove", remove);
    define(globals, "upper", upper);
    define(globals, "lower", lower);
    define(globals, "ord", ord);
    define(globals, "chr", chr);
    define(globals, "repeat", repeat);
    define(globals, "pad_left", pad_left);
    define(globals, "pad_right", pad_right);
    define(globals, "copy", copy);
    define(globals, "trim", trim);
    define(globals, "replace", replace);
    define(globals, "split", split);
    define(globals, "join", join);
    define(globals, "contains", contains);
    define(globals, "find", find);
    define(globals, "starts_with", starts_with);
    define(globals, "ends_with", ends_with);
    define(globals, "pop", pop);
    define(globals, "index_of", index_of);
    define(globals, "slice", slice);
    define(globals, "reverse", reverse);
    define(globals, "abs", abs);
    define(globals, "mod", modulo);
    define(globals, "min", min);
    define(globals, "max", max);
    define(globals, "floor", floor);
    define(globals, "ceil", ceil);
    define(globals, "round", round);
    define(globals, "sqrt", sqrt);
    define(globals, "pow", pow);
    define(globals, "sum", sum);
    define(globals, "product", product);
    define(globals, "int", int);
    define(globals, "float", float);
    define(globals, "input", input);
    define_system(globals, "read_file", read_file);
    define_system(globals, "write_file", write_file);
    define_system(globals, "file_exists", file_exists);
    define_system(globals, "args", args);
    define_ambient(globals, "now", now);
    define_ambient(globals, "sleep", sleep);
    define_ambient(globals, "random", random);
    define_ambient(globals, "random_int", random_int);
    define_ambient(globals, "seed", seed);
    define_ambient(globals, "read_key", read_key);
    define_ambient(globals, "key_ready", key_ready);
    define_ambient(globals, "clear", clear);
    define_ambient(globals, "move_to", move_to);
    define_ambient(globals, "hide_cursor", hide_cursor);
    define_ambient(globals, "show_cursor", show_cursor);
    define_ambient(globals, "term_size", term_size);
    define_host(globals, "sort", sort);
    define_host(globals, "map", map);
    define_host(globals, "filter", filter);
    define_host(globals, "reduce", reduce);
}

/// Whether a builtin may be handed a caught error.
///
/// Every other builtin refuses one, because passing an error on as though it
/// were a result is the mistake this milestone exists to prevent. Asking what
/// type a value is has to be the exception: it is how a program finds out that
/// it is holding an error in the first place, and a check that cannot be made
/// without tripping the guard is no check at all.
pub fn accepts_error(name: &str) -> bool {
    matches!(name, "type" | "is_error")
}

fn define(globals: &mut Globals, name: &'static str, func: BuiltinFn) {
    let slot = globals
        .slot_for_builtin(name)
        .expect("room for the builtins");
    let func = NativeFn::Plain(func);
    globals.define(slot, Value::Builtin(Builtin { name, func }));
}

/// Register a builtin that needs the host's file system or command line.
///
/// Called like any other builtin, and differing only in what it is handed,
/// which is why it is a kind of [`NativeFn`] rather than a kind of [`Value`].
fn define_system(globals: &mut Globals, name: &'static str, func: SystemFn) {
    let slot = globals
        .slot_for_builtin(name)
        .expect("room for the builtins");
    let func = NativeFn::System(func);
    globals.define(slot, Value::Builtin(Builtin { name, func }));
}

/// Register a builtin that reads something its arguments do not contain: the
/// clock, or the random number generator.
///
/// Called like any other builtin, as [`define_system`] is, and separate for the
/// same reason: what it is handed differs, and nothing else does.
fn define_ambient(globals: &mut Globals, name: &'static str, func: AmbientFn) {
    let slot = globals
        .slot_for_builtin(name)
        .expect("room for the builtins");
    let func = NativeFn::Ambient(func);
    globals.define(slot, Value::Builtin(Builtin { name, func }));
}

/// Register a higher-order builtin, one that receives the running engine so it
/// can apply a function argument.
fn define_host(globals: &mut Globals, name: &'static str, func: HostFn) {
    let slot = globals
        .slot_for_builtin(name)
        .expect("room for the builtins");
    globals.define(slot, Value::HostBuiltin(HostBuiltin { name, func }));
}

/// Refuse a builtin call that brought the wrong number of arguments.
///
/// The wording follows [`crate::value::Arity::describe`], which a user function
/// now uses, because a program should not be told `expects 1 argument` by one
/// and `expects 1 argument` by the other for the same mistake. `argument(s)`
/// is what a message says when nobody has decided between the two spellings.
fn check_arity(name: &str, args: &[Value], expected: usize) -> Result<(), String> {
    if args.len() == expected {
        Ok(())
    } else {
        let plural = if expected == 1 {
            "argument"
        } else {
            "arguments"
        };
        Err(format!(
            "{name} expects {expected} {plural} but got {}",
            args.len()
        ))
    }
}

/// `print(...)` writes its arguments separated by spaces, then a newline.
fn print(out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    let parts: Vec<String> = args.iter().map(Value::display).collect();
    out.write(&parts.join(" "));
    out.write("\n");
    Ok(Value::Nil)
}

/// `eprint(...)` is `print` to the diagnostic stream instead of the result
/// stream.
///
/// Deliberately the same in every other way: same separator, same trailing
/// newline, same acceptance of any number of arguments. A program that changes
/// `print` to `eprint` should change where the text goes and nothing else, so
/// there is one rule to learn rather than two.
///
/// This is what lets a script say something went wrong without putting it in
/// the output a caller is parsing. Until now the choice was to print a
/// complaint into the middle of the result, or to raise an error and say
/// nothing else at all.
fn eprint(out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    let parts: Vec<String> = args.iter().map(Value::display).collect();
    out.write_error(&parts.join(" "));
    out.write_error("\n");
    Ok(Value::Nil)
}

/// `exit(code)` stops the program and gives the code to whoever ran it.
///
/// This only asks. Stopping is done by returning an error, which unwinds the
/// way any other error does, and the virtual machine marks that error **fatal**
/// once a code has been recorded so a `try` cannot swallow it. Without that a
/// program would carry on running with an exit code already set, and the caller
/// would be told a lie about a program that never stopped.
///
/// The message below is not normally seen: whoever runs the program reads the
/// code first and reports nothing. It is written to be honest for the one case
/// where it does surface, an embedder calling [`crate::vm::Vm::run`] directly
/// and never asking for the code.
///
/// **0 through 255.** That is what a process may return on the platforms this
/// runs on; 256 is not a smaller number than 255 to an operating system, it is
/// zero, and a program silently reporting success because it asked for 256 is
/// the worst answer available. So it is refused, and the range is in section 9
/// of the specification with the other limits.
fn exit(out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("exit", &args, 1)?;
    let code = match &args[0] {
        Value::Int(n) => *n,
        other => {
            return Err(format!(
                "exit expects an int but got a {}",
                other.type_name()
            ))
        }
    };
    if !(0..=255).contains(&code) {
        return Err(format!("exit code must be from 0 to 255 but got {code}"));
    }
    out.request_exit(code as i32);
    Err("the program called exit".to_string())
}

/// `len(value)` returns the length of a string, array, or map.
fn len(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("len", &args, 1)?;
    match &args[0] {
        Value::Str(s) => Ok(Value::Int(s.chars().count() as i64)),
        Value::Array(items) => Ok(Value::Int(items.borrow().len() as i64)),
        Value::Map(entries) => Ok(Value::Int(entries.borrow().len() as i64)),
        other => Err(format!(
            "len expects a string, array, or map but got a {}",
            other.type_name()
        )),
    }
}

/// `push(array, value)` appends to an array in place and returns the array.
fn push(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("push", &args, 2)?;
    match &args[0] {
        Value::Array(items) => {
            items.borrow_mut().push(args[1].clone());
            Ok(args[0].clone())
        }
        other => Err(format!(
            "push expects an array as its first argument but got a {}",
            other.type_name()
        )),
    }
}

/// `insert(array, index, value)` puts a value at a position, in place, and
/// returns the array.
///
/// The companion of `push`, which can only append. Putting something at the
/// front is the common case (a queue, or the new head of a snake), and without
/// this it takes a fresh array and a loop.
///
/// **The index must be from 0 to the length, and anything else is an error.**
/// `insert(a, len(a), v)` appends, which is the one past-the-end position that
/// means something: it is where a new last element goes.
///
/// This follows indexing rather than `slice`. `slice` clamps, because a range
/// asking for more than exists can sensibly give what exists. A position is not
/// a range: `insert(a, 99, v)` on an array of three is a mistake in the caller's
/// arithmetic, and quietly appending would hide it. `a[99]` is an error for the
/// same reason, and the message here is shaped like that one.
fn insert(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("insert", &args, 3)?;
    let index = match &args[1] {
        Value::Int(n) => *n,
        other => {
            return Err(format!(
                "insert expects an integer index but got a {}",
                other.type_name()
            ))
        }
    };
    match &args[0] {
        Value::Array(items) => {
            let mut items = items.borrow_mut();
            let len = items.len();
            // One past the end is allowed and appends, which is what makes
            // `insert(a, len(a), v)` the same as `push`. A negative index counts
            // back from the end, so `insert(a, -1, v)` puts the new element
            // where `a[-1]` is and pushes the last one along. That is the
            // reading that agrees with `[]`: both give `-1` the same element.
            //
            // `resolve_index` is not used here because its range stops at
            // `len - 1`, and inserting has one more legal position than
            // indexing does.
            let at = if index < 0 { index + len as i64 } else { index };
            if at < 0 || at > len as i64 {
                return Err(format!(
                    "index {index} is out of range for inserting into an array of length {len}"
                ));
            }
            items.insert(at as usize, args[2].clone());
            drop(items);
            Ok(args[0].clone())
        }
        other => Err(format!(
            "insert expects an array as its first argument but got a {}",
            other.type_name()
        )),
    }
}

/// `str(value)` converts any value to its display string.
fn to_str(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("str", &args, 1)?;
    Ok(Value::Str(Rc::new(args[0].display())))
}

/// `type(value)` returns the name of a value's type.
fn type_of(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("type", &args, 1)?;
    Ok(Value::Str(Rc::new(args[0].type_name().to_string())))
}

/// Whether a value is an error caught by `try`.
///
/// `type(v) == "error"` says the same thing and needed no builtin, but it puts
/// the check that decides whether a program is about to misuse a value behind a
/// string comparison a typo can silently break. This cannot be misspelled
/// without failing outright.
fn is_error(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("is_error", &args, 1)?;
    Ok(Value::Bool(matches!(args[0], Value::Error(_))))
}

/// `range(end)` or `range(start, end)` returns an array of integers in the
/// half-open interval, so the end value is not included.
fn range(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    let (start, end, step) = match args.as_slice() {
        [Value::Int(end)] => (0i64, *end, 1i64),
        [Value::Int(start), Value::Int(end)] => (*start, *end, 1),
        [Value::Int(start), Value::Int(end), Value::Int(step)] => (*start, *end, *step),
        [_] | [_, _] | [_, _, _] => return Err("range expects integer arguments".to_string()),
        _ => {
            return Err(format!(
                "range expects 1 to 3 arguments but got {}",
                args.len()
            ))
        }
    };
    // A loop that never ends, so it is refused rather than run. Naming it beats
    // letting the program hang with nothing to read.
    if step == 0 {
        return Err("range expects a step that is not 0".to_string());
    }
    let mut items = Vec::new();
    let mut current = start;
    // **A step whose sign disagrees with the bounds gives an empty array, not
    // an error.** `range(5, 0)` is empty in every release since the builtin
    // existed, and section 2.3 does not let that become an error now. The same
    // rule then has to cover `range(0, 10, -1)`, which is the same disagreement
    // written a second way.
    if step > 0 {
        while current < end {
            items.push(Value::Int(current));
            // Saturating rather than wrapping: a step that runs off the end of
            // the integers stops the loop instead of turning it back on itself.
            current = current.saturating_add(step);
        }
    } else {
        while current > end {
            items.push(Value::Int(current));
            current = current.saturating_add(step);
        }
    }
    Ok(Value::array(items))
}

/// `keys(map)` returns an array of the map's keys, in sorted order.
fn keys(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("keys", &args, 1)?;
    match &args[0] {
        Value::Map(entries) => {
            let items: Vec<Value> = entries
                .borrow()
                .keys()
                .map(|key| Value::Str(Rc::new(key.clone())))
                .collect();
            Ok(Value::array(items))
        }
        other => Err(format!(
            "keys expects a map but got a {}",
            other.type_name()
        )),
    }
}

/// `values(map)` returns an array of the map's values, in key order.
fn values(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("values", &args, 1)?;
    match &args[0] {
        Value::Map(entries) => {
            let items: Vec<Value> = entries.borrow().values().cloned().collect();
            Ok(Value::array(items))
        }
        other => Err(format!(
            "values expects a map but got a {}",
            other.type_name()
        )),
    }
}

/// `has(map, key)` reports whether the map contains the given string key.
fn has(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("has", &args, 2)?;
    let key = match &args[1] {
        Value::Str(s) => s.to_string(),
        other => {
            return Err(format!(
                "has expects a string key but got a {}",
                other.type_name()
            ))
        }
    };
    match &args[0] {
        Value::Map(entries) => Ok(Value::Bool(entries.borrow().contains_key(&key))),
        other => Err(format!("has expects a map but got a {}", other.type_name())),
    }
}

/// `remove(map, key)` takes the key out of the map and gives the value it held,
/// or `nil` when the map held no such key.
///
/// This is the inverse of assignment, which a map had no way to undo. Setting a
/// key to `nil` does not remove it: the key stays, `len` still counts it, and
/// `keys` still lists it. Arrays have had `pop` since v0.2 and maps had
/// nothing, so a program that built a map could not filter one without
/// rebuilding it by hand.
///
/// **An absent key gives `nil` rather than an error**, which is how reading one
/// already behaves: `m["absent"]` is `nil` and not a failure. That makes
/// "remove it if it is there" one call instead of a `has` and then a `remove`,
/// which is the shape most programs want.
///
/// The cost is real and is written down in the specification: a key holding
/// `nil` and a key that is not there give the same answer. `has(map, key)`
/// tells them apart, and it has to be asked before the removal rather than
/// after.
///
/// The key is borrowed rather than copied into a `String`. `BTreeMap` keyed by
/// `String` accepts a `&str` through `Borrow`, which is the same allocation
/// v1.1 removed from reading a map.
fn remove(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("remove", &args, 2)?;
    let key = match &args[1] {
        Value::Str(s) => s.as_str(),
        other => {
            return Err(format!(
                "remove expects a string key but got a {}",
                other.type_name()
            ))
        }
    };
    match &args[0] {
        Value::Map(entries) => Ok(entries.borrow_mut().remove(key).unwrap_or(Value::Nil)),
        other => Err(format!(
            "remove expects a map but got a {}",
            other.type_name()
        )),
    }
}

/// `upper(s)` returns the string with every letter upper-cased.
fn upper(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("upper", &args, 1)?;
    match &args[0] {
        Value::Str(s) => Ok(Value::Str(Rc::new(s.to_uppercase()))),
        other => Err(format!(
            "upper expects a string but got a {}",
            other.type_name()
        )),
    }
}

/// `copy(v)` gives a value that shares nothing with `v` at the top level.
///
/// **Arrays and maps are shared when they are assigned.** `let b = a` makes
/// both names reach one array, so `b[0] = 99` changes `a`. That is the value
/// model and not a defect; what was missing is a way to ask for the other
/// thing. `examples/tetris.miru` had to write `slice(row, 0, width)` to get it,
/// which is a copy spelled as a slice and needs the width in scope to say.
///
/// **Shallow, and named so it cannot be read as deep.** A grid is an array of
/// arrays, and copying one shallowly shares every row, so `map(grid, copy)` is
/// the documented way to copy that, and the golden corpus pins it. A deep form
/// can be added later under section 2.3; a shallow `copy` that later started
/// copying deeply could not, because that would change what a builtin does. A
/// naive deep copy also has to answer what happens to a value that holds
/// itself, which is the class of defect v1.0 spent a milestone closing.
fn copy(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("copy", &args, 1)?;
    Ok(match &args[0] {
        Value::Array(items) => Value::array(items.borrow().clone()),
        Value::Map(entries) => Value::map(entries.borrow().clone()),
        // Everything else is already a value rather than a handle: two names
        // holding the same string cannot observe each other, because nothing
        // can change one in place. Returning it is the copy.
        other => other.clone(),
    })
}

/// `repeat(s, n)` gives `s` written `n` times.
///
/// `examples/dice.miru` had a six-line function that did only this, and any
/// program printing a rule, a bar, or an indent wrote the same loop again. It
/// also allocates once where the loop built a new string per turn.
fn repeat(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("repeat", &args, 2)?;
    let Value::Str(s) = &args[0] else {
        return Err(format!(
            "repeat expects a string but got a {}",
            args[0].type_name()
        ));
    };
    let Value::Int(count) = &args[1] else {
        return Err(format!(
            "repeat expects an int count but got a {}",
            args[1].type_name()
        ));
    };
    // Zero gives the empty string, which is what the hand-written loop did and
    // is worth keeping: a builtin that refused zero would be a step back for
    // every caller whose count is computed.
    if *count < 0 {
        return Err(format!(
            "repeat expects a count of 0 or more but got {count}"
        ));
    }
    let times =
        usize::try_from(*count).map_err(|_| format!("repeat count {count} is too large"))?;
    // Refuse a result too large to build rather than aborting on the
    // allocation, in the shape section 5.2 uses for integer overflow.
    s.chars()
        .count()
        .checked_mul(times)
        .filter(|size| *size <= MAX_REPEAT_CHARACTERS)
        .ok_or_else(|| {
            format!("repeat would build a string longer than {MAX_REPEAT_CHARACTERS} characters")
        })?;
    Ok(Value::Str(Rc::new(s.repeat(times))))
}

/// The longest string `repeat`, `pad_left` and `pad_right` will build, so a
/// wrong count fails with a sentence rather than by exhausting memory.
///
/// Ten million characters is far past any rule, bar, or indent a program has a
/// reason to draw, and small enough that the refusal arrives immediately.
/// **Section 3.2 of the stability guarantee leaves this number free**, so it
/// can rise later without breaking a promise.
const MAX_REPEAT_CHARACTERS: usize = 10_000_000;

/// Fill `s` out to `width` characters, putting the fill on the given side.
///
/// Shared by `pad_left` and `pad_right`, which differ only in where the fill
/// goes.
fn pad_to(name: &str, args: &[Value], on_the_left: bool) -> Result<Value, String> {
    if args.len() != 2 && args.len() != 3 {
        return Err(format!(
            "{name} expects 2 or 3 arguments but got {}",
            args.len()
        ));
    }
    let Value::Str(s) = &args[0] else {
        return Err(format!(
            "{name} expects a string but got a {}",
            args[0].type_name()
        ));
    };
    let Value::Int(width) = &args[1] else {
        return Err(format!(
            "{name} expects an int width but got a {}",
            args[1].type_name()
        ));
    };
    if *width < 0 {
        return Err(format!(
            "{name} expects a width of 0 or more but got {width}"
        ));
    }
    // Exactly one character. A fill of several would overshoot the width or
    // need a rule about cutting it, and neither is worth having.
    let fill = match args.get(2) {
        None => ' ',
        Some(Value::Str(f)) => {
            let mut chars = f.chars();
            match (chars.next(), chars.next()) {
                (Some(only), None) => only,
                _ => {
                    return Err(format!(
                        "{name} expects a fill of one character but got one of {}",
                        f.chars().count()
                    ))
                }
            }
        }
        Some(other) => {
            return Err(format!(
                "{name} expects a string fill but got a {}",
                other.type_name()
            ))
        }
    };

    // Characters, not bytes, so a table holding anything outside ASCII still
    // lines up. Measuring in bytes is what makes a naive implementation wrong
    // in exactly the case padding exists to handle.
    let have = s.chars().count();
    let want = *width as usize;
    // Already long enough: unchanged rather than cut. Losing text to make a
    // column line up is a worse failure than a ragged column, and a caller who
    // wants it cut has `slice`.
    if have >= want {
        return Ok(Value::Str(Rc::new(s.to_string())));
    }
    // The same limit `repeat` has, for the same reason and in the same words.
    // Both build a run of one character; `repeat` refused a wrong count with a
    // sentence and this had no refusal path at all, so
    // `pad_left("", 9223372036854775807)` was a program asking for the process
    // to die in a way it could not see. Section 2.6 of the guarantee says that
    // does not happen.
    if want > MAX_REPEAT_CHARACTERS {
        return Err(format!(
            "{name} would build a string longer than {MAX_REPEAT_CHARACTERS} characters"
        ));
    }
    let fill: String = std::iter::repeat_n(fill, want - have).collect();
    let padded = if on_the_left {
        fill + s.as_str()
    } else {
        s.to_string() + &fill
    };
    Ok(Value::Str(Rc::new(padded)))
}

/// `pad_left(s, width, fill)` puts the fill on the **left**, which lines the
/// text up on the right. Use it for numbers in a column.
fn pad_left(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    pad_to("pad_left", &args, true)
}

/// `pad_right(s, width, fill)` puts the fill on the **right**, which lines the
/// text up on the left. Use it for words in a column.
fn pad_right(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    pad_to("pad_right", &args, false)
}

/// `ord(s)` gives the code point of a one-character string.
///
/// **Exactly one character, not the first of several.** Python's `ord` refuses
/// a longer string and JavaScript's `charCodeAt` takes the first; refusing is
/// what matches this project, where `term_size` refuses rather than inventing
/// a width and `sqrt` refuses rather than returning `nan`. `ord("hello")`
/// quietly meaning 104 is a bug that runs.
///
/// Characters, not bytes, like everything else here, so this is the code point
/// and not the first of the four bytes an emoji is stored in.
fn ord(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("ord", &args, 1)?;
    match &args[0] {
        Value::Str(s) => {
            let mut chars = s.chars();
            match (chars.next(), chars.next()) {
                (Some(only), None) => Ok(Value::Int(only as i64)),
                // Counted rather than described, so the message says which
                // mistake was made: an empty string and a whole word are
                // different errors with the same cause.
                _ => Err(format!(
                    "ord expects a string of one character but got one of {}",
                    s.chars().count()
                )),
            }
        }
        other => Err(format!(
            "ord expects a string but got a {}",
            other.type_name()
        )),
    }
}

/// `chr(n)` gives the one-character string for a code point.
///
/// **The refusals are the `\u{...}` escape's, because they are the same
/// question.** `char::from_u32` is what the lexer consults at `read_unicode_
/// escape`, and it is the whole rule: everything above `10FFFF` is refused,
/// and so is a surrogate from `D800` to `DFFF`. Calling it here rather than
/// writing a second range check is what keeps the two from drifting apart, and
/// the message is the escape's word for word, so `chr(0xD800)` and
/// `"\u{D800}"` do not read as two different problems.
///
/// `chr(ord(c)) == c` for every character the language admits, which is the
/// property the golden corpus pins.
fn chr(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("chr", &args, 1)?;
    let Value::Int(n) = &args[0] else {
        return Err(format!(
            "chr expects an int but got a {}",
            args[0].type_name()
        ));
    };
    // Spelled in hex, matching the escape this agrees with, even though the
    // argument is usually written in decimal. A number too big or too small to
    // be a code point at all is reported as itself instead: rendering -1 in
    // hex gives '\u{FFFFFFFFFFFFFFFF}', which describes the bits rather than
    // the mistake.
    let refuse = || match u32::try_from(*n) {
        Ok(code) => format!("'\\u{{{code:X}}}' is not a character"),
        Err(_) => format!("{n} is not a character"),
    };
    let code = u32::try_from(*n).map_err(|_| refuse())?;
    match char::from_u32(code) {
        Some(found) => Ok(Value::Str(Rc::new(found.to_string()))),
        None => Err(refuse()),
    }
}

/// `lower(s)` returns the string with every letter lower-cased.
fn lower(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("lower", &args, 1)?;
    match &args[0] {
        Value::Str(s) => Ok(Value::Str(Rc::new(s.to_lowercase()))),
        other => Err(format!(
            "lower expects a string but got a {}",
            other.type_name()
        )),
    }
}

/// `trim(s)` returns the string with leading and trailing whitespace removed.
fn trim(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("trim", &args, 1)?;
    match &args[0] {
        Value::Str(s) => Ok(Value::Str(Rc::new(s.trim().to_string()))),
        other => Err(format!(
            "trim expects a string but got a {}",
            other.type_name()
        )),
    }
}

/// `replace(s, from, to)` returns `s` with every occurrence of `from` replaced
/// by `to`.
fn replace(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("replace", &args, 3)?;
    match (&args[0], &args[1], &args[2]) {
        (Value::Str(s), Value::Str(from), Value::Str(to)) => {
            Ok(Value::Str(Rc::new(s.replace(from.as_str(), to.as_str()))))
        }
        _ => Err("replace expects three string arguments".to_string()),
    }
}

/// `split(s, sep)` returns an array of the pieces of `s` between each `sep`.
/// An empty separator splits the string into its individual characters.
fn split(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("split", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Str(s), Value::Str(sep)) => {
            let parts: Vec<Value> = if sep.is_empty() {
                s.chars()
                    .map(|c| Value::Str(Rc::new(c.to_string())))
                    .collect()
            } else {
                s.split(sep.as_str())
                    .map(|part| Value::Str(Rc::new(part.to_string())))
                    .collect()
            };
            Ok(Value::array(parts))
        }
        _ => Err("split expects two string arguments".to_string()),
    }
}

/// `join(array, sep)` returns the array's elements, displayed and joined by
/// `sep` into a single string.
fn join(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("join", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Array(items), Value::Str(sep)) => {
            let parts: Vec<String> = items.borrow().iter().map(Value::display).collect();
            Ok(Value::Str(Rc::new(parts.join(sep.as_str()))))
        }
        _ => Err("join expects an array and a string separator".to_string()),
    }
}

/// `contains(seq, value)` reports whether a string contains a substring or an
/// array contains an element equal to `value`.
fn contains(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("contains", &args, 2)?;
    match &args[0] {
        Value::Str(s) => match &args[1] {
            Value::Str(sub) => Ok(Value::Bool(s.contains(sub.as_str()))),
            other => Err(format!(
                "contains on a string expects a string but got a {}",
                other.type_name()
            )),
        },
        Value::Array(items) => Ok(Value::Bool({
            let items = items.borrow();
            let mut found = false;
            for item in items.iter() {
                if item.equals(&args[1])? {
                    found = true;
                    break;
                }
            }
            found
        })),
        other => Err(format!(
            "contains expects a string or array but got a {}",
            other.type_name()
        )),
    }
}

/// `find(s, sub)` returns the character index of the first `sub` in `s`, or -1
/// when it is not present.
fn find(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("find", &args, 2)?;
    match (&args[0], &args[1]) {
        // `nil` for "not here", not `-1`. Version 1 answered `-1` because a
        // negative index could not name an element, so no confusion was
        // possible. Now that `-1` is the last element, `s[find(s, x)]` would
        // give the last character of a string that does not contain `x`: a
        // wrong answer where there used to be an error. The two changes had to
        // ship together or this release would have shipped a trap.
        (Value::Str(s), Value::Str(sub)) => Ok(match s.find(sub.as_str()) {
            Some(byte_index) => Value::Int(s[..byte_index].chars().count() as i64),
            None => Value::Nil,
        }),
        _ => Err("find expects two string arguments".to_string()),
    }
}

/// `starts_with(s, prefix)` reports whether `s` begins with `prefix`.
///
/// The comparison is by byte, which is not a way around the rule that every
/// string builtin here counts characters. UTF-8 is self synchronising and both
/// arguments are whole strings, so a needle that matches the leading bytes
/// matches the leading characters as well: a byte prefix cannot stop part way
/// through one. `find` counts because it gives back an index. This gives back
/// yes or no, and there the two measures agree.
fn starts_with(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("starts_with", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Str(s), Value::Str(prefix)) => Ok(Value::Bool(s.starts_with(prefix.as_str()))),
        _ => Err("starts_with expects two string arguments".to_string()),
    }
}

/// `ends_with(s, suffix)` reports whether `s` ends with `suffix`.
///
/// [`starts_with`] gives the reason a byte comparison answers a question about
/// characters. It holds at the end of a string for the same reason it holds at
/// the start.
fn ends_with(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("ends_with", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Str(s), Value::Str(suffix)) => Ok(Value::Bool(s.ends_with(suffix.as_str()))),
        _ => Err("ends_with expects two string arguments".to_string()),
    }
}

/// `pop(array)` removes and returns the last element; an empty array is an error.
fn pop(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("pop", &args, 1)?;
    match &args[0] {
        Value::Array(items) => items
            .borrow_mut()
            .pop()
            .ok_or_else(|| "pop from an empty array".to_string()),
        other => Err(format!(
            "pop expects an array but got a {}",
            other.type_name()
        )),
    }
}

/// `index_of(array, value)` returns the index of the first element equal to
/// `value`, or -1 when there is none.
fn index_of(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("index_of", &args, 2)?;
    match &args[0] {
        Value::Array(items) => {
            // A loop rather than `position`, because a comparison can now refuse
            // and a closure cannot carry that out of an iterator adaptor. The
            // refusal has to travel: swallowing it would answer "not present",
            // which is the wrong answer rather than no answer.
            let items = items.borrow();
            for (index, item) in items.iter().enumerate() {
                if item.equals(&args[1])? {
                    return Ok(Value::Int(index as i64));
                }
            }
            // `nil`, not `-1`. See `find`: since this release `-1` is the last
            // element, so `a[index_of(a, missing)]` would answer with it.
            Ok(Value::Nil)
        }
        other => Err(format!(
            "index_of expects an array but got a {}",
            other.type_name()
        )),
    }
}

/// Resolve a half-open `[start, end)` range, counting a negative bound from the
/// end, then clamp it to `0..=len` keeping `end >= start`.
///
/// **`slice` clamps where `[]` refuses, and that difference is deliberate.**
/// An index names one element and getting it wrong is a mistake worth stopping
/// for. A slice names a stretch, and asking for more than there is usually
/// means "as much as you have": `slice(a, 0, n)` should give what it can rather
/// than refuse because the array was short. So this does not use
/// [`crate::ops::resolve_index`], which refuses; it borrows only its rule for
/// what a negative bound means, and the two must not drift apart.
///
/// A bound that is still negative after counting back clamps to 0, so
/// `slice(a, -100, 2)` on three elements is the first two rather than an error.
fn clamp_range(start: i64, end: i64, len: usize) -> (usize, usize) {
    let len = len as i64;
    let from_end = |n: i64| if n < 0 { n.saturating_add(len) } else { n };
    let lo = from_end(start).clamp(0, len) as usize;
    let hi = from_end(end).clamp(0, len) as usize;
    (lo, hi.max(lo))
}

/// `slice(seq, start, end)` returns the half-open `[start, end)` slice of an
/// array or string. Indices are character based for strings and are clamped to
/// the sequence bounds.
fn slice(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("slice", &args, 3)?;
    let start = match &args[1] {
        Value::Int(n) => *n,
        other => {
            return Err(format!(
                "slice expects an integer start but got a {}",
                other.type_name()
            ))
        }
    };
    let end = match &args[2] {
        Value::Int(n) => *n,
        other => {
            return Err(format!(
                "slice expects an integer end but got a {}",
                other.type_name()
            ))
        }
    };
    match &args[0] {
        Value::Array(items) => {
            let items = items.borrow();
            let (lo, hi) = clamp_range(start, end, items.len());
            Ok(Value::array(items[lo..hi].to_vec()))
        }
        Value::Str(s) => {
            let chars: Vec<char> = s.chars().collect();
            let (lo, hi) = clamp_range(start, end, chars.len());
            Ok(Value::Str(Rc::new(chars[lo..hi].iter().collect())))
        }
        other => Err(format!(
            "slice expects an array or string but got a {}",
            other.type_name()
        )),
    }
}

/// The numeric value of an int or float, for ordering. Non-numbers map to 0.
fn number_as_f64(value: &Value) -> f64 {
    match value {
        Value::Int(n) => *n as f64,
        Value::Float(f) => *f,
        _ => 0.0,
    }
}

/// How a set of values is ordered, decided once by looking at all of them.
///
/// Extracted so that the two forms of `sort` cannot come to disagree. Both ask
/// this same question: `sort(a)` asks it about the elements and `sort(a, key)`
/// asks it about the keys. Two copies of this decision is how one form would
/// end up refusing `NaN` while the other quietly ordered it.
#[derive(Clone, Copy)]
enum Ordered {
    Ints,
    Strings,
    /// A mix of integers and floats, compared as floats. Section 5.2 of the
    /// specification gives the promotion rule this follows.
    Numbers,
}

impl Ordered {
    /// Decide how to order these values, or say why they cannot be ordered.
    fn of(values: &[Value]) -> Result<Ordered, String> {
        if values.iter().all(|v| matches!(v, Value::Int(_))) {
            Ok(Ordered::Ints)
        } else if values.iter().all(|v| matches!(v, Value::Str(_))) {
            Ok(Ordered::Strings)
        } else if values
            .iter()
            .all(|v| matches!(v, Value::Int(_) | Value::Float(_)))
        {
            // NaN is refused rather than ordered arbitrarily. It compares equal
            // to nothing, including itself, so a sort that admitted it would
            // give a different arrangement depending on where it started.
            if values
                .iter()
                .any(|v| matches!(v, Value::Float(f) if f.is_nan()))
            {
                Err("sort cannot order NaN".to_string())
            } else {
                Ok(Ordered::Numbers)
            }
        } else {
            Err("sort expects an array of all numbers or all strings".to_string())
        }
    }

    fn compare(self, a: &Value, b: &Value) -> Ordering {
        match (self, a, b) {
            (Ordered::Ints, Value::Int(x), Value::Int(y)) => x.cmp(y),
            (Ordered::Strings, Value::Str(x), Value::Str(y)) => x.cmp(y),
            // `of` has already refused NaN, so the comparison always answers.
            (Ordered::Numbers, _, _) => number_as_f64(a)
                .partial_cmp(&number_as_f64(b))
                .unwrap_or(Ordering::Equal),
            // Unreachable: `of` checked every value against the kind it chose.
            _ => Ordering::Equal,
        }
    }
}

/// Order `values` in place, or say why they cannot be ordered.
fn sort_in_place(values: &mut [Value]) -> Result<(), String> {
    let ordering = Ordered::of(values)?;
    values.sort_by(|a, b| ordering.compare(a, b));
    Ok(())
}

/// `reverse(seq)` returns a reversed copy of an array or string.
fn reverse(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("reverse", &args, 1)?;
    match &args[0] {
        Value::Array(items) => {
            let mut copy = items.borrow().clone();
            copy.reverse();
            Ok(Value::array(copy))
        }
        Value::Str(s) => Ok(Value::Str(Rc::new(s.chars().rev().collect()))),
        other => Err(format!(
            "reverse expects an array or string but got a {}",
            other.type_name()
        )),
    }
}

/// `abs(x)` returns the absolute value of an int or float.
fn abs(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("abs", &args, 1)?;
    match &args[0] {
        Value::Int(n) => n
            .checked_abs()
            .map(Value::Int)
            .ok_or_else(|| "integer overflow in abs".to_string()),
        Value::Float(f) => Ok(Value::Float(f.abs())),
        other => Err(format!(
            "abs expects a number but got a {}",
            other.type_name()
        )),
    }
}

/// Floored remainder of two integers: sign follows the divisor, never the
/// dividend. Differs from `%`, which truncates toward zero.
///
/// `a.checked_rem(b)` is the truncated form. When the truncated remainder is
/// non-zero and the operands have different signs, adding `b` lands on the
/// floored answer. That is the adjustment every wrapping use wants:
/// `mod(-1, 10)` is `9`, not `-1`.
fn floored_rem_i64(a: i64, b: i64) -> Option<i64> {
    let r = a.checked_rem(b)?;
    if r != 0 && (a < 0) != (b < 0) {
        r.checked_add(b)
    } else {
        Some(r)
    }
}

/// Floored remainder of two floats, built the same way as the integer form
/// above: take the truncated remainder, then adjust by one divisor when the
/// operands disagree in sign. A zero divisor is refused by the caller.
///
/// **Not `a - b * (a / b).floor()`**, which is the textbook spelling and is
/// wrong twice. With `b` infinite it evaluates `inf * 0.0`, which is `nan`, so
/// `mod(1.0, float("inf"))` answered `nan` where `%` answers `1.0` and where
/// the floored and truncated remainders agree anyway. And for a large
/// quotient the multiply undoes a division that has already rounded, so
/// `mod(1e20, 3.0)` answered `0.0` where the answer is `1`. `%` is IEEE
/// `fmod`, which is exact for every pair it accepts, and building on it
/// inherits both properties.
fn floored_rem_f64(a: f64, b: f64) -> f64 {
    let r = a % b;
    if r != 0.0 && (r < 0.0) != (b < 0.0) {
        r + b
    } else {
        r
    }
}

/// `mod(n, d)` is the floored remainder of `n` by `d`. The sign follows `d`,
/// so a negative dividend never produces a negative result when `d` is positive.
///
/// `%` keeps the truncating form required by section 5 (and by every language
/// that maps remainder onto machine division). Wrapping arithmetic needs the
/// other definition, and writing `((n % d) + d) % d` by hand is three operations
/// and two mentions of `d` for one idea. `mod` is that idea under one name.
///
/// A zero divisor refuses with the same words `%` uses. Two integers stay
/// integers; any float promotes, matching every other binary numeric builtin.
fn modulo(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    check_arity("mod", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Int(n), Value::Int(d)) => {
            if *d == 0 {
                return Err("modulo by zero".to_string());
            }
            floored_rem_i64(*n, *d)
                .map(Value::Int)
                .ok_or_else(|| "integer overflow in mod".to_string())
        }
        (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
            let n = number_arg("mod", &args[0])?;
            let d = number_arg("mod", &args[1])?;
            if d == 0.0 {
                return Err("modulo by zero".to_string());
            }
            let result = floored_rem_f64(n, d);
            // The same guard `pow` carries, for the same reason. An infinite
            // dividend has no floored remainder, and answering `nan` would let
            // it travel to a line with no connection to this one. Only an
            // invented `nan` refuses: one that arrived in an argument is
            // carried, because carrying a `nan` a program already had is not
            // inventing one.
            if result.is_nan() && !n.is_nan() && !d.is_nan() {
                return Err("mod of an infinite number".to_string());
            }
            Ok(Value::Float(result))
        }
        (other, _) if !matches!(other, Value::Int(_) | Value::Float(_)) => Err(format!(
            "mod expects numbers but got a {}",
            other.type_name()
        )),
        (_, other) => Err(format!(
            "mod expects numbers but got a {}",
            other.type_name()
        )),
    }
}

/// Shared implementation of `min` and `max`: pick the argument that compares as
/// `want` against the running best. Preserves the winning value's own type.
///
/// The comparison goes through [`Ordered`], which is the type whose whole
/// purpose is that this decision exists once. It did not, and the two copies
/// came apart: this function compared through `f64` even when every argument
/// was an integer, so `max(9223372036854775806, 9223372036854775807)` gave the
/// smaller of the two, while `<` and `sort` both ordered them correctly.
fn extreme(name: &str, args: Vec<Value>, want: Ordering) -> Result<Value, String> {
    if args.is_empty() {
        return Err(format!("{name} expects at least one argument"));
    }
    for value in &args {
        if !matches!(value, Value::Int(_) | Value::Float(_)) {
            return Err(format!(
                "{name} expects numbers but got a {}",
                value.type_name()
            ));
        }
        if matches!(value, Value::Float(f) if f.is_nan()) {
            return Err(format!("{name} cannot compare NaN"));
        }
    }
    // The loop above has already refused everything `Ordered::of` refuses, and
    // in this order deliberately, so the two refusals a program can reach are
    // worded for `min` and `max` rather than for `sort`. What survives to here
    // is `Ints` or `Numbers`.
    let ordered = Ordered::of(&args)?;
    let mut best = args[0].clone();
    for value in &args[1..] {
        if ordered.compare(value, &best) == want {
            best = value.clone();
        }
    }
    Ok(best)
}

/// `min(...)` returns the smallest of its numeric arguments.
fn min(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    extreme("min", args, Ordering::Less)
}

/// `max(...)` returns the largest of its numeric arguments.
fn max(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    extreme("max", args, Ordering::Greater)
}

/// Shared implementation of `sum` and `product`: fold an array of numbers.
///
/// `identity` is the answer for an empty array, 0 for a sum and 1 for a
/// product. Those are the values that let the builtins compose: summing the
/// halves of a split array gives the sum of the whole however the split fell,
/// including when one half is empty.
///
/// The fold holds an integer until a float arrives and a float afterwards,
/// which is section 5.2's promotion rule applied one element at a time. The
/// integer step is checked, because every integer operation in this language is
/// checked and none of them wraps.
///
/// `NaN` is not refused, unlike in `min` and `max`. Those compare, and there is
/// no answer to a comparison with `NaN`. This only adds or multiplies, where
/// `NaN` propagates and is a value the language already holds.
fn fold_numbers(
    name: &str,
    args: Vec<Value>,
    identity: i64,
    step_int: fn(i64, i64) -> Option<i64>,
    step_float: fn(f64, f64) -> f64,
) -> Result<Value, String> {
    check_arity(name, &args, 1)?;
    let items = match &args[0] {
        Value::Array(items) => items,
        other => {
            return Err(format!(
                "{name} expects an array but got a {}",
                other.type_name()
            ))
        }
    };

    let mut whole = identity;
    let mut fraction: Option<f64> = None;
    let items = items.borrow();
    for item in items.iter() {
        match (item, fraction) {
            (Value::Int(n), None) => {
                whole = step_int(whole, *n).ok_or_else(|| format!("integer overflow in {name}"))?;
            }
            (Value::Int(n), Some(f)) => fraction = Some(step_float(f, *n as f64)),
            (Value::Float(x), None) => fraction = Some(step_float(whole as f64, *x)),
            (Value::Float(x), Some(f)) => fraction = Some(step_float(f, *x)),
            (other, _) => {
                return Err(format!(
                    "{name} expects an array of numbers but got a {}",
                    other.type_name()
                ))
            }
        }
    }

    Ok(match fraction {
        Some(f) => Value::Float(f),
        None => Value::Int(whole),
    })
}

/// `sum(a)` adds the numbers in an array. An empty array gives `0`.
fn sum(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    fold_numbers("sum", args, 0, i64::checked_add, |a, b| a + b)
}

/// `product(a)` multiplies the numbers in an array. An empty array gives `1`.
fn product(
    _out: &mut dyn Output,
    _input: &mut dyn Input,
    args: Vec<Value>,
) -> Result<Value, String> {
    fold_numbers("product", args, 1, i64::checked_mul, |a, b| a * b)
}

/// Shared implementation of `floor`, `ceil`, and `round`. Ints pass through
/// unchanged; a float is rounded by `apply` and returned as an int.
fn round_like(name: &str, args: Vec<Value>, apply: fn(f64) -> f64) -> Result<Value, String> {
    check_arity(name, &args, 1)?;
    match &args[0] {
        Value::Int(n) => Ok(Value::Int(*n)),
        Value::Float(x) => {
            let rounded = apply(*x);
            if !rounded.is_finite() {
                return Err(format!("{name} of a non-finite number"));
            }
            as_int(rounded).ok_or_else(|| format!("integer overflow in {name}"))
        }
        other => Err(format!(
            "{name} expects a number but got a {}",
            other.type_name()
        )),
    }
}

/// The integer `x` names, or `None` when no integer does.
///
/// **`f64 as i64` saturates**, so without this `int(float("1e300"))` answered
/// `9223372036854775807`: a wrong number where every sibling refuses. `abs`,
/// `sum`, `product` and `pow` all give "integer overflow in ..." rather than a
/// nearby answer, and section 5 of the specification says every integer
/// operation tests for overflow.
///
/// The upper bound is a strict `<` against 2^63 rather than `<=` against
/// `i64::MAX`, because `i64::MAX as f64` rounds *up* to 2^63 and would let the
/// one value past the end through. `i64::MIN as f64` is exact, so the lower
/// bound needs no such care.
fn as_int(x: f64) -> Option<Value> {
    let least = i64::MIN as f64;
    if x >= least && x < -least {
        Some(Value::Int(x as i64))
    } else {
        None
    }
}

/// `floor(x)` returns the largest integer not greater than `x`.
fn floor(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    round_like("floor", args, f64::floor)
}

/// `ceil(x)` returns the smallest integer not less than `x`.
fn ceil(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    round_like("ceil", args, f64::ceil)
}

/// `round(x)` returns `x` rounded to the nearest integer, halves away from zero.
fn round(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    round_like("round", args, f64::round)
}

/// The f64 value of a numeric argument, or an error naming the builtin.
fn number_arg(name: &str, value: &Value) -> Result<f64, String> {
    match value {
        Value::Int(n) => Ok(*n as f64),
        Value::Float(f) => Ok(*f),
        other => Err(format!(
            "{name} expects numbers but got a {}",
            other.type_name()
        )),
    }
}

/// `sqrt(x)` returns the square root of a non-negative number, as a float.
fn sqrt(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("sqrt", &args, 1)?;
    let x = number_arg("sqrt", &args[0])?;
    if x < 0.0 {
        return Err("sqrt of a negative number".to_string());
    }
    Ok(Value::Float(x.sqrt()))
}

/// `pow(base, exp)` returns `base` raised to `exp`. With two integers and a
/// non-negative exponent the result is an integer; otherwise it is a float.
fn pow(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("pow", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Int(base), Value::Int(exp)) if *exp >= 0 => {
            let exp = u32::try_from(*exp).map_err(|_| "pow exponent is too large".to_string())?;
            base.checked_pow(exp)
                .map(Value::Int)
                .ok_or_else(|| "integer overflow in pow".to_string())
        }
        _ => {
            let base = number_arg("pow", &args[0])?;
            let exp = number_arg("pow", &args[1])?;
            let result = base.powf(exp);
            // The other half of issue #52. `sqrt(-1)` refuses and
            // `pow(-8.0, 0.5)` used to answer `nan`, which is the same question
            // asked twice and answered differently. `nan` then travels through
            // every operation that touches it and surfaces far from the line
            // that made it, which is what the refusal exists to prevent.
            //
            // Only an invented `nan` refuses. One that arrived in an argument
            // is propagated, the way `sum` and `product` propagate theirs:
            // carrying a `nan` a program already had is not inventing one.
            if result.is_nan() && !base.is_nan() && !exp.is_nan() {
                return Err("pow of a negative number to a fractional power".to_string());
            }
            Ok(Value::Float(result))
        }
    }
}

/// `int(x)` converts a float (truncating toward zero) or a numeric string to an
/// integer; an integer is returned unchanged.
fn int(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("int", &args, 1)?;
    match &args[0] {
        Value::Int(n) => Ok(Value::Int(*n)),
        Value::Float(f) => {
            if !f.is_finite() {
                return Err("int of a non-finite number".to_string());
            }
            as_int(*f).ok_or_else(|| "integer overflow in int".to_string())
        }
        Value::Str(s) => s
            .trim()
            .parse::<i64>()
            .map(Value::Int)
            .map_err(|_| format!("cannot convert \"{s}\" to an int")),
        other => Err(format!("int cannot convert a {}", other.type_name())),
    }
}

/// `float(x)` converts an integer or a numeric string to a float; a float is
/// returned unchanged.
fn float(_out: &mut dyn Output, _input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    check_arity("float", &args, 1)?;
    match &args[0] {
        Value::Int(n) => Ok(Value::Float(*n as f64)),
        Value::Float(f) => Ok(Value::Float(*f)),
        Value::Str(s) => s
            .trim()
            .parse::<f64>()
            .map(Value::Float)
            .map_err(|_| format!("cannot convert \"{s}\" to a float")),
        other => Err(format!("float cannot convert a {}", other.type_name())),
    }
}

/// `args()` gives the arguments the program was given, as an array of strings.
///
/// The program's own path is not among them. It is not an argument to the
/// program, and a caller that wants it already knows it.
///
/// Empty rather than an error where there is no command line, because a program
/// that was given no arguments and a program that could not have been given any
/// both have none, and the loop over them is the same either way.
fn args(system: &mut dyn System, args: Vec<Value>) -> Result<Value, String> {
    check_arity("args", &args, 0)?;
    let items = system
        .arguments()
        .into_iter()
        .map(|arg| Value::Str(Rc::new(arg)))
        .collect();
    Ok(Value::array(items))
}

/// `read_file(path)` gives the whole file as a string.
///
/// A relative path is resolved against the working directory, which is not what
/// `import` does. Section 8 of the specification states the difference and why.
fn read_file(system: &mut dyn System, args: Vec<Value>) -> Result<Value, String> {
    check_arity("read_file", &args, 1)?;
    match &args[0] {
        Value::Str(path) => system.read_file(path).map(|text| Value::Str(Rc::new(text))),
        other => Err(format!(
            "read_file expects a string path but got a {}",
            other.type_name()
        )),
    }
}

/// `write_file(path, contents)` writes the string, replacing what was there.
fn write_file(system: &mut dyn System, args: Vec<Value>) -> Result<Value, String> {
    check_arity("write_file", &args, 2)?;
    match (&args[0], &args[1]) {
        (Value::Str(path), Value::Str(contents)) => {
            system.write_file(path, contents).map(|()| Value::Nil)
        }
        (Value::Str(_), other) => Err(format!(
            "write_file expects a string to write but got a {}",
            other.type_name()
        )),
        (other, _) => Err(format!(
            "write_file expects a string path but got a {}",
            other.type_name()
        )),
    }
}

/// `file_exists(path)` says whether there is a file at the path.
///
/// This one answers rather than refusing where there is no file system, because
/// the honest answer to "is there a file there" is then no. A program that asks
/// before reading gets a useful `false` instead of an error it has to catch, and
/// the read itself still refuses if it is tried anyway.
fn file_exists(system: &mut dyn System, args: Vec<Value>) -> Result<Value, String> {
    check_arity("file_exists", &args, 1)?;
    match &args[0] {
        Value::Str(path) => Ok(Value::Bool(system.file_exists(path))),
        other => Err(format!(
            "file_exists expects a string path but got a {}",
            other.type_name()
        )),
    }
}

/// `now()` gives the milliseconds since 1970-01-01T00:00:00Z.
///
/// An integer rather than a float, because a float loses whole milliseconds
/// somewhere in the year 287396 and an integer does not, and because the two
/// things a program does with this are subtract one from another and print it.
///
/// It refuses where the host has no clock, rather than answering 0. Section 8
/// of the specification says so, and `try` catches it.
fn now(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("now", &args, 0)?;
    ambient.now_millis().map(Value::Int)
}

/// `sleep(ms)` does nothing for that many milliseconds.
///
/// This is what lets a loop hold a frame rate. Without it a loop runs as fast as
/// the machine allows, measured at just under eight million turns a second on
/// an ordinary one, which is a pegged processor and a game whose speed depends
/// on what it is running on.
///
/// **A negative duration is an error rather than a no-op.** Nobody means to wait
/// for less than no time, so it is a mistake somewhere further up, usually a
/// subtraction that went the wrong way while working out how much of a frame is
/// left. Returning at once would hide it and leave the loop running flat out,
/// which is the exact fault this builtin exists to fix.
///
/// Zero is not an error, because `sleep(deadline - now())` legitimately reaches
/// zero on the frame where the work took exactly as long as the frame.
///
/// It refuses where the host cannot pause, which is any page: see
/// `BrowserClock::sleep_millis`. `try` catches it.
fn sleep(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("sleep", &args, 1)?;
    let millis = match &args[0] {
        Value::Int(n) => *n,
        other => {
            return Err(format!(
                "sleep expects an int number of milliseconds but got a {}",
                other.type_name()
            ))
        }
    };
    if millis < 0 {
        return Err(format!(
            "sleep expects a number of milliseconds that is not negative but got {millis}"
        ));
    }
    ambient.sleep_millis(millis as u64).map(|()| Value::Nil)
}

/// `random()` gives a float from 0 up to but not including 1.
///
/// The generator seeds itself from the clock the first time a program asks, so
/// two runs differ. `seed` pins it when they must not.
fn random(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("random", &args, 0)?;
    Ok(Value::Float(ambient.rng().unit()))
}

/// `random_int(low, high)` gives an integer from `low` to `high`, both
/// included.
///
/// Both ends are in the range because that is what a program asking for a die
/// or a card means, and because a half-open range would make `random_int(1, 6)`
/// the wrong spelling of the most common use of it.
///
/// Floats are refused rather than truncated. `random_int(1, 6.5)` is a program
/// that has not decided what it wants, and either answer this could give would
/// be a guess about which.
fn random_int(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("random_int", &args, 2)?;
    let bound = |value: &Value, which: &str| match value {
        Value::Int(n) => Ok(*n),
        other => Err(format!(
            "random_int expects an int {which} bound but got a {}",
            other.type_name()
        )),
    };
    let low = bound(&args[0], "low")?;
    let high = bound(&args[1], "high")?;
    if low > high {
        return Err(format!(
            "random_int expects a low bound not above the high bound but got {low} and {high}"
        ));
    }
    Ok(Value::Int(ambient.rng().int_in(low, high)))
}

/// `seed(n)` starts the generator again from `n`.
///
/// This is what makes a program that uses random numbers testable. Two runs
/// that start from the same seed draw the same numbers, so a program can be
/// asserted against exact output and still be about chance.
///
/// Any integer is a seed, including one a program has already used. There is no
/// value to refuse: the generator has 2^64 states and every integer names one.
fn seed(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("seed", &args, 1)?;
    match &args[0] {
        Value::Int(n) => {
            ambient.set_seed(*n);
            Ok(Value::Nil)
        }
        other => Err(format!(
            "seed expects an int but got a {}",
            other.type_name()
        )),
    }
}

/// `read_key()` gives the next key, without waiting for a line.
///
/// A string, which is the character itself for a key that produced one and a
/// name from section 8.11 of the specification otherwise. `nil` at end of
/// input, matching what `input()` gives there.
///
/// It refuses where the host has no keyboard, as `now` refuses where there is
/// no clock, and `try` catches that.
fn read_key(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("read_key", &args, 0)?;
    Ok(match ambient.read_key()? {
        Some(key) => Value::Str(Rc::new(key)),
        None => Value::Nil,
    })
}

/// `key_ready()` says whether `read_key()` would answer without waiting.
///
/// **This is what lets a loop go round when nobody has pressed anything.**
/// `read_key` on its own waits, so a loop built from it only advances once per
/// key: a program cannot move something across the screen while the person
/// holds still, because it never gets control back to do it. Guarding the read
/// turns that inside out, and the world advances whether a key came or not.
///
/// ```text
/// while true {
///   while key_ready() { handle(read_key()) }   // take everything pressed
///   advance()                                  // whether or not any was
///   draw()
///   sleep(50)
/// }
/// ```
///
/// The inner loop drains rather than reading one, so a burst of keys pressed
/// inside one frame is all seen in that frame instead of arriving one per
/// frame for the next several.
///
/// **It is `true` at end of input**, because a read there answers at once. That
/// is what stops the drain loop above from spinning forever on a closed stream:
/// the read gives `nil` and the program can stop. It reports whether a read
/// will wait, not whether a key exists, and the two differ exactly there.
fn key_ready(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("key_ready", &args, 0)?;
    ambient.key_ready().map(Value::Bool)
}

/// `clear()` empties the screen and puts the cursor at the top left.
///
/// **This is what turns printing into drawing.** Without it a program that
/// prints a picture every frame produces a column of pictures scrolling
/// upwards; with it, each one replaces the last and the thing appears to move.
///
/// The whole frame should be built as one string and printed once. Printing it
/// a row at a time works and can be seen doing it, because the terminal draws
/// each row as it arrives and the eye catches the sweep.
///
/// Where standard output is not a terminal (a pipe, a file) this does
/// nothing, because there is no screen to clear. That is what keeps a game's
/// output readable when it is redirected, and comparable in a test.
fn clear(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("clear", &args, 0)?;
    ambient.screen().clear().map(|()| Value::Nil)
}

/// `move_to(column, row)` puts the cursor there, counting from zero.
///
/// From zero because the language indexes arrays from zero, and a program
/// drawing a grid is indexing one: `move_to(0, 0)` is the top left, matching
/// `grid[0][0]`. The escape sequence underneath counts from one, which is the
/// implementation's business.
fn move_to(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("move_to", &args, 2)?;
    let coordinate = |value: &Value, which: &str| match value {
        Value::Int(n) => Ok(*n),
        other => Err(format!(
            "move_to expects an int {which} but got a {}",
            other.type_name()
        )),
    };
    let column = coordinate(&args[0], "column")?;
    let row = coordinate(&args[1], "row")?;
    ambient.screen().move_to(column, row).map(|()| Value::Nil)
}

/// `hide_cursor()` stops the terminal drawing the cursor.
///
/// Worth doing in anything that animates: the cursor sits wherever the last
/// character was written, which in a redrawn frame is the bottom right, and it
/// blinks there through the whole game.
///
/// **The cursor comes back by itself when the program ends**, however it ends:
/// normally, on an error, or through `exit`. A program does not have to pair
/// this with `show_cursor`, for the same reason it does not have to put the
/// terminal back after `read_key`.
fn hide_cursor(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("hide_cursor", &args, 0)?;
    ambient.screen().hide_cursor().map(|()| Value::Nil)
}

/// `show_cursor()` draws the cursor again.
fn show_cursor(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("show_cursor", &args, 0)?;
    ambient.screen().show_cursor().map(|()| Value::Nil)
}

/// `term_size()` gives `[columns, rows]` for the terminal.
///
/// **It refuses where there is no terminal**, rather than answering with the
/// traditional 80 by 24. That would be a wrong answer and not an absent one,
/// and a program handed it draws a board that does not fit, by the same reasoning
/// that makes `now()` refuse rather than answering 1970.
///
/// The consequence is worth stating: a program that calls this cannot run under
/// a pipe unless it catches the refusal. The bundled games fix their own size
/// instead, which is why they can be tested by piping keys into them.
fn term_size(ambient: &mut Ambient, args: Vec<Value>) -> Result<Value, String> {
    check_arity("term_size", &args, 0)?;
    let (columns, rows) = ambient.screen().size()?;
    Ok(Value::array(vec![Value::Int(columns), Value::Int(rows)]))
}

/// `input()` reads one line from the input source and returns it as a string,
/// or `nil` at end of input. `input(prompt)` writes the prompt string first.
fn input(out: &mut dyn Output, input: &mut dyn Input, args: Vec<Value>) -> Result<Value, String> {
    match args.as_slice() {
        [] => {}
        [Value::Str(prompt)] => out.write(prompt.as_str()),
        [other] => {
            return Err(format!(
                "input expects a string prompt but got a {}",
                other.type_name()
            ))
        }
        _ => {
            return Err(format!(
                "input expects 0 or 1 arguments but got {}",
                args.len()
            ))
        }
    }
    match input.read_line() {
        Some(line) => Ok(Value::Str(Rc::new(line))),
        None => Ok(Value::Nil),
    }
}

/// The arguments a suspended higher-order builtin wants applied, held inline
/// rather than in a `Vec`.
///
/// This is built once per element, so a `Vec` here would put back the heap
/// allocation the trampoline exists to remove: one was measured at 10.8 ns
/// against a per-element budget of 74 ns. The three higher-order builtins pass
/// at most two arguments; a builtin wanting three would add a variant.
pub enum Args {
    One(Value),
    Two(Value, Value),
}

impl Args {
    /// How many arguments there are, for the callee's arity check. Named
    /// `count` rather than `len` because a `len` invites an `is_empty` beside
    /// it, and these are never empty.
    pub fn count(&self) -> usize {
        match self {
            Args::One(_) => 1,
            Args::Two(_, _) => 2,
        }
    }

    /// Push the arguments in order, leaving the stack as a bytecode call would.
    pub fn push_onto(self, stack: &mut Vec<Value>) {
        match self {
            Args::One(a) => stack.push(a),
            Args::Two(a, b) => {
                stack.push(a);
                stack.push(b);
            }
        }
    }

    /// Collect into a `Vec` for an ordinary native builtin, whose signature
    /// takes one.
    ///
    /// This is the last per-element heap allocation left in the engine, and it
    /// only happens when a *builtin* is the callback, as in `map(xs, abs)`.
    /// Removing it means changing [`BuiltinFn`] for the forty-eight builtins
    /// registered with `define`, several of which move values out of the vector
    /// they are handed, which is a larger change than it looks and is left for
    /// later.
    ///
    /// Forty-eight is the count of `define` calls, not the count of builtins.
    /// The two were the same figure until 1.1 and are not any more: there are
    /// sixty-eight builtins, of which four take a `SystemFn`, twelve take an
    /// `AmbientFn`, and four take a `HostFn`, and none of those twenty would
    /// be touched by such a change.
    pub fn into_vec(self) -> Vec<Value> {
        match self {
            Args::One(a) => vec![a],
            Args::Two(a, b) => vec![a, b],
        }
    }
}

/// What a suspended higher-order builtin wants next.
///
/// The values are owned rather than borrowed so that advancing a task does not
/// hold a borrow of the engine. The task lives on the engine's own task stack,
/// and the engine has to touch its value stack to carry the step out, so a
/// [`Step`] that borrowed from the task would make those two borrows overlap.
pub enum Step {
    /// Apply the task's own callback to these arguments, then resume it with
    /// the result.
    ///
    /// The callee is not carried here. It never varies across a task's steps,
    /// so repeating it per element only made this enum bigger, and this value
    /// is built and moved once per element. Naming it cost 32 of the 96 bytes
    /// that move each time; the engine reads it from the task instead.
    Call(Args),
    /// The builtin is finished; this is its value.
    Done(Value),
}

/// A higher-order builtin part way through its work.
///
/// `map`, `filter`, and `reduce` are state machines rather than loops. A loop
/// would have to call back into the engine per element, which costs a nested
/// bytecode loop and a real Rust call each time; instead each step says what to
/// call and the single dispatch loop does the calling.
///
/// Every variant walks `items` by index and moves each element out with
/// [`std::mem::replace`] rather than cloning it. That is not a flourish: it
/// keeps the clone count per element the same as the loops these replaced, and
/// `reduce` in particular would otherwise clone its accumulator on every step.
pub enum HostTask {
    Map {
        func: Value,
        items: Vec<Value>,
        next: usize,
        out: Vec<Value>,
    },
    Filter {
        func: Value,
        items: Vec<Value>,
        next: usize,
        out: Vec<Value>,
        /// The element the outstanding call is deciding on, kept so a truthy
        /// answer can move it into `out` rather than clone it again.
        pending: Option<Value>,
    },
    Reduce {
        func: Value,
        items: Vec<Value>,
        next: usize,
        acc: Value,
    },
    Sort {
        /// The key function, or `Value::Nil` when `sort` was given one
        /// argument. That spelling is unambiguous because the constructor
        /// refuses a second argument that is not callable, so a program cannot
        /// reach here by writing `sort(a, nil)`.
        func: Value,
        items: Vec<Value>,
        next: usize,
        /// The element whose key is being computed, kept for the same reason
        /// `Filter` keeps one: it is moved into the result rather than cloned
        /// a second time when the answer arrives.
        pending: Option<Value>,
        /// The keys, and the elements they belong to, at matching indexes.
        ///
        /// Two vectors rather than one of pairs, so that deciding how to order
        /// the keys can look at them as a slice without cloning every one of
        /// them out of a tuple first.
        keys: Vec<Value>,
        kept: Vec<Value>,
    },
}

impl HostTask {
    /// The function this task applies. It is the same for every step, which is
    /// why [`Step::Call`] does not repeat it.
    pub fn callback(&self) -> &Value {
        match self {
            HostTask::Map { func, .. }
            | HostTask::Filter { func, .. }
            | HostTask::Reduce { func, .. }
            | HostTask::Sort { func, .. } => func,
        }
    }

    /// Advance the builtin one step. `last` is the value the previously
    /// requested call returned, or `None` on the first step.
    ///
    /// Fallible because `filter` asks its callback's answer whether it is true,
    /// and a caught error refuses to answer that. `map` and `reduce` only ever
    /// store what they are given, which is what assigning an error already does
    /// everywhere else, so they cannot fail here.
    pub fn resume(&mut self, last: Option<Value>) -> Result<Step, String> {
        match self {
            HostTask::Map {
                items, next, out, ..
            } => {
                if let Some(value) = last {
                    out.push(value);
                }
                match take_next(items, next) {
                    None => Ok(Step::Done(array(std::mem::take(out)))),
                    Some(item) => Ok(Step::Call(Args::One(item))),
                }
            }
            HostTask::Filter {
                items,
                next,
                out,
                pending,
                ..
            } => {
                // `pending` holds the element the answer is about. Keeping it
                // means a kept element is moved into the result rather than
                // cloned a second time.
                if let Some(value) = last {
                    let item = pending.take().expect("an element under decision");
                    // `condition`, not `is_truthy`: this is a conditional, and a
                    // caught error must refuse to be one here exactly as it does
                    // in `if` and `while`. Reading it as true kept every element
                    // and said nothing.
                    if value.condition()? {
                        out.push(item);
                    }
                }
                match take_next(items, next) {
                    None => Ok(Step::Done(array(std::mem::take(out)))),
                    Some(item) => {
                        *pending = Some(item.clone());
                        Ok(Step::Call(Args::One(item)))
                    }
                }
            }
            HostTask::Sort {
                func,
                items,
                next,
                pending,
                keys,
                kept,
            } => {
                // One argument. The whole sort happens on this first resume and
                // the task never asks for a call, so `callback` is never
                // consulted and the `nil` held there is never reached.
                if matches!(func, Value::Nil) {
                    let mut sorted = std::mem::take(items);
                    sort_in_place(&mut sorted)?;
                    return Ok(Step::Done(array(sorted)));
                }
                if let Some(key) = last {
                    keys.push(key);
                    kept.push(pending.take().expect("an element under decision"));
                }
                match take_next(items, next) {
                    None => {
                        let ordering = Ordered::of(keys)?;
                        // A permutation is sorted rather than the elements, so
                        // no key and no element is cloned to get them into one
                        // place. `sort_by` is stable, which is what makes two
                        // passes a two-key sort and is promised in section 8.4
                        // of the specification.
                        let mut order: Vec<usize> = (0..keys.len()).collect();
                        order.sort_by(|&a, &b| ordering.compare(&keys[a], &keys[b]));
                        let out = order
                            .into_iter()
                            .map(|i| std::mem::replace(&mut kept[i], Value::Nil))
                            .collect();
                        Ok(Step::Done(array(out)))
                    }
                    Some(item) => {
                        *pending = Some(item.clone());
                        Ok(Step::Call(Args::One(item)))
                    }
                }
            }
            HostTask::Reduce {
                items, next, acc, ..
            } => {
                if let Some(value) = last {
                    *acc = value;
                }
                match take_next(items, next) {
                    None => Ok(Step::Done(std::mem::replace(acc, Value::Nil))),
                    Some(item) => {
                        // Move the accumulator out rather than cloning it. The
                        // call's result puts one back on the next resume.
                        let carried = std::mem::replace(acc, Value::Nil);
                        Ok(Step::Call(Args::Two(carried, item)))
                    }
                }
            }
        }
    }
}

/// Move the element at `next` out of `items` and advance the cursor, or `None`
/// once the walk is done. The vacated slot is left holding `nil`, which nothing
/// reads: the cursor only ever moves forward.
fn take_next(items: &mut [Value], next: &mut usize) -> Option<Value> {
    let slot = items.get_mut(*next)?;
    *next += 1;
    Some(std::mem::replace(slot, Value::Nil))
}

fn array(items: Vec<Value>) -> Value {
    Value::array(items)
}

/// Check the two-argument shape `map` and `filter` share: an array to walk and a
/// function to apply to each of its elements.
///
/// The array is copied here rather than borrowed for the length of the walk.
/// That matches `for x in xs`, which copies through `OpCode::IterSnapshot`, so a
/// callback that pushes to the array being walked does not extend the walk. It
/// also means the task owns its elements and can move them out one at a time
/// instead of cloning them.
/// A value that can be called, or a refusal naming what arrived instead.
///
/// **Checked eagerly, which `sort` always did and the other three did not.**
/// `map`, `filter` and `reduce` only found out at the first call, so
/// `map([], nil)` answered `[]`: an empty array makes no call, so a program
/// that passed something uncallable was told nothing at all. One of the four
/// builtins in section 8.8 checked its arguments and three checked them by
/// accident.
fn function_arg(name: &str, value: Value) -> Result<Value, String> {
    match value {
        func @ (Value::Closure(_) | Value::Builtin(_) | Value::HostBuiltin(_)) => Ok(func),
        other => Err(format!(
            "{name} expects a function but got a {}",
            other.type_name()
        )),
    }
}

fn array_and_function(name: &str, args: Vec<Value>) -> Result<(Vec<Value>, Value), String> {
    if args.len() != 2 {
        return Err(format!("{name} expects 2 arguments but got {}", args.len()));
    }
    let mut args = args.into_iter();
    let items = match args.next().expect("two arguments") {
        Value::Array(items) => items.borrow().clone(),
        other => {
            return Err(format!(
                "{name} expects an array but got a {}",
                other.type_name()
            ))
        }
    };
    let func = function_arg(name, args.next().expect("two arguments"))?;
    Ok((items, func))
}

/// `map(array, f)` returns a new array holding `f(x)` for each element `x`, in
/// order. The function is applied by the engine, so it may be a user-defined
/// function, a closure, or another builtin.
fn map(args: Vec<Value>) -> Result<HostTask, String> {
    let (items, func) = array_and_function("map", args)?;
    Ok(HostTask::Map {
        out: Vec::with_capacity(items.len()),
        func,
        items,
        next: 0,
    })
}

/// `filter(array, f)` returns a new array of the elements for which `f(x)` is
/// truthy, keeping their original order.
fn filter(args: Vec<Value>) -> Result<HostTask, String> {
    let (items, func) = array_and_function("filter", args)?;
    Ok(HostTask::Filter {
        func,
        items,
        next: 0,
        out: Vec::new(),
        pending: None,
    })
}

/// `sort(array)` gives a sorted copy. `sort(array, key)` gives one ordered by
/// `key(x)` for each element, rather than by the elements themselves.
///
/// A key function and not a comparator. A key is asked for once per element,
/// which is a walk from start to end and so fits the shape every other
/// higher-order builtin already has; a comparator would mean driving a sort as
/// a state machine that hands out one comparison at a time. Decreasing order is
/// `reverse(sort(a, key))`, and a two-key sort is two passes, least significant
/// first, which works because the sort is stable.
fn sort(args: Vec<Value>) -> Result<HostTask, String> {
    if args.is_empty() || args.len() > 2 {
        return Err(format!(
            "sort expects 1 to 2 arguments but got {}",
            args.len()
        ));
    }
    let mut args = args.into_iter();
    let items = match args.next().expect("at least one argument") {
        Value::Array(items) => items.borrow().clone(),
        other => {
            return Err(format!(
                "sort expects an array but got a {}",
                other.type_name()
            ))
        }
    };
    // Checked here rather than left to fail at the call, which is what `map`
    // and `filter` do. This one has to know the difference between "no key
    // function" and "a second argument that is not one", because the first is
    // spelled as `nil` in the task.
    let func = match args.next() {
        None => Value::Nil,
        Some(func @ (Value::Closure(_) | Value::Builtin(_) | Value::HostBuiltin(_))) => func,
        Some(other) => {
            return Err(format!(
                "sort expects a function but got a {}",
                other.type_name()
            ))
        }
    };
    Ok(HostTask::Sort {
        keys: Vec::with_capacity(items.len()),
        kept: Vec::with_capacity(items.len()),
        func,
        items,
        next: 0,
        pending: None,
    })
}

/// `reduce(array, f, init)` folds the array from the left: starting with the
/// accumulator `init`, it computes `f(acc, x)` for each element in order and
/// returns the final accumulator.
fn reduce(args: Vec<Value>) -> Result<HostTask, String> {
    if args.len() != 3 {
        return Err(format!("reduce expects 3 arguments but got {}", args.len()));
    }
    let mut args = args.into_iter();
    let items = match args.next().expect("three arguments") {
        Value::Array(items) => items.borrow().clone(),
        other => {
            return Err(format!(
                "reduce expects an array but got a {}",
                other.type_name()
            ))
        }
    };
    let func = function_arg("reduce", args.next().expect("three arguments"))?;
    Ok(HostTask::Reduce {
        func,
        items,
        next: 0,
        acc: args.next().expect("three arguments"),
    })
}

#[cfg(test)]
mod task_tests {
    //! The higher-order builtins as state machines, driven by hand.
    //!
    //! No virtual machine here. A task only ever says what it wants called and
    //! is told what came back, so it can be stepped directly, and a fault in
    //! the sequencing shows up as a wrong step rather than as a wrong program
    //! output three layers away.

    use super::{Args, HostTask, Step};
    use crate::value::Value;

    /// The element a step asks for, as a readable string, or a description of
    /// why it was not the single-argument call the caller expected.
    ///
    /// Takes the whole `Result` so a refusal reads as a value here rather than
    /// unwrapping at every call site. Only `filter` can produce one.
    fn asked_for(step: &Result<Step, String>) -> String {
        match step {
            Ok(Step::Call(Args::One(v))) => v.repr(),
            Ok(Step::Call(Args::Two(a, b))) => format!("two: {} {}", a.repr(), b.repr()),
            Ok(Step::Done(v)) => format!("done: {}", v.repr()),
            Err(message) => format!("refused: {message}"),
        }
    }

    fn ints(values: &[i64]) -> Vec<Value> {
        values.iter().map(|n| Value::Int(*n)).collect()
    }

    /// A callback stands in for the function the engine would apply. The task
    /// never calls it, so any value does.
    fn callback() -> Value {
        Value::Nil
    }

    #[test]
    fn a_map_task_asks_for_each_element_then_yields_the_results() {
        let mut task = HostTask::Map {
            func: callback(),
            items: ints(&[1, 2]),
            next: 0,
            out: Vec::new(),
        };
        assert_eq!(asked_for(&task.resume(None)), "1");
        assert_eq!(asked_for(&task.resume(Some(Value::Int(10)))), "2");
        assert_eq!(
            asked_for(&task.resume(Some(Value::Int(20)))),
            "done: [10, 20]"
        );
    }

    #[test]
    fn a_map_task_over_nothing_is_done_at_once() {
        let mut task = HostTask::Map {
            func: callback(),
            items: Vec::new(),
            next: 0,
            out: Vec::new(),
        };
        assert_eq!(asked_for(&task.resume(None)), "done: []");
    }

    #[test]
    fn a_filter_task_keeps_only_what_the_answer_was_truthy_for() {
        let mut task = HostTask::Filter {
            func: callback(),
            items: ints(&[1, 2, 3]),
            next: 0,
            out: Vec::new(),
            pending: None,
        };
        assert_eq!(asked_for(&task.resume(None)), "1");
        assert_eq!(asked_for(&task.resume(Some(Value::Bool(false)))), "2");
        assert_eq!(asked_for(&task.resume(Some(Value::Bool(true)))), "3");
        // nil is falsy, like false, so the third element is dropped.
        assert_eq!(asked_for(&task.resume(Some(Value::Nil))), "done: [2]");
    }

    #[test]
    fn a_filter_task_yields_the_element_and_not_the_answer() {
        // The distinction that a loop makes for free and a state machine has to
        // be deliberate about: what goes into the result is the element, not
        // whatever the predicate returned about it.
        let mut task = HostTask::Filter {
            func: callback(),
            items: ints(&[7]),
            next: 0,
            out: Vec::new(),
            pending: None,
        };
        assert_eq!(asked_for(&task.resume(None)), "7");
        assert_eq!(asked_for(&task.resume(Some(Value::Int(999)))), "done: [7]");
    }

    #[test]
    fn a_reduce_task_carries_the_accumulator_through() {
        let mut task = HostTask::Reduce {
            func: callback(),
            items: ints(&[1, 2]),
            next: 0,
            acc: Value::Int(0),
        };
        // Each call gets the accumulator first and the element second.
        assert_eq!(asked_for(&task.resume(None)), "two: 0 1");
        assert_eq!(asked_for(&task.resume(Some(Value::Int(1)))), "two: 1 2");
        assert_eq!(asked_for(&task.resume(Some(Value::Int(3)))), "done: 3");
    }

    #[test]
    fn a_reduce_task_over_nothing_yields_its_initial_value() {
        let mut task = HostTask::Reduce {
            func: callback(),
            items: Vec::new(),
            next: 0,
            acc: Value::Int(42),
        };
        assert_eq!(asked_for(&task.resume(None)), "done: 42");
    }
}

#[cfg(test)]
mod tests {
    use crate::run_capture;

    fn out(source: &str) -> String {
        run_capture(source).expect("program should run")
    }

    fn err(source: &str) -> String {
        run_capture(source)
            .expect_err("program should fail")
            .message
    }

    /// `eprint` writes to the diagnostic stream and not to the result stream.
    ///
    /// Asserting on both is the point. A capture that merged them, or a builtin
    /// that quietly called `write` instead of `write_error`, would pass a test
    /// that only checked the text had appeared somewhere.
    #[test]
    fn eprint_writes_to_the_diagnostic_stream() {
        let captured =
            crate::run_capture_all("print(\"result\")\neprint(\"warning\")").expect("it runs");
        assert_eq!(captured.out, "result\n");
        assert_eq!(captured.err, "warning\n");
        assert_eq!(captured.code, 0);
    }

    /// Whatever `print` does with its arguments, `eprint` does too. One rule.
    #[test]
    fn eprint_formats_exactly_as_print_does() {
        for source in [
            "eprint()",
            "eprint(1)",
            "eprint(1, \"a\", true, nil)",
            "eprint([1, 2], {\"k\": 1})",
        ] {
            let printed = crate::run_capture_all(&source.replace("eprint", "print")).expect("runs");
            let complained = crate::run_capture_all(source).expect("runs");
            assert_eq!(
                complained.err, printed.out,
                "eprint and print disagree on {source}"
            );
        }
    }

    /// A program that stops on purpose keeps the output it already produced,
    /// and reports the code rather than an error.
    #[test]
    fn exit_carries_a_code_and_keeps_what_was_printed() {
        let captured =
            crate::run_capture_all("print(\"done\")\neprint(\"why\")\nexit(2)").expect("it runs");
        assert_eq!(captured.code, 2);
        assert_eq!(captured.out, "done\n");
        assert_eq!(captured.err, "why\n");
    }

    /// An ordinary end is code 0 without anybody asking.
    #[test]
    fn a_program_that_never_calls_exit_reports_zero() {
        assert_eq!(crate::run_capture_all("print(1)").expect("runs").code, 0);
    }

    #[test]
    fn exit_refuses_a_code_an_operating_system_cannot_carry() {
        assert_eq!(
            err("exit(256)"),
            "exit code must be from 0 to 255 but got 256"
        );
        assert_eq!(
            err("exit(-1)"),
            "exit code must be from 0 to 255 but got -1"
        );
        assert_eq!(err("exit(1.5)"), "exit expects an int but got a float");
    }

    #[test]
    fn upper_and_lower() {
        assert_eq!(out("print(upper(\"aBc\"), lower(\"aBc\"))"), "ABC abc\n");
    }

    #[test]
    fn upper_rejects_non_strings() {
        assert!(err("upper(1)").contains("expects a string"));
    }

    #[test]
    fn trim_strips_surrounding_whitespace() {
        assert_eq!(out("print(trim(\"  hi \"))"), "hi\n");
    }

    #[test]
    fn replace_swaps_every_occurrence() {
        assert_eq!(out("print(replace(\"a.b.c\", \".\", \"-\"))"), "a-b-c\n");
    }

    #[test]
    fn split_breaks_on_separator() {
        assert_eq!(
            out("print(split(\"a,b,c\", \",\"))"),
            "[\"a\", \"b\", \"c\"]\n"
        );
    }

    #[test]
    fn split_on_empty_separator_yields_characters() {
        assert_eq!(out("print(split(\"hi\", \"\"))"), "[\"h\", \"i\"]\n");
    }

    #[test]
    fn join_concatenates_with_separator() {
        assert_eq!(out("print(join([1, 2, 3], \"-\"))"), "1-2-3\n");
    }

    #[test]
    fn contains_checks_substrings_and_membership() {
        assert_eq!(
            out("print(contains(\"hello\", \"ell\"), contains([1, 2], 2), contains([1, 2], 9))"),
            "true true false\n"
        );
    }

    #[test]
    fn sum_and_product_fold_an_array_of_numbers() {
        assert_eq!(out("print(sum([1, 2, 3]), product([2, 3, 4]))"), "6 24\n");
        // The identity values, which are what make the two compose: the sum of
        // the halves of a split array is the sum of the whole, whichever way it
        // was split.
        assert_eq!(out("print(sum([]), product([]))"), "0 1\n");
        assert_eq!(out("print(sum([7]), product([7]))"), "7 7\n");
    }

    #[test]
    fn sum_and_product_promote_to_a_float_when_one_element_is_one() {
        assert_eq!(out("print(sum([1, 2.5]), product([2, 1.5]))"), "3.5 3.0\n");
        // The float can arrive first, last, or alone, and the answer is a float
        // in each. The identity has to carry across the change of type, which
        // is where a fold like this usually goes wrong.
        assert_eq!(out("print(sum([2.5, 1]), sum([2.0]))"), "3.5 2.0\n");
        assert_eq!(out("print(product([2.0]), product([1.5, 2]))"), "2.0 3.0\n");
    }

    #[test]
    fn sum_and_product_refuse_overflow_rather_than_wrapping() {
        // Every integer operation in this language is checked, and these are no
        // different from `+` and `*` written out.
        assert!(err("print(sum([9223372036854775807, 1]))").contains("integer overflow in sum"));
        assert!(
            err("print(product([4294967296, 4294967296]))").contains("integer overflow in product")
        );
    }

    #[test]
    fn sum_and_product_refuse_what_is_not_an_array_of_numbers() {
        assert!(err("print(sum([1, \"two\"]))").contains("an array of numbers"));
        assert!(err("print(product(5))").contains("expects an array"));
    }

    #[test]
    fn sum_does_not_refuse_nan_the_way_min_and_max_do() {
        // `min` and `max` refuse it because there is no answer to a comparison
        // with NaN. These do not compare, so NaN propagates as it does through
        // `+` written out, and the language already holds the value.
        assert_eq!(out("print(sum([float(\"nan\"), 1.0]))"), "nan\n");
        assert!(err("print(min(float(\"nan\"), 1.0))").contains("NaN"));
    }

    #[test]
    fn starts_with_and_ends_with_answer_about_a_prefix_and_a_suffix() {
        assert_eq!(
            out("print(starts_with(\"hello.miru\", \"hello\"), ends_with(\"hello.miru\", \".miru\"))"),
            "true true\n"
        );
        assert_eq!(
            out("print(starts_with(\"hello\", \"jelly\"), ends_with(\"hello\", \"jelly\"))"),
            "false false\n"
        );

        // The dull cases, which are the ones a caller trips over. An empty
        // needle is a prefix and a suffix of everything, including of nothing.
        assert_eq!(
            out("print(starts_with(\"a\", \"\"), ends_with(\"a\", \"\"), starts_with(\"\", \"\"))"),
            "true true true\n"
        );
        // A needle longer than the string cannot be either.
        assert_eq!(
            out("print(starts_with(\"ab\", \"abc\"), ends_with(\"ab\", \"zab\"))"),
            "false false\n"
        );
    }

    #[test]
    fn a_prefix_of_a_multi_byte_string_is_measured_the_same_as_a_character_one() {
        // The claim in the doc comment, checked rather than asserted in prose.
        // Both of these split inside what would be a byte prefix if the
        // comparison could stop part way through a character. `é` is two bytes
        // and the emoji is four.
        assert_eq!(
            out("print(starts_with(\"héllo\", \"hé\"), ends_with(\"héllo\", \"llo\"))"),
            "true true\n"
        );
        assert_eq!(
            out("print(starts_with(\"héllo\", \"h\\u{e8}\"), ends_with(\"a\\u{1F600}\", \"\\u{1F600}\"))"),
            "false true\n"
        );
    }

    #[test]
    fn starts_with_and_ends_with_refuse_an_argument_that_is_not_a_string() {
        assert!(err("print(starts_with(\"a\", 1))").contains("two string arguments"));
        assert!(err("print(ends_with(1, \"a\"))").contains("two string arguments"));
    }

    #[test]
    fn find_returns_a_char_index_or_nil() {
        assert_eq!(
            out("print(find(\"hello\", \"l\"), find(\"hello\", \"z\"))"),
            "2 nil\n"
        );
    }

    #[test]
    fn pop_removes_and_returns_last() {
        assert_eq!(out("let a = [1, 2, 3]\nprint(pop(a), a)"), "3 [1, 2]\n");
    }

    #[test]
    fn pop_on_empty_array_errors() {
        assert!(err("pop([])").contains("empty array"));
    }

    #[test]
    fn index_of_finds_the_first_match_or_gives_nil() {
        assert_eq!(
            out("print(index_of([10, 20, 30], 20), index_of([1], 9))"),
            "1 nil\n"
        );
    }

    /// The trap this release would have shipped if the sentinel had stayed.
    ///
    /// `-1` used to be a safe way to say "not here", because no index could be
    /// negative. Now `-1` is the last element, so a `-1` from `index_of` fed
    /// back into `[]` would answer with it: a wrong answer replacing an error,
    /// which is the failure this project refuses everywhere else. `nil` is not
    /// an index, so the mistake still stops.
    #[test]
    fn a_missing_element_fed_back_into_an_index_is_still_an_error() {
        assert!(err("let a = [1, 2, 3]\nprint(a[index_of(a, 99)])")
            .contains("array index must be an int, not a nil"));
        assert!(err("let s = \"abc\"\nprint(s[find(s, \"z\")])")
            .contains("string index must be an int, not a nil"));
    }

    #[test]
    fn slice_on_arrays_and_strings() {
        assert_eq!(out("print(slice([1, 2, 3, 4], 1, 3))"), "[2, 3]\n");
        assert_eq!(out("print(slice(\"hello\", 1, 4))"), "ell\n");
    }

    #[test]
    fn slice_clamps_out_of_range_bounds() {
        assert_eq!(
            out("print(slice([1, 2], 0, 99), slice([1, 2], 5, 9))"),
            "[1, 2] []\n"
        );
    }

    #[test]
    fn insert_places_a_value_at_a_position() {
        assert_eq!(
            out("let a = [2, 3]\ninsert(a, 0, 1)\nprint(a)"),
            "[1, 2, 3]\n"
        );
        assert_eq!(
            out("let a = [1, 3]\ninsert(a, 1, 2)\nprint(a)"),
            "[1, 2, 3]\n"
        );
    }

    /// The one past-the-end position that means something: where a new last
    /// element goes. `insert(a, len(a), v)` is `push(a, v)`.
    #[test]
    fn insert_at_the_length_appends() {
        assert_eq!(
            out("let a = [1, 2]\ninsert(a, 2, 3)\nprint(a)"),
            "[1, 2, 3]\n"
        );
        assert_eq!(out("let a = []\ninsert(a, 0, 1)\nprint(a)"), "[1]\n");
    }

    /// **`insert` follows indexing, not `slice`.**
    ///
    /// `slice` clamps, because a range that asks for more than exists can
    /// sensibly give what exists. A position is not a range: an index past the
    /// end is arithmetic that went wrong, and appending quietly would hide it.
    #[test]
    fn insert_past_the_end_is_an_error_rather_than_an_append() {
        assert_eq!(
            err("insert([1], 99, 0)"),
            "index 99 is out of range for inserting into an array of length 1"
        );
        // The far end of the same rule. `-1` is now a position rather than a
        // refusal, so what falls off is one further back than it used to be.
        assert_eq!(
            err("insert([1, 2], -3, 0)"),
            "index -3 is out of range for inserting into an array of length 2"
        );
    }

    /// `insert` gives `-1` the element that `a[-1]` gives, and puts the new
    /// value where it was.
    ///
    /// The alternative reading is "at the end", which would make
    /// `insert(a, -1, v)` the same as `push`. That was rejected because it
    /// gives `-1` two meanings in one language: the last element to `[]` and
    /// past the last element to `insert`.
    #[test]
    fn insert_at_a_negative_index_counts_from_the_end() {
        assert_eq!(
            out("let a = [1, 2, 3]\ninsert(a, -1, 9)\nprint(a)"),
            "[1, 2, 9, 3]\n"
        );
        // `-len` is the front, which is the far end of the range.
        assert_eq!(
            out("let a = [1, 2, 3]\ninsert(a, -3, 0)\nprint(a)"),
            "[0, 1, 2, 3]\n"
        );
    }

    #[test]
    fn sort_orders_numbers_and_strings() {
        assert_eq!(out("print(sort([3, 1, 2]))"), "[1, 2, 3]\n");
        assert_eq!(
            out("print(sort([\"c\", \"a\", \"b\"]))"),
            "[\"a\", \"b\", \"c\"]\n"
        );
    }

    #[test]
    fn sort_rejects_mixed_types() {
        assert!(err("sort([1, \"a\"])").contains("all numbers or all strings"));
    }

    #[test]
    fn reverse_flips_arrays_and_strings() {
        assert_eq!(
            out("print(reverse([1, 2, 3]), reverse(\"abc\"))"),
            "[3, 2, 1] cba\n"
        );
    }

    #[test]
    fn abs_of_ints_and_floats() {
        assert_eq!(out("print(abs(-3), abs(-2.5), abs(4))"), "3 2.5 4\n");
    }

    #[test]
    fn mod_follows_the_divisor_and_wraps_a_negative_dividend() {
        // Floored remainder: positive divisor, negative dividend lands in
        // `[0, d)` rather than the negative truncated remainder `%` gives.
        assert_eq!(out("print(mod(-1, 10), mod(-7, 3), mod(7, 3))"), "9 2 1\n");
        // Negative divisor: sign follows the divisor under the floored rule.
        assert_eq!(
            out("print(mod(1, -10), mod(7, -3), mod(-7, -3))"),
            "-9 -2 -1\n"
        );
        // Floats match, including mixed int/float promotion.
        assert_eq!(
            out("print(mod(-7.0, 3.0), mod(-1, 10.0), mod(7.5, 2.0))"),
            "2.0 9.0 1.5\n"
        );
        // Same answer as `%` when both operands are non-negative.
        assert_eq!(out("print(mod(7, 3), 7 % 3)"), "1 1\n");
    }

    #[test]
    fn mod_refuses_a_zero_divisor() {
        assert_eq!(err("mod(1, 0)"), "modulo by zero");
        assert_eq!(err("mod(1.0, 0.0)"), "modulo by zero");
    }

    #[test]
    fn mod_does_not_invent_a_nan_from_an_infinity() {
        // An infinite divisor is where floored and truncated agree, so this
        // answers, and answers what `%` answers.
        assert_eq!(out("print(mod(1.0, float(\"inf\")))"), "1.0\n");
        assert_eq!(out("print(1.0 % float(\"inf\"))"), "1.0\n");
        // The sign rule still holds for an infinite divisor.
        assert_eq!(out("print(mod(1.0, 0.0 - float(\"inf\")))"), "-inf\n");
        // An infinite dividend has no floored remainder, so it refuses rather
        // than answering `nan`, which is what `sqrt` and `pow` do.
        assert_eq!(err("mod(float(\"inf\"), 3.0)"), "mod of an infinite number");
        // A `nan` that arrived in an argument is carried, not refused.
        assert_eq!(out("print(mod(float(\"nan\"), 3.0))"), "nan\n");
    }

    #[test]
    fn mod_is_exact_where_the_textbook_formula_is_not() {
        // `a - d * floor(a / d)` rounds the division and multiplies the error
        // back up: this answered 0.0. `%` is `fmod` and is exact.
        assert_eq!(out("print(mod(float(\"1e20\"), 3.0))"), "1.0\n");
    }

    #[test]
    fn mod_refuses_non_numbers() {
        assert!(err("mod(\"a\", 2)").contains("expects numbers"));
        assert!(err("mod(2, \"a\")").contains("expects numbers"));
    }

    #[test]
    fn min_and_max_over_numbers() {
        assert_eq!(out("print(min(3, 1, 2), max(3, 1, 2))"), "1 3\n");
        assert_eq!(out("print(min(2, 1.5), max(2, 1.5))"), "1.5 2\n");
    }

    #[test]
    fn min_requires_arguments() {
        assert!(err("min()").contains("at least one"));
    }

    #[test]
    fn min_and_max_compare_large_integers_exactly() {
        // Both of these round to the same `f64`, so comparing through one made
        // `max` answer with whichever argument came first. The three lines
        // below have to agree: `sort` orders an all-int array with `i64::cmp`
        // and so does `<`, and nothing should be able to tell a program that
        // the largest of two numbers is the smaller one.
        let big = "9223372036854775807";
        let smaller = "9223372036854775806";
        assert_eq!(
            out(&format!("print(max({smaller}, {big}))")),
            format!("{big}\n")
        );
        assert_eq!(
            out(&format!("print(min({big}, {smaller}))")),
            format!("{smaller}\n")
        );
        assert_eq!(out(&format!("print({smaller} < {big})")), "true\n");
        assert_eq!(
            out(&format!("print(sort([{big}, {smaller}]))")),
            format!("[{smaller}, {big}]\n")
        );
    }

    #[test]
    fn floor_ceil_round_return_ints() {
        assert_eq!(
            out("print(floor(2.7), ceil(2.1), round(2.5), round(2.4))"),
            "2 3 3 2\n"
        );
    }

    #[test]
    fn rounding_passes_ints_through() {
        assert_eq!(out("print(floor(5), ceil(5), round(5))"), "5 5 5\n");
    }

    #[test]
    fn sqrt_returns_a_float() {
        assert_eq!(out("print(sqrt(9), sqrt(16.0))"), "3.0 4.0\n");
    }

    #[test]
    fn sqrt_rejects_negatives() {
        assert!(err("sqrt(-1)").contains("negative"));
    }

    #[test]
    fn pow_is_int_for_int_base_and_nonneg_exp() {
        assert_eq!(
            out("print(pow(2, 10), pow(2, -1), pow(2.0, 3))"),
            "1024 0.5 8.0\n"
        );
    }

    #[test]
    fn int_converts_floats_and_strings() {
        assert_eq!(out("print(int(2.9), int(\"42\"), int(7))"), "2 42 7\n");
    }

    #[test]
    fn float_converts_ints_and_strings() {
        assert_eq!(out("print(float(3), float(\"1.5\"))"), "3.0 1.5\n");
    }

    #[test]
    fn int_rejects_unparseable_strings() {
        assert!(err("int(\"abc\")").contains("cannot convert"));
    }

    #[test]
    fn input_reads_a_line() {
        let output =
            crate::run_capture_with_input("let name = input()\nprint(\"hi\", name)", &["Aiko"])
                .expect("program should run");
        assert_eq!(output, "hi Aiko\n");
    }

    #[test]
    fn input_writes_the_prompt() {
        let output = crate::run_capture_with_input("let x = input(\"name? \")\nprint(x)", &["Bo"])
            .expect("program should run");
        assert_eq!(output, "name? Bo\n");
    }

    #[test]
    fn input_returns_nil_at_end_of_input() {
        let output =
            crate::run_capture_with_input("print(input())", &[]).expect("program should run");
        assert_eq!(output, "nil\n");
    }

    #[test]
    fn map_applies_a_function_to_each_element() {
        assert_eq!(
            out("print(map([1, 2, 3], fn(x) { return x * 2 }))"),
            "[2, 4, 6]\n"
        );
    }

    #[test]
    fn map_over_an_empty_array_is_empty() {
        assert_eq!(out("print(map([], fn(x) { return x }))"), "[]\n");
    }

    #[test]
    fn map_can_apply_a_closure() {
        assert_eq!(
            out("let n = 10\nlet add = fn(x) { return x + n }\nprint(map([1, 2, 3], add))"),
            "[11, 12, 13]\n"
        );
    }

    #[test]
    fn map_can_apply_a_builtin() {
        assert_eq!(out("print(map([-1, -2, 3], abs))"), "[1, 2, 3]\n");
    }

    #[test]
    fn map_rejects_non_arrays() {
        assert!(err("map(5, fn(x) { return x })").contains("expects an array"));
    }

    #[test]
    fn map_rejects_a_non_callable_function() {
        // Eagerly, so an empty array is refused too. `sort` always did this and
        // the other three found out at the first call, which meant no call and
        // no complaint when there was nothing to iterate.
        assert!(err("map([], 3)").contains("map expects a function"));
        assert!(err("map([1, 2], 3)").contains("map expects a function"));
    }

    #[test]
    fn map_checks_arity() {
        assert!(err("map([1, 2])").contains("2 arguments"));
    }

    #[test]
    fn filter_keeps_elements_where_the_predicate_is_truthy() {
        assert_eq!(
            out("print(filter([1, 2, 3, 4], fn(x) { return x % 2 == 0 }))"),
            "[2, 4]\n"
        );
    }

    #[test]
    fn filter_can_drop_every_element() {
        assert_eq!(out("print(filter([1, 2], fn(x) { return false }))"), "[]\n");
    }

    #[test]
    fn filter_treats_nil_and_false_as_falsy() {
        assert_eq!(
            out("print(filter([1, 2, 3], fn(x) { if x == 2 { return nil } return true }))"),
            "[1, 3]\n"
        );
    }

    #[test]
    fn filter_rejects_non_arrays() {
        assert!(err("filter(5, fn(x) { return true })").contains("expects an array"));
    }

    #[test]
    fn filter_rejects_a_non_callable_predicate() {
        assert!(err("filter([1, 2], 3)").contains("filter expects a function"));
    }

    #[test]
    fn filter_checks_arity() {
        assert!(err("filter([1, 2])").contains("2 arguments"));
    }

    #[test]
    fn reduce_folds_from_the_left() {
        assert_eq!(
            out("print(reduce([1, 2, 3, 4], fn(acc, x) { return acc + x }, 0))"),
            "10\n"
        );
    }

    #[test]
    fn reduce_returns_the_initial_value_for_an_empty_array() {
        assert_eq!(
            out("print(reduce([], fn(acc, x) { return acc + x }, 42))"),
            "42\n"
        );
    }

    #[test]
    fn reduce_can_build_up_a_non_number() {
        assert_eq!(
            out("print(reduce([\"a\", \"b\", \"c\"], fn(acc, x) { return acc + x }, \"\"))"),
            "abc\n"
        );
    }

    #[test]
    fn reduce_rejects_non_arrays() {
        assert!(err("reduce(5, fn(acc, x) { return acc }, 0)").contains("expects an array"));
    }

    #[test]
    fn reduce_rejects_a_non_callable_function() {
        assert!(err("reduce([1, 2], 3, 0)").contains("reduce expects a function"));
    }

    #[test]
    fn reduce_checks_arity() {
        assert!(err("reduce([1, 2], fn(acc, x) { return acc })").contains("3 arguments"));
    }
}

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

    /// The pinned list and what `register` actually does are the same set.
    ///
    /// Two comments in this codebase carried a hand-counted total, and both
    /// drifted: one said forty and one said thirty-seven, and neither was
    /// checked by anything. The specification and the stability guarantee both
    /// promise behaviour for "every builtin", so the membership has to be a
    /// fact rather than a recollection.
    ///
    /// Checked in **both** directions on purpose. A name in the list but not
    /// registered is a promise the language does not keep. A builtin registered
    /// but not in the list is worse, because `tests/specification.rs` generates
    /// its checks from this list, so an omission here means the specification is
    /// never asked about that builtin at all.
    ///
    /// The length is not asserted against a literal. `BUILTIN_NAMES` declares
    /// its own size, so a literal here would be a second place to update and a
    /// third to get wrong: exactly the drift this test exists to stop.
    #[test]
    fn the_pinned_list_holds_every_builtin_that_is_registered() {
        let mut globals = Globals::new();
        register(&mut globals);
        for name in BUILTIN_NAMES {
            assert!(
                globals.contains(name),
                "'{name}' is listed but not registered"
            );
        }
        assert_eq!(
            globals.builtin_count(),
            BUILTIN_NAMES.len(),
            "register defines {} builtins but the list names {}",
            globals.builtin_count(),
            BUILTIN_NAMES.len()
        );
    }

    /// Hold the kind counts to the numbers written in prose about them.
    ///
    /// There is no single "number of builtins" that every sentence means. A
    /// claim about `BuiltinFn` counts the `define` calls, a claim about the
    /// caught-error guard counts everything reaching `call_native`, and a claim
    /// about the language counts all of them. Those were one figure until 1.1
    /// and are three now.
    ///
    /// 1.5 shows how little they move together: it added a builtin and the
    /// first of those three did not change, because `now` is not a `define`.
    ///
    /// This was nearly the cause of real damage: two comments saying
    /// "thirty-seven" were read as stale and lined up to be "corrected" to
    /// forty-four, which would have made two right sentences wrong. Counting
    /// first is what caught it, so the count is a test now.
    ///
    /// **When this fails, go and read the comments named below.** One of them
    /// has just become false. Changing the number here without reading them is
    /// how the drift gets back in.
    #[test]
    fn builtin_kind_counts_match_the_comments_that_quote_them() {
        let mut globals = Globals::new();
        register(&mut globals);

        let (mut plain, mut system, mut ambient, mut host) = (0, 0, 0, 0);
        for slot in 0..globals.builtin_count() {
            match globals.get(slot as u16) {
                Some(Value::Builtin(builtin)) => match builtin.func {
                    NativeFn::Plain(_) => plain += 1,
                    NativeFn::System(_) => system += 1,
                    NativeFn::Ambient(_) => ambient += 1,
                },
                Some(Value::HostBuiltin(_)) => host += 1,
                Some(other) => {
                    panic!(
                        "slot {slot} holds a {} rather than a builtin",
                        other.type_name()
                    )
                }
                None => panic!("slot {slot} is empty but is inside the builtin range"),
            }
        }

        assert_eq!(
            plain, 48,
            "{plain} builtins take a BuiltinFn, not 48. Quoted by `Args::into_vec` \
             above and by the trampoline section of docs/architecture.md."
        );
        assert_eq!(
            ambient, 12,
            "{ambient} builtins take an AmbientFn, not 12. This kind arrived in \
             1.5 and is quoted by `Args::into_vec` above."
        );
        assert_eq!(
            plain + system + ambient,
            64,
            "{} builtins reach `call_native`, not 64. Quoted by the caught-error \
             guard in `Vm::call_native`.",
            plain + system + ambient
        );
        assert_eq!(
            host, 4,
            "{host} builtins are higher-order, not 4. Quoted by the same two \
             places, which say the other twenty take a different signature."
        );
        assert_eq!(
            plain + system + ambient + host,
            BUILTIN_NAMES.len(),
            "the four kinds do not add up to the pinned list"
        );
    }
}

/// Every builtin, in registration order. Pinned so the count cannot drift and
/// so the specification has one list to be generated from rather than a second
/// hand-written one that can disagree.
pub const BUILTIN_NAMES: [&str; 68] = [
    "print",
    "eprint",
    "exit",
    "len",
    "push",
    "insert",
    "str",
    "type",
    "is_error",
    "range",
    "keys",
    "values",
    "has",
    "remove",
    "upper",
    "lower",
    "ord",
    "chr",
    "repeat",
    "pad_left",
    "pad_right",
    "copy",
    "trim",
    "replace",
    "split",
    "join",
    "contains",
    "find",
    "starts_with",
    "ends_with",
    "pop",
    "index_of",
    "slice",
    "reverse",
    "abs",
    "mod",
    "min",
    "max",
    "floor",
    "ceil",
    "round",
    "sqrt",
    "pow",
    "sum",
    "product",
    "int",
    "float",
    "input",
    "read_file",
    "write_file",
    "file_exists",
    "args",
    "now",
    "sleep",
    "random",
    "random_int",
    "seed",
    "read_key",
    "key_ready",
    "clear",
    "move_to",
    "hide_cursor",
    "show_cursor",
    "term_size",
    "sort",
    "map",
    "filter",
    "reduce",
];