ahk 0.3.1

The ahk language: a lexer, an AST, a parser and an interpreter for AutoHotkey-style scripts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
//! The built-ins the language carries.
//!
//! AutoHotkey v2 keeps its built-ins in a flat table: a name, a handler,
//! an arity, and a byte that picks the flavour of a handler that several
//! names share. This module is that table in the same shape, so that the
//! language can grow to the whole of v2 without the dispatch becoming a
//! match with four hundred arms.
//!
//! The `kind` of a row is the record of the binary: it keeps its names
//! in two tables, and the kind says which one a name came from. It is
//! not a rule of the parser. v2 has no kind of command -- the
//! documentation says that the parentheses of a call may be left out
//! when the answer is not needed and the name is at the start of the
//! line, and that every function may be written that way -- so the
//! parser decides by the syntax alone.
//!
//! The arity is in the row too, and it is the arity of the binary, so
//! the runtime can answer "Too few parameters passed to function."
//! without every handler checking for itself. A handler that cannot
//! honour a parameter answers with the reason.
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

pub(crate) use crate::date::{date_add, date_diff, format_time};
pub(crate) use crate::dialogs::{dir_select, file_select, input_box, tray_tip};
use crate::dll::{Convention, NativeArg, NativeCall, NativeFailureKind, NativeType, NativeValue};
pub(crate) use crate::files::{
    dir_copy, dir_move, download, file_append, file_copy, file_encoding, file_get_attrib,
    file_get_size, file_get_time, file_install, file_move, file_open, file_read, file_set_attrib,
    file_set_time, ini_delete, ini_read, ini_write,
};
pub(crate) use crate::hotkeys::{
    get_key_state, hotif, hotif_window, hotkey, hotstring, install_hook, key_history, list_hotkeys,
};
pub(crate) use crate::pictures::{image_search, load_picture};
use crate::runtime::{
    Runtime, RuntimeError, RuntimeFailure, TypeName, Value, WindowAnswer, expected_type,
};
pub(crate) use crate::settings::{
    coord_mode, get_key_name, get_key_sc, get_key_vk, send_event, send_input, send_level,
    send_play, send_text, set_control_delay, set_default_mouse_speed, set_detect_hidden_text,
    set_detect_hidden_windows, set_key_delay, set_mouse_delay, set_reg_view,
    set_store_caps_lock_mode, set_title_match_mode, set_win_delay,
};
use core::cmp::Ordering;
use core::sync::atomic::{AtomicU32, Ordering as AtomicOrder};

/// What kind of built-in a name is.
///
/// The two kinds are the two tables of the binary. The parser does not
/// use them: v2 lets every function be written without parentheses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuiltinKind {
    /// A name of the function table of the binary.
    Function,
    /// A name of the command table of the binary.
    Command,
}

/// The shape of one parameter of a built-in.
///
/// The shape is what the dialect says about the parameter: the value of an
/// expression, the name of a variable of the script, or the name of a
/// variable that the built-in writes into. The v2 writes a reference with
/// the `&`, and the v1 writes the name of a variable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Parameter {
    /// The parameter is an expression, and the value of it reaches the
    /// handler.
    Value,
    /// The parameter is a reference that the caller passes, written with
    /// the `&` of the v2.
    Reference,
    /// The parameter is a reference the caller passes, and v2 declares it as
    /// a value of the kind `VarRef`: a value of another kind is refused with
    /// "requires a VarRef, but received ...", and the name of the built-in is
    /// in the `What` of the failure.
    ///
    /// Measured on the binary of v2.0.19 on 2026-11-09: `MonitorGet(1, 9)` is
    /// "Parameter #2 of MonitorGet requires a VarRef, but received an
    /// Integer." with "MonitorGet" in the `What`, while the output variable of
    /// `RegExMatch` answers "a variable reference" with the empty `What`.
    VarRef,
    /// The parameter is the name of a variable of the script, and the value
    /// of that variable reaches the handler. The commands of the v1 read
    /// their input this way.
    Variable,
    /// The parameter is the name of a variable of the script, and the
    /// handler writes into it. The commands of the v1 write their output
    /// this way.
    Output,
    /// The parameter is the name of a thing of the machine -- a variable of
    /// the environment -- and the text of it reaches the handler. The name
    /// may not be blank, and the commands of the v1 that name a thing of
    /// the machine are checked at the load.
    Name,
}

/// What a built-in does with its arguments.
///
/// The variant is the byte that picks the flavour of a handler that
/// several names share. `Ceil` and `Floor` are one handler with two
/// variants, the way they are in the binary.
pub type BuiltinHandler =
    for<'a> fn(&mut Runtime<'a>, &[Value], u32, u8) -> Result<Value, RuntimeError>;

/// One built-in: the name, the arity, and the handler.
pub struct Builtin {
    /// The name, as AutoHotkey v2 spells it.
    pub name: &'static str,
    /// Whether it is a function or a command.
    pub kind: BuiltinKind,
    /// The fewest parameters it takes.
    pub min: u8,
    /// The most it takes. 255 means any number.
    pub max: u8,
    /// The flavour of the handler.
    pub variant: u8,
    /// The shape of each parameter.
    pub parameters: &'static [Parameter],
    /// What it does.
    pub handler: BuiltinHandler,
}

impl Builtin {
    /// Whether the parameter at this place is written back.
    ///
    /// The reference of the v2 is written back by the caller that passes
    /// it, and the output of the v1 is written back by the built-in that
    /// writes into the variable of the script.
    pub fn writes_back(&self, index: usize) -> bool {
        matches!(
            self.parameters.get(index),
            Some(Parameter::Reference) | Some(Parameter::Output)
        )
    }
}

/// The built-ins the language carries.
///
/// The arities are AutoHotkey v2's, read out of the table in the binary:
/// the function entries state them, and the command entries keep theirs
/// in a packing that was not decoded, so the command rows carry the
/// arity the documentation gives.
pub const BUILTINS: &[Builtin] = &[
    // -- the numbers -------------------------------------------------------------
    Builtin {
        name: "Abs",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: abs,
    },
    Builtin {
        name: "ACos",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: inverse_trigonometry,
    },
    Builtin {
        name: "ASin",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: inverse_trigonometry,
    },
    Builtin {
        name: "ATan",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: inverse_trigonometry,
    },
    Builtin {
        name: "Ceil",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: round_to,
    },
    Builtin {
        name: "Cos",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: trigonometry,
    },
    Builtin {
        name: "Exp",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: exponential,
    },
    Builtin {
        name: "Floor",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: round_to,
    },
    Builtin {
        name: "Ln",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: logarithm,
    },
    Builtin {
        name: "Log",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: logarithm,
    },
    Builtin {
        name: "Max",
        kind: BuiltinKind::Function,
        min: 1,
        max: 255,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: extreme,
    },
    Builtin {
        name: "Min",
        kind: BuiltinKind::Function,
        min: 1,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: extreme,
    },
    Builtin {
        name: "Mod",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: modulo,
    },
    Builtin {
        name: "NumGet",
        kind: BuiltinKind::Function,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: num_get,
    },
    Builtin {
        name: "NumPut",
        kind: BuiltinKind::Function,
        min: 3,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: num_put,
    },
    Builtin {
        name: "Random",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: random,
    },
    Builtin {
        name: "Round",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: round_to_digits,
    },
    Builtin {
        name: "Sin",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: trigonometry,
    },
    Builtin {
        name: "Sqrt",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: square_root,
    },
    Builtin {
        name: "Tan",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: trigonometry,
    },
    // -- the text ----------------------------------------------------------------
    Builtin {
        name: "Chr",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: chr,
    },
    Builtin {
        name: "Format",
        kind: BuiltinKind::Function,
        min: 1,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: format,
    },
    Builtin {
        name: "InStr",
        kind: BuiltinKind::Function,
        min: 2,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: in_str,
    },
    Builtin {
        name: "LTrim",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: trim,
    },
    Builtin {
        name: "Ord",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: ord,
    },
    Builtin {
        name: "RTrim",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: trim,
    },
    Builtin {
        name: "Sort",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sort,
    },
    Builtin {
        name: "StrCompare",
        kind: BuiltinKind::Function,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_compare,
    },
    Builtin {
        name: "StrLen",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_len,
    },
    Builtin {
        name: "StrLower",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: change_case,
    },
    Builtin {
        name: "StrReplace",
        kind: BuiltinKind::Function,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Reference,
            Parameter::Value,
        ],
        handler: str_replace,
    },
    Builtin {
        name: "StrUpper",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: change_case,
    },
    Builtin {
        name: "SubStr",
        kind: BuiltinKind::Function,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sub_str,
    },
    Builtin {
        name: "Trim",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: trim,
    },
    // -- the predicates --------------------------------------------------------------
    Builtin {
        name: "IsAlnum",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 7,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsAlpha",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 8,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsDigit",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsFloat",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 3,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsInteger",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsLower",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 10,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsNumber",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsObject",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: is_object,
    },
    Builtin {
        name: "IsSpace",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 11,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsTime",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsUpper",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 9,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "IsXDigit",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 6,
        parameters: &[Parameter::Value],
        handler: is_value,
    },
    Builtin {
        name: "Type",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: type_of,
    },
    // -- the patterns ----------------------------------------------------------------
    Builtin {
        name: "RegExMatch",
        kind: BuiltinKind::Function,
        min: 2,
        max: 4,
        variant: 0,
        parameters: &[
            Parameter::Value,
            Parameter::Value,
            Parameter::Reference,
            Parameter::Value,
        ],
        handler: regex_match,
    },
    Builtin {
        name: "RegExReplace",
        kind: BuiltinKind::Function,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Reference,
            Parameter::Value,
            Parameter::Value,
        ],
        handler: regex_replace,
    },
    // -- the screen --------------------------------------------------------------
    Builtin {
        name: "Click",
        kind: BuiltinKind::Function,
        min: 0,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: click,
    },
    Builtin {
        name: "MouseGetPos",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Value,
        ],
        handler: mouse_get_pos,
    },
    Builtin {
        name: "MouseMove",
        kind: BuiltinKind::Command,
        min: 2,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: mouse_move,
    },
    Builtin {
        name: "PixelGetColor",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: pixel_get_color,
    },
    Builtin {
        name: "PixelSearch",
        kind: BuiltinKind::Command,
        min: 7,
        max: 8,
        variant: 0,
        parameters: &[
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
        ],
        handler: pixel_search,
    },
    Builtin {
        name: "Screenshot",
        kind: BuiltinKind::Command,
        min: 5,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: screenshot,
    },
    // -- the windows -------------------------------------------------------------
    Builtin {
        name: "WinActive",
        kind: BuiltinKind::Function,
        min: 0,
        max: 4,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: window_active,
    },
    Builtin {
        name: "WinExist",
        kind: BuiltinKind::Function,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: window_exist,
    },
    Builtin {
        name: "WinGetTitle",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_title,
    },
    // -- the rest ----------------------------------------------------------------
    Builtin {
        name: "MsgBox",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: msg_box,
    },
    Builtin {
        name: "Run",
        kind: BuiltinKind::Command,
        min: 1,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: run,
    },
    Builtin {
        name: "Send",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: send,
    },
    Builtin {
        name: "Sleep",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sleep,
    },
    // -- the names this runtime answers -------------------------------------------
    Builtin {
        name: "ClipWait",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: clip_wait,
    },
    Builtin {
        name: "DirCreate",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: dir_create,
    },
    Builtin {
        name: "DirDelete",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: dir_delete,
    },
    Builtin {
        name: "DirExist",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: dir_exist,
    },
    Builtin {
        name: "EnvGet",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: env_get,
    },
    Builtin {
        name: "EnvSet",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: env_set,
    },
    Builtin {
        name: "Exit",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: exit_script,
    },
    Builtin {
        name: "ExitApp",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: exit_script,
    },
    Builtin {
        name: "FileAppend",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_append,
    },
    Builtin {
        name: "FileDelete",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_delete,
    },
    Builtin {
        name: "FileExist",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_exist,
    },
    Builtin {
        name: "FileRead",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_read,
    },
    Builtin {
        name: "GetMethod",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: get_method,
    },
    Builtin {
        name: "HasBase",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: has_base,
    },
    Builtin {
        name: "HasMethod",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: has_method,
    },
    Builtin {
        name: "HasProp",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: has_prop,
    },
    Builtin {
        name: "IsSet",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Reference],
        handler: is_set,
    },
    Builtin {
        name: "IsSetRef",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Reference],
        handler: is_set_ref,
    },
    Builtin {
        name: "KeyWait",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: key_wait,
    },
    Builtin {
        name: "RunWait",
        kind: BuiltinKind::Function,
        min: 1,
        max: 4,
        variant: 0,
        parameters: &[
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Reference,
        ],
        handler: run,
    },
    Builtin {
        name: "SendMode",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: send_mode,
    },
    Builtin {
        name: "SetKeyDelay",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_key_delay,
    },
    Builtin {
        name: "SetTimer",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_timer,
    },
    Builtin {
        name: "SplitPath",
        kind: BuiltinKind::Function,
        min: 1,
        max: 6,
        variant: 0,
        parameters: &[
            Parameter::Value,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
        ],
        handler: split_path,
    },
    Builtin {
        name: "StrSplit",
        kind: BuiltinKind::Command,
        min: 1,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_split,
    },
    Builtin {
        name: "VarSetStrCapacity",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Reference, Parameter::Value],
        handler: var_set_str_capacity,
    },
    // -- the names of Windows ------------------------------------------------
    Builtin {
        name: "BlockInput",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: block_input,
    },
    Builtin {
        name: "CallbackCreate",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: callback_create,
    },
    Builtin {
        name: "CallbackFree",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: callback_free,
    },
    Builtin {
        name: "CaretGetPos",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Reference, Parameter::Reference],
        handler: caret_get_pos,
    },
    Builtin {
        name: "ComCall",
        kind: BuiltinKind::Function,
        min: 2,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_call,
    },
    Builtin {
        name: "ComObjActive",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_active,
    },
    Builtin {
        name: "ComObjConnect",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_connect,
    },
    Builtin {
        name: "ComObjFlags",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_flags,
    },
    Builtin {
        name: "ComObjFromPtr",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_from_ptr,
    },
    Builtin {
        name: "ComObjGet",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_get,
    },
    Builtin {
        name: "ComObjQuery",
        kind: BuiltinKind::Function,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_query,
    },
    Builtin {
        name: "ComObjType",
        kind: BuiltinKind::Function,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_type,
    },
    Builtin {
        name: "ComObjValue",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: com_obj_value,
    },
    Builtin {
        name: "ControlAddItem",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_add_item,
    },
    Builtin {
        name: "ControlChooseIndex",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_choose_index,
    },
    Builtin {
        name: "ControlChooseString",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_choose_string,
    },
    Builtin {
        name: "ControlClick",
        kind: BuiltinKind::Command,
        min: 0,
        max: 8,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_act,
    },
    Builtin {
        name: "ControlDeleteItem",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_delete_item,
    },
    Builtin {
        name: "ControlFindItem",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_find_item,
    },
    Builtin {
        name: "ControlFocus",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: control_act,
    },
    Builtin {
        name: "ControlGetChecked",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_checked,
    },
    Builtin {
        name: "ControlGetChoice",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_choice,
    },
    Builtin {
        name: "ControlGetClassNN",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_classnn,
    },
    Builtin {
        name: "ControlGetEnabled",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: control_flag,
    },
    Builtin {
        name: "ControlGetExStyle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 127,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "ControlGetFocus",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_focus,
    },
    Builtin {
        name: "ControlGetHwnd",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_hwnd,
    },
    Builtin {
        name: "ControlGetIndex",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_index,
    },
    Builtin {
        name: "ControlGetItems",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_items,
    },
    Builtin {
        name: "ControlGetPos",
        kind: BuiltinKind::Command,
        min: 0,
        max: 9,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_pos,
    },
    Builtin {
        name: "ControlGetStyle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 127,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "ControlGetText",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_get_text,
    },
    Builtin {
        name: "ControlGetVisible",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_flag,
    },
    Builtin {
        name: "ControlHide",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_visibility,
    },
    Builtin {
        name: "ControlHideDropDown",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_hide_drop_down,
    },
    Builtin {
        name: "ControlMove",
        kind: BuiltinKind::Command,
        min: 0,
        max: 9,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_move,
    },
    Builtin {
        name: "ControlSend",
        kind: BuiltinKind::Command,
        min: 1,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_send,
    },
    Builtin {
        name: "ControlSendText",
        kind: BuiltinKind::Command,
        min: 1,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_send_text,
    },
    Builtin {
        name: "ControlSetChecked",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_set_checked,
    },
    Builtin {
        name: "ControlSetEnabled",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_set_enabled,
    },
    Builtin {
        name: "ControlSetExStyle",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 127,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "ControlSetStyle",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 127,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "ControlSetText",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_set_text,
    },
    Builtin {
        name: "ControlShow",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_show,
    },
    Builtin {
        name: "ControlShowDropDown",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: control_show_drop_down,
    },
    Builtin {
        name: "DetectHiddenText",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_detect_hidden_text,
    },
    Builtin {
        name: "DetectHiddenWindows",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_detect_hidden_windows,
    },
    Builtin {
        name: "DllCall",
        kind: BuiltinKind::Function,
        min: 1,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: dll_call,
    },
    Builtin {
        name: "DriveEject",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_eject,
    },
    Builtin {
        name: "DriveGetCapacity",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_capacity,
    },
    Builtin {
        name: "DriveGetFilesystem",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_filesystem,
    },
    Builtin {
        name: "DriveGetLabel",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_label,
    },
    Builtin {
        name: "DriveGetList",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_list,
    },
    Builtin {
        name: "DriveGetSerial",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_serial,
    },
    Builtin {
        name: "DriveGetSpaceFree",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_space_free,
    },
    Builtin {
        name: "DriveGetStatus",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_status,
    },
    Builtin {
        name: "DriveGetStatusCD",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_status_cd,
    },
    Builtin {
        name: "DriveGetType",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_get_type,
    },
    Builtin {
        name: "DriveLock",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_lock,
    },
    Builtin {
        name: "DriveRetract",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_retract,
    },
    Builtin {
        name: "DriveSetLabel",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_set_label,
    },
    Builtin {
        name: "DriveUnlock",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: drive_unlock,
    },
    Builtin {
        name: "Edit",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: edit,
    },
    Builtin {
        name: "EditGetCurrentCol",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_get_current_col,
    },
    Builtin {
        name: "EditGetCurrentLine",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_get_current_line,
    },
    Builtin {
        name: "EditGetLine",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_get_line,
    },
    Builtin {
        name: "EditGetLineCount",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_get_line_count,
    },
    Builtin {
        name: "EditGetSelectedText",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_get_selected_text,
    },
    Builtin {
        name: "EditPaste",
        kind: BuiltinKind::Command,
        min: 2,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: edit_paste,
    },
    Builtin {
        name: "FileCreateShortcut",
        kind: BuiltinKind::Command,
        min: 2,
        max: 9,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_create_shortcut,
    },
    Builtin {
        name: "FileGetShortcut",
        kind: BuiltinKind::Command,
        min: 1,
        max: 8,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_get_shortcut,
    },
    Builtin {
        name: "FileGetVersion",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_get_version,
    },
    Builtin {
        name: "FileRecycle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_recycle,
    },
    Builtin {
        name: "FileRecycleEmpty",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_recycle_empty,
    },
    Builtin {
        name: "GroupActivate",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: group_activate,
    },
    Builtin {
        name: "GroupAdd",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: group_add,
    },
    Builtin {
        name: "GroupClose",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: group_close,
    },
    Builtin {
        name: "GroupDeactivate",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: group_close,
    },
    Builtin {
        name: "GuiCtrlFromHwnd",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: gui_ctrl_from_hwnd,
    },
    Builtin {
        name: "GuiFromHwnd",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: gui_from_hwnd,
    },
    Builtin {
        name: "IL_Add",
        kind: BuiltinKind::Command,
        min: 2,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: il_add,
    },
    Builtin {
        name: "IL_Create",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: il_create,
    },
    Builtin {
        name: "IL_Destroy",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: il_destroy,
    },
    Builtin {
        name: "ListViewGetContent",
        kind: BuiltinKind::Command,
        min: 0,
        max: 6,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: list_view_get_content,
    },
    Builtin {
        name: "MenuFromHandle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: menu_from_handle,
    },
    Builtin {
        name: "MenuSelect",
        kind: BuiltinKind::Command,
        min: 0,
        max: 11,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: menu_select,
    },
    Builtin {
        name: "MonitorGet",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: monitor_get,
    },
    Builtin {
        name: "MonitorGetCount",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: monitor_get_count,
    },
    Builtin {
        name: "MonitorGetName",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: monitor_get_name,
    },
    Builtin {
        name: "MonitorGetPrimary",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: monitor_get_primary,
    },
    Builtin {
        name: "MonitorGetWorkArea",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: monitor_get_work_area,
    },
    Builtin {
        name: "ObjAddRef",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_add_ref,
    },
    Builtin {
        name: "ObjBindMethod",
        kind: BuiltinKind::Function,
        min: 1,
        max: 255,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_bind_method,
    },
    // -- the object model ---------------------------------------------------------
    Builtin {
        name: "ObjFromPtr",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_from_ptr,
    },
    Builtin {
        name: "ObjFromPtrAddRef",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_from_ptr_add_ref,
    },
    Builtin {
        name: "ObjGetBase",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_get_base,
    },
    Builtin {
        name: "ObjGetCapacity",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_get_capacity,
    },
    Builtin {
        name: "ObjHasOwnProp",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_has_own_prop,
    },
    Builtin {
        name: "ObjOwnPropCount",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_own_prop_count,
    },
    Builtin {
        name: "ObjOwnProps",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_own_props,
    },
    Builtin {
        name: "ObjPtr",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_ptr,
    },
    Builtin {
        name: "ObjPtrAddRef",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_ptr_add_ref,
    },
    Builtin {
        name: "ObjRelease",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: obj_add_ref,
    },
    Builtin {
        name: "ObjSetBase",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_set_base,
    },
    Builtin {
        name: "ObjSetCapacity",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: obj_set_capacity,
    },
    Builtin {
        name: "OnClipboardChange",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: on_clipboard_change,
    },
    Builtin {
        name: "OnMessage",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: on_message,
    },
    Builtin {
        name: "OutputDebug",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: output_debug,
    },
    Builtin {
        name: "PostMessage",
        kind: BuiltinKind::Command,
        min: 1,
        max: 8,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: post_message,
    },
    Builtin {
        name: "ProcessClose",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_close,
    },
    Builtin {
        name: "ProcessExist",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_exist,
    },
    Builtin {
        name: "ProcessGetName",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_get_name,
    },
    Builtin {
        name: "ProcessGetParent",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_get_parent,
    },
    Builtin {
        name: "ProcessGetPath",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_get_path,
    },
    Builtin {
        name: "ProcessSetPriority",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_set_priority,
    },
    Builtin {
        name: "ProcessWait",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_wait,
    },
    Builtin {
        name: "ProcessWaitClose",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: process_wait_close,
    },
    Builtin {
        name: "RegCreateKey",
        kind: BuiltinKind::Function,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: reg_create_key,
    },
    Builtin {
        name: "RegDelete",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: reg_delete,
    },
    Builtin {
        name: "RegDeleteKey",
        kind: BuiltinKind::Function,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: reg_delete_key,
    },
    Builtin {
        name: "RegRead",
        kind: BuiltinKind::Function,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: reg_read,
    },
    Builtin {
        name: "RegWrite",
        kind: BuiltinKind::Function,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: reg_write,
    },
    Builtin {
        name: "RunAs",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: run_as,
    },
    Builtin {
        name: "SendMessage",
        kind: BuiltinKind::Command,
        min: 1,
        max: 9,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: send_message,
    },
    Builtin {
        name: "SetCapsLockState",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_caps_lock_state,
    },
    Builtin {
        name: "SetControlDelay",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_control_delay,
    },
    Builtin {
        name: "SetNumLockState",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_num_lock_state,
    },
    Builtin {
        name: "SetRegView",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_reg_view,
    },
    Builtin {
        name: "SetScrollLockState",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_scroll_lock_state,
    },
    Builtin {
        name: "SetTitleMatchMode",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_title_match_mode,
    },
    Builtin {
        name: "SetWinDelay",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_win_delay,
    },
    Builtin {
        name: "Shutdown",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: shutdown,
    },
    Builtin {
        name: "SoundBeep",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_beep,
    },
    Builtin {
        name: "SoundGetInterface",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_get_interface,
    },
    Builtin {
        name: "SoundGetMute",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_get_mute,
    },
    Builtin {
        name: "SoundGetName",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_get_name,
    },
    Builtin {
        name: "SoundGetVolume",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_get_volume,
    },
    Builtin {
        name: "SoundPlay",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_play,
    },
    Builtin {
        name: "SoundSetMute",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_set_mute,
    },
    Builtin {
        name: "SoundSetVolume",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sound_set_volume,
    },
    Builtin {
        name: "StatusBarGetText",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: status_bar_get_text,
    },
    Builtin {
        name: "StatusBarWait",
        kind: BuiltinKind::Command,
        min: 0,
        max: 8,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: status_bar_wait,
    },
    Builtin {
        name: "StrGet",
        kind: BuiltinKind::Function,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_get,
    },
    Builtin {
        name: "StrPtr",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_ptr,
    },
    Builtin {
        name: "StrPut",
        kind: BuiltinKind::Function,
        min: 1,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_put,
    },
    Builtin {
        name: "SysGet",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sys_get,
    },
    Builtin {
        name: "SysGetIPAddresses",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: sys_get_ip_addresses,
    },
    Builtin {
        name: "ToolTip",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: tooltip,
    },
    Builtin {
        name: "TraySetIcon",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: tray_set_icon,
    },
    Builtin {
        name: "TrayTip",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: tray_tip,
    },
    Builtin {
        name: "WinActivate",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_activate,
    },
    Builtin {
        name: "WinActivateBottom",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_activate_bottom,
    },
    Builtin {
        name: "WinClose",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_close,
    },
    Builtin {
        name: "WinGetClass",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_class,
    },
    Builtin {
        name: "WinGetControls",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_controls,
    },
    Builtin {
        name: "WinGetControlsHwnd",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_controls_hwnd,
    },
    Builtin {
        name: "WinGetCount",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_count,
    },
    Builtin {
        name: "WinGetExStyle",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_style,
    },
    Builtin {
        name: "WinGetID",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_id,
    },
    Builtin {
        name: "WinGetIDLast",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_id_last,
    },
    Builtin {
        name: "WinGetList",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_list,
    },
    Builtin {
        name: "WinGetMinMax",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_min_max,
    },
    Builtin {
        name: "WinGetPID",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_pid,
    },
    Builtin {
        name: "WinGetPos",
        kind: BuiltinKind::Command,
        min: 0,
        max: 8,
        variant: 0,
        parameters: &[
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
        ],
        handler: win_get_pos,
    },
    Builtin {
        name: "WinGetClientPos",
        kind: BuiltinKind::Command,
        min: 0,
        max: 8,
        variant: 0,
        parameters: &[
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
        ],
        handler: win_get_client_pos,
    },
    Builtin {
        name: "WinGetProcessName",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_process,
    },
    Builtin {
        name: "WinGetProcessPath",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: win_get_process,
    },
    Builtin {
        name: "WinGetStyle",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_style,
    },
    Builtin {
        name: "WinGetText",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_text,
    },
    Builtin {
        name: "WinGetTransColor",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_trans_color,
    },
    Builtin {
        name: "WinGetTransparent",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_get_transparent,
    },
    Builtin {
        name: "WinHide",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_hide,
    },
    Builtin {
        name: "WinKill",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_kill,
    },
    Builtin {
        name: "WinMaximize",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_maximize,
    },
    Builtin {
        name: "WinMinimize",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_minimize,
    },
    Builtin {
        name: "WinMinimizeAll",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_minimize_all,
    },
    Builtin {
        name: "WinMinimizeAllUndo",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_minimize_all_undo,
    },
    Builtin {
        name: "WinMove",
        kind: BuiltinKind::Command,
        min: 0,
        max: 8,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_move,
    },
    Builtin {
        name: "WinMoveBottom",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_move_bottom,
    },
    Builtin {
        name: "WinMoveTop",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_move_top,
    },
    Builtin {
        name: "WinRedraw",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_redraw,
    },
    Builtin {
        name: "WinRestore",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_restore,
    },
    Builtin {
        name: "WinSetAlwaysOnTop",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_set_always_on_top,
    },
    Builtin {
        name: "WinSetEnabled",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_set_enabled,
    },
    Builtin {
        name: "WinSetExStyle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_style,
    },
    Builtin {
        name: "WinSetRegion",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_set_region,
    },
    Builtin {
        name: "WinSetStyle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_style,
    },
    Builtin {
        name: "WinSetTitle",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_set_title,
    },
    Builtin {
        name: "WinSetTransColor",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 100,
        parameters: &[Parameter::Value],
        handler: win_trans_color,
    },
    Builtin {
        name: "WinSetTransparent",
        kind: BuiltinKind::Command,
        min: 1,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_set_transparent,
    },
    Builtin {
        name: "WinShow",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_show,
    },
    Builtin {
        name: "WinWait",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_wait,
    },
    Builtin {
        name: "WinWaitActive",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_wait_active,
    },
    Builtin {
        name: "WinWaitClose",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_wait_close,
    },
    Builtin {
        name: "WinWaitNotActive",
        kind: BuiltinKind::Command,
        min: 0,
        max: 5,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: win_wait_not_active,
    },
    // -- the hotkeys --------------------------------------------------------
    Builtin {
        name: "GetKeyState",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: get_key_state,
    },
    Builtin {
        name: "HotIf",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: hotif,
    },
    Builtin {
        name: "HotIfWinActive",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: hotif_window,
    },
    Builtin {
        name: "HotIfWinExist",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: hotif_window,
    },
    Builtin {
        name: "HotIfWinNotActive",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: hotif_window,
    },
    Builtin {
        name: "HotIfWinNotExist",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 3,
        parameters: &[Parameter::Value],
        handler: hotif_window,
    },
    Builtin {
        name: "Hotkey",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: hotkey,
    },
    Builtin {
        name: "Hotstring",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: hotstring,
    },
    Builtin {
        name: "InstallKeybdHook",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: install_hook,
    },
    Builtin {
        name: "InstallMouseHook",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: install_hook,
    },
    Builtin {
        name: "KeyHistory",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: key_history,
    },
    Builtin {
        name: "ListHotkeys",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 1,
        parameters: &[Parameter::Value],
        handler: list_hotkeys,
    },
    // -- the names of the script that this runtime cannot answer -----------------
    Builtin {
        name: "CoordMode",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: coord_mode,
    },
    Builtin {
        name: "Critical",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 108,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "DateAdd",
        kind: BuiltinKind::Command,
        min: 3,
        max: 3,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: date_add,
    },
    Builtin {
        name: "DateDiff",
        kind: BuiltinKind::Command,
        min: 3,
        max: 3,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: date_diff,
    },
    Builtin {
        name: "DirCopy",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: dir_copy,
    },
    Builtin {
        name: "DirMove",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: dir_move,
    },
    Builtin {
        name: "DirSelect",
        kind: BuiltinKind::Command,
        min: 0,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: dir_select,
    },
    Builtin {
        name: "Download",
        kind: BuiltinKind::Command,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: download,
    },
    Builtin {
        name: "FileCopy",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 6,
        parameters: &[Parameter::Value],
        handler: file_copy,
    },
    Builtin {
        name: "FileEncoding",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_encoding,
    },
    Builtin {
        name: "FileGetAttrib",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_get_attrib,
    },
    Builtin {
        name: "FileGetSize",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_get_size,
    },
    Builtin {
        name: "FileGetTime",
        kind: BuiltinKind::Command,
        min: 0,
        max: 2,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_get_time,
    },
    Builtin {
        name: "FileInstall",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_install,
    },
    Builtin {
        name: "FileMove",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 6,
        parameters: &[Parameter::Value],
        handler: file_move,
    },
    Builtin {
        name: "FileOpen",
        kind: BuiltinKind::Function,
        min: 2,
        max: 3,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_open,
    },
    Builtin {
        name: "FileSelect",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: file_select,
    },
    Builtin {
        name: "FileSetAttrib",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_set_attrib,
    },
    Builtin {
        name: "FileSetTime",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: file_set_time,
    },
    Builtin {
        name: "FormatTime",
        kind: BuiltinKind::Function,
        min: 0,
        max: 2,
        variant: 2,
        parameters: &[Parameter::Value],
        handler: format_time,
    },
    Builtin {
        name: "GetKeyName",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: get_key_name,
    },
    Builtin {
        name: "GetKeySC",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: get_key_sc,
    },
    Builtin {
        name: "GetKeyVK",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: get_key_vk,
    },
    Builtin {
        name: "ImageSearch",
        kind: BuiltinKind::Command,
        min: 7,
        max: 7,
        variant: 0,
        parameters: &[
            Parameter::Reference,
            Parameter::Reference,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
            Parameter::Value,
        ],
        handler: image_search,
    },
    Builtin {
        name: "IniDelete",
        kind: BuiltinKind::Command,
        min: 2,
        max: 3,
        variant: 6,
        parameters: &[Parameter::Value],
        handler: ini_delete,
    },
    Builtin {
        name: "IniRead",
        kind: BuiltinKind::Command,
        min: 1,
        max: 4,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: ini_read,
    },
    Builtin {
        name: "IniWrite",
        kind: BuiltinKind::Command,
        min: 3,
        max: 4,
        variant: 4,
        parameters: &[Parameter::Value],
        handler: ini_write,
    },
    Builtin {
        name: "InputBox",
        kind: BuiltinKind::Command,
        min: 0,
        max: 4,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: input_box,
    },
    Builtin {
        name: "IsLabel",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: is_label,
    },
    Builtin {
        name: "ListLines",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: list_lines,
    },
    Builtin {
        name: "ListVars",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: list_vars,
    },
    Builtin {
        name: "LoadPicture",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 0,
        parameters: &[Parameter::Value, Parameter::Value, Parameter::Reference],
        handler: load_picture,
    },
    Builtin {
        name: "MouseClick",
        kind: BuiltinKind::Command,
        min: 0,
        max: 7,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: mouse_click,
    },
    Builtin {
        name: "MouseClickDrag",
        kind: BuiltinKind::Command,
        min: 0,
        max: 7,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: mouse_click_drag,
    },
    Builtin {
        name: "OnError",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: on_error,
    },
    Builtin {
        name: "OnExit",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: on_exit,
    },
    Builtin {
        name: "Pause",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: pause,
    },
    Builtin {
        name: "Persistent",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: persistent,
    },
    Builtin {
        name: "Reload",
        kind: BuiltinKind::Command,
        min: 0,
        max: 0,
        variant: 112,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "SendEvent",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: send_event,
    },
    Builtin {
        name: "SendInput",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: send_input,
    },
    Builtin {
        name: "SendLevel",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: send_level,
    },
    Builtin {
        name: "SendPlay",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: send_play,
    },
    Builtin {
        name: "SendText",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: send_text,
    },
    Builtin {
        name: "SetDefaultMouseSpeed",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: set_default_mouse_speed,
    },
    Builtin {
        name: "SetMouseDelay",
        kind: BuiltinKind::Command,
        min: 1,
        max: 2,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: set_mouse_delay,
    },
    Builtin {
        name: "SetStoreCapsLockMode",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 5,
        parameters: &[Parameter::Value],
        handler: set_store_caps_lock_mode,
    },
    Builtin {
        name: "SetWorkingDir",
        kind: BuiltinKind::Command,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: set_working_dir,
    },
    Builtin {
        name: "StrTitle",
        kind: BuiltinKind::Function,
        min: 1,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: str_title,
    },
    Builtin {
        name: "Suspend",
        kind: BuiltinKind::Command,
        min: 0,
        max: 1,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: suspend,
    },
    Builtin {
        name: "Thread",
        kind: BuiltinKind::Command,
        min: 1,
        max: 3,
        variant: 109,
        parameters: &[Parameter::Value],
        handler: not_carried,
    },
    Builtin {
        name: "VerCompare",
        kind: BuiltinKind::Function,
        min: 2,
        max: 2,
        variant: 0,
        parameters: &[Parameter::Value],
        handler: ver_compare,
    },
];

/// The shape the three COM members that take an object share: the measured
/// wording names the ComValue the argument is wanted to be, and an object
/// that IS there goes to the honest refusal of the platform.
macro_rules! com_object_argument {
    ($name:literal, $function:ident) => {
        pub(crate) fn $function(
            _rt: &mut Runtime<'_>,
            values: &[Value],
            line: u32,
            _variant: u8,
        ) -> Result<Value, RuntimeError> {
            match values.first() {
                Some(Value::Object(_)) => Err(RuntimeError {
                    message: "this platform has no COM: there is no object model behind the object the script holds".to_string(),
                    line,
                }),
                other => Err(RuntimeError {
                    message: crate::runtime::requires(
                        1,
                        $name,
                        TypeName::ComValue,
                        other.unwrap_or(&Value::Text(String::new())),
                    ),
                    line,
                }),
            }
        }
    };
}

com_object_argument!("ComObjFlags", com_obj_flags);
com_object_argument!("ComObjValue", com_obj_value);
com_object_argument!("ComObjConnect", com_obj_connect);

/// The parameters of a command that may not be left out.
///
/// The table of the binary says how many parameters a command declares,
/// and the documentation says which of them may be left out. There are
/// commands that declare fewer than they need: the `FileGetAttrib` takes
/// the name of the file, and it takes it whether the table says so or
/// not. Measured on the binary of v2.0.19 on 2026-10-31: the refusal of
/// such a command is not the one of the count -- "Too few parameters
/// passed to function." -- but the one of the parameter that is missing:
/// "Parameter #1 of FileGetAttrib must not be omitted in this case."
///
/// The numbers are the places of the parameters, counted from one.
const THE_REQUIRED: &[(&str, &[u8])] = &[
    ("ControlGetPos", &[5]),
    ("FileGetAttrib", &[1]),
    ("FileGetSize", &[1]),
    ("FileGetTime", &[1]),
    ("FileGetVersion", &[1]),
    ("FileSetTime", &[2]),
    ("ListViewGetContent", &[2]),
    ("MenuSelect", &[3]),
    ("MouseClickDrag", &[4, 5]),
];

/// The parameters of a command that may not be left out, in order.
///
/// The first one that the call does not carry is the one that the
/// refusal names.
pub fn required_parameters(name: &str) -> &'static [u8] {
    THE_REQUIRED
        .iter()
        .find(|(command, _)| *command == name)
        .map(|(_, numbers)| *numbers)
        .unwrap_or(&[])
}

/// The parameters of a built-in that take a reference.
///
/// The flag of the table of v2 is the place of the first parameter that
/// is written back, and the parameters after it are the ones that follow
/// it. A reference in any other place is a value where a variable is
/// wanted, and the built-in says so.
pub fn reference_parameters(name: &str) -> Vec<usize> {
    find(name)
        .map(|builtin| {
            builtin
                .parameters
                .iter()
                .enumerate()
                .filter(|(_, shape)| **shape == Parameter::Reference)
                .map(|(index, _)| index)
                .collect()
        })
        .unwrap_or_default()
}

/// The shape of the parameters of a built-in.
///
/// The shape is the column of the table: the value of an expression, the
/// reference that the caller passes, the name of a variable of the script,
/// or the name of the variable that the built-in writes into.
pub fn parameters_of(name: &str) -> &'static [Parameter] {
    find(name).map(|builtin| builtin.parameters).unwrap_or(&[])
}

/// Whether the built-in says itself which parameters take a reference.
///
/// The `DllCall` is the one that does: the place of the reference is
/// said by the type of the argument, and the type is a parameter of the
/// call. The table of v2 cannot hold that, because the table is fixed
/// and the call is not.
pub fn decides_references(name: &str) -> bool {
    matches!(name, "DllCall")
}

/// The built-in with this name, if the language has one.
///
/// The name is matched the way AutoHotkey matches it: without regard to
/// the case.
pub fn find(name: &str) -> Option<&'static Builtin> {
    let wanted = name.to_lowercase();
    BUILTINS
        .iter()
        .find(|builtin| builtin.name.to_lowercase() == wanted)
}

/// The value that a built-in complains about, when its message does
/// not name the parameter it is about.
///
/// v2 carries the value in the `Extra` of the failure, and most of the
/// messages name the parameter it is about. The message of the options
/// of an input box that v2 does not know does not: the value there is
/// the option itself, and the built-in says which one it is.
pub fn the_extra_of(name: &str, message: &str, values: &[Value]) -> Option<String> {
    // The failure of a mode of the window titles carries the value that was
    // not a mode in the `Extra`: measured on the binary of v2.0.19 on
    // 2026-11-09, `SetTitleMatchMode("Bogus")` carries "Bogus",
    // `SetTitleMatchMode(4)` carries "4" and `SetTitleMatchMode(0)` carries
    // "0".
    if name == "SetTitleMatchMode" && message == "Parameter #1 of SetTitleMatchMode is invalid." {
        return values.first().map(|value| value.to_text());
    }
    // The failure of a window query carries the window it was asked about in
    // the `Extra`, and a window that was named by its id leaves it empty.
    //
    // Measured on the binary of v2.0.19 on 2026-11-09: `WinGetID("zzz")` is
    // "Target window not found." with "zzz" in the `Extra`, and `WinGetID(0)`
    // carries nothing.
    if matches!(
        name,
        "WinGetID" | "WinGetIDLast" | "WinGetClass" | "WinGetTitle"
    ) && message == "Target window not found."
    {
        return match values.first() {
            Some(Value::Int(_)) | None => None,
            Some(value) => Some(value.to_text()),
        };
    }
    // The base of an object is written with the `ObjSetBase`, and the value
    // that is not an object goes in the `Extra` of the refusal.
    //
    // Measured on the binary of v2.0.19 on 2026-10-31.
    if name == "ObjSetBase" && message.starts_with("Expected an Object but got") {
        return values.get(1).map(crate::runtime::the_extra_of_the_value);
    }
    // The button of a `MouseClick` is the first parameter, and the value
    // that the refusal carries has the space at the end of it cut.
    //
    // Measured on the binary of v2.0.19 on 2026-10-31: "Left " is refused
    // with the "Left" in the `Extra`, and "  nonsense  " with the
    // " nonsense" in it.
    if name == "MouseClick" && message == "Parameter #1 of MouseClick is invalid." {
        return values
            .first()
            .map(|value| value.to_text().trim_end().to_string());
    }
    // The failure of a copy or of a move of a file carries the number of
    // the files that failed.
    //
    // Measured on the binary of v2.0.19 on 2026-11-01: the copy of a file
    // that is not there fails with "Failed", and the `Extra` of the failure
    // is 1.
    if matches!(name, "FileCopy" | "FileMove") && message == "Failed" {
        return Some("1".to_string());
    }
    // The target of a `StrPut` is a buffer, and a buffer that cannot hold
    // the text is refused with the kind of the value in the `Extra`: the
    // name of the class, and not the text of the object.
    //
    // Measured on the binary of v2.0.19 on 2026-11-09.
    if name == "StrPut"
        && message == "Parameter #2 of StrPut is invalid."
        && matches!(values.get(1), Some(Value::Object(_)))
    {
        return Some("Buffer".to_string());
    }
    if message != "Invalid option." {
        return None;
    }
    match name {
        "InputBox" => {
            let options = values
                .get(2)
                .map(|value| value.to_text())
                .unwrap_or_default();
            crate::dialogs::the_option_that_failed(&options)
        }
        // The options of a file are in the second parameter of the read and
        // in the third one of the write.
        "FileRead" => {
            let options = values
                .get(1)
                .map(|value| value.to_text())
                .unwrap_or_default();
            crate::files::the_option_that_failed(&options, true)
        }
        "FileAppend" => {
            let options = values
                .get(2)
                .map(|value| value.to_text())
                .unwrap_or_default();
            crate::files::the_option_that_failed(&options, false)
        }
        _ => None,
    }
}

/// The built-in with this name, if the language has one, as a command.
///
/// A command may be written as a statement; a function may not.
pub fn find_command(name: &str) -> Option<&'static Builtin> {
    find(name).filter(|builtin| builtin.kind == BuiltinKind::Command)
}

/// The names of the built-ins, as the language spells them.
pub fn names() -> impl Iterator<Item = &'static str> {
    BUILTINS.iter().map(|builtin| builtin.name)
}

// -- the names that are carried, and that this runtime cannot answer ------------

/// `DllCall`: a call into a library of the machine.
///
/// v2 writes the library and the function in one string, the type of
/// every argument after it, and the type of the answer at the end. The
/// types and the values alternate, and the last parameter may be the
/// type of the answer alone: the count of the parameters tells the two
/// apart.
pub(crate) fn dll_call(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    dll_call_with_the_kind(rt, values, line).map_err(|(_, error)| error)
}

/// The call of a library, with the kind of the failure.
///
/// The kind says what failed: the call itself, the library, or the function
/// in the library. The v1 turns it into the code that it writes in the
/// `ErrorLevel`, and the v2 does not use it: the wrapper above drops it.
pub(crate) fn dll_call_with_the_kind(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
) -> Result<Value, (NativeFailureKind, RuntimeError)> {
    let Some(first) = values.first() else {
        return Err((
            NativeFailureKind::Invalid,
            RuntimeError {
                message: "DllCall wants the library and the function.".into(),
                line,
            },
        ));
    };
    let Value::Text(target) = first else {
        return Err((
            NativeFailureKind::Invalid,
            RuntimeError {
                message: expected_type(TypeName::String, first.type_name()),
                line,
            },
        ));
    };
    let (library, function) = crate::dll::split_target(target);
    let rest = &values[1..];
    let (returns, convention, rest) = if rest.len() % 2 == 1 {
        let last = rest.last().expect("there is one");
        let Value::Text(text) = last else {
            return Err((
                NativeFailureKind::Invalid,
                RuntimeError {
                    message: expected_type(TypeName::String, last.type_name()),
                    line,
                },
            ));
        };
        let (convention, name) = split_convention(text);
        let Some((kind, _)) = crate::dll::parse_type(name) else {
            return Err((
                NativeFailureKind::Invalid,
                RuntimeError {
                    message: "Invalid return type.".into(),
                    line,
                },
            ));
        };
        (kind, convention, &rest[..rest.len() - 1])
    } else {
        (NativeType::Int, Convention::Standard, rest)
    };
    let mut arguments = Vec::new();
    let mut references = Vec::new();
    let mut index = 0;
    while index < rest.len() {
        let Value::Text(text) = &rest[index] else {
            return Err((
                NativeFailureKind::Invalid,
                RuntimeError {
                    message: expected_type(TypeName::String, rest[index].type_name()),
                    line,
                },
            ));
        };
        let Some((kind, address)) = crate::dll::parse_type(text) else {
            return Err((
                NativeFailureKind::Invalid,
                RuntimeError {
                    message: "Invalid arg type.".into(),
                    line,
                },
            ));
        };
        let (argument, reference) = marshal(rt, kind, address, &rest[index + 1], line)
            .map_err(|error| (NativeFailureKind::Invalid, error))?;
        arguments.push(argument);
        references.push(reference);
        index += 2;
    }
    let mut call = NativeCall {
        library,
        function,
        convention,
        returns,
        arguments,
    };
    let answer = rt.desktop().call_native(&mut call).map_err(|failure| {
        (
            failure.kind,
            RuntimeError {
                message: failure.reason,
                line,
            },
        )
    })?;
    // The arguments that are the address of a variable come back into
    // the variable.
    for (argument, reference) in call.arguments.iter().zip(references) {
        // Only the argument that is the address of a variable comes back.
        if !argument.address {
            continue;
        }
        let Some(reference) = reference else { continue };
        let NativeValue::Bytes(bytes) = &argument.value else {
            continue;
        };
        let written = if argument.kind.is_text() {
            Value::Text(crate::dll::decode(bytes, argument.kind))
        } else if argument.kind.is_float() {
            Value::Float(crate::dll::decode_number(bytes, argument.kind))
        } else {
            Value::Int(crate::dll::decode_number(bytes, argument.kind) as i64)
        };
        rt.write_reference(&reference, written);
    }
    Ok(match answer.value {
        NativeValue::Integer(number) => Value::Int(number),
        NativeValue::Float(number) => Value::Float(number),
        NativeValue::Bytes(bytes) => Value::Text(crate::dll::decode(&bytes, answer.kind)),
    })
}

/// The argument of a native call, out of the value the script wrote.
///
/// A value behind a reference is the value of the variable, and the
/// call writes into the variable: the reference comes back with the
/// argument.
fn marshal(
    rt: &mut Runtime<'_>,
    kind: NativeType,
    address: bool,
    value: &Value,
    line: u32,
) -> Result<(NativeArg, Option<Value>), RuntimeError> {
    let (value, reference) = match value {
        Value::Reference(reference) => {
            let Some(current) = rt.read_reference(reference) else {
                return Err(RuntimeError {
                    message: rt.the_unassigned(&reference.name),
                    line,
                });
            };
            (current, Some(value.clone()))
        }
        other => (other.clone(), None),
    };
    // A text goes out as its bytes.
    if kind.is_text() {
        let Value::Text(text) = &value else {
            return Err(RuntimeError {
                message: expected_type(TypeName::String, value.type_name()),
                line,
            });
        };
        let bytes = crate::dll::encode(text, kind);
        return Ok((
            NativeArg {
                kind,
                address,
                value: NativeValue::Bytes(bytes),
            },
            reference,
        ));
    }
    // A pointer may be an object, and then it is the address of the
    // object that goes.
    if matches!(kind, NativeType::Ptr | NativeType::UPtr) {
        if let Value::Object(_) = &value {
            if let Some(place) = rt.property_of(&value, "ptr", line) {
                let place = place.to_number_strict().map_err(|got| RuntimeError {
                    message: expected_type(TypeName::Integer, got),
                    line,
                })?;
                return Ok((
                    NativeArg {
                        kind,
                        address,
                        value: NativeValue::Integer(place as i64),
                    },
                    reference,
                ));
            }
        }
    }
    let number = native_number(rt, &value, line)?;
    let value = if kind.is_float() {
        NativeValue::Float(number)
    } else {
        NativeValue::Integer(number as i64)
    };
    Ok((
        NativeArg {
            kind,
            address,
            value,
        },
        reference,
    ))
}

/// The value as a number, the way a native call wants it.
fn native_number(rt: &Runtime<'_>, value: &Value, line: u32) -> Result<f64, RuntimeError> {
    match rt.number(value, line) {
        Ok(number) => Ok(number),
        Err(RuntimeFailure::Error(error)) => Err(error),
        Err(RuntimeFailure::Detailed(error, _)) => Err(error),
        Err(RuntimeFailure::Fatal(error)) => Err(error),
        Err(RuntimeFailure::Timeout(_)) => Err(RuntimeError {
            message: "the script ran out of time.".into(),
            line,
        }),
        Err(RuntimeFailure::Flow(_)) => Err(RuntimeError {
            message: "a number was expected.".into(),
            line,
        }),
        Err(RuntimeFailure::Thrown(_)) => Err(RuntimeError {
            message: "a number was expected.".into(),
            line,
        }),
    }
}

/// The convention and the type of the answer, read out of the last
/// parameter.
///
/// v2 writes the convention and the type of the answer in one string:
/// "CDecl Int", or "CDecl" alone, or the type alone.
fn split_convention(text: &str) -> (Convention, &str) {
    let trimmed = text.trim();
    let (head, tail) = match trimmed.split_once(char::is_whitespace) {
        Some((head, tail)) => (head, tail.trim()),
        None => (trimmed, ""),
    };
    if head.eq_ignore_ascii_case("cdecl") {
        return (Convention::Cdecl, tail);
    }
    if head.eq_ignore_ascii_case("stdcall") {
        return (Convention::Standard, tail);
    }
    (Convention::Standard, trimmed)
}

/// The variant that says the name is refused.
///
/// The variants below it belong to the handlers that answer a value, and
/// the ones from it up are the refusals: the reason of a refusal is
/// told from the variant of the row.
pub const REFUSAL: u8 = 100;

/// The reason the tree does not answer a name, when it does not.
///
/// The refusals are the names whose handler is the refusal, and the
/// variant of the row says which reason it is.
pub fn refusal_of(name: &str) -> Option<&'static str> {
    find(name).and_then(refusal_of_the)
}

/// The reason the tree does not answer a built-in, when it does not.
///
/// The refusal is told from the variant of the row, and the row may be
/// the one of any dialect.
pub fn refusal_of_the(builtin: &Builtin) -> Option<&'static str> {
    if builtin.variant < REFUSAL {
        return None;
    }
    Some(refusal_message(builtin.variant - REFUSAL))
}

/// The reason of a refusal.
///
/// The variant is the one of the row, without the offset of the
/// refusals.
fn refusal_message(variant: u8) -> &'static str {
    match variant {
        0 => "this is a name of Windows, and this desktop is not Windows.",
        1 => "this runtime has no hotkeys yet.",
        2 => {
            "the clock of this runtime counts from an arbitrary origin, and it does not know the date."
        }
        3 => "this runtime is one script that ends when it ends, and it cannot do that.",
        4 => "this desktop cannot serve that with the files it has.",
        5 => {
            "the pointer and the keyboard of this runtime are the ones of the box, and they have no setting of that kind."
        }
        // The reason of a method: a name of a class that the tree does
        // not carry. The names of v2 that were in this slot were not
        // methods at all -- the tables that were read out of the binary
        // had them in a table of methods -- and the reason moved with
        // them.
        6 => "a method of this runtime is not bound to an object.",
        // The shape of the runtime: each name of the group says what it
        // wants, and the group of them is gone.
        8 => "this runtime runs one script in one thread, and it cannot make it critical.",
        9 => "this runtime runs one script in one thread, and it cannot start another.",
        10 => "this runtime cannot wait for a key to continue: the script ends when it ends.",
        11 => "this runtime is a script that ends when it ends, and it cannot be kept alive.",
        12 => "this runtime runs one script once, and it cannot run itself again.",
        13 => "this runtime cannot stop itself: it would never end.",
        14 => {
            "the lines are listed in a window of v2, and this runtime has no window to show them in."
        }
        15 => {
            "the variables are listed in a window of v2, and this runtime has no window to show them in."
        }
        16 => {
            "the question of the user is asked in a window of v2, and this runtime has no window to ask in."
        }
        17 => "the download is made by the desktop, and this desktop does not reach the network.",
        18 => {
            "the picture is read by the desktop, and this desktop does not read the images of the machine."
        }
        19 => {
            "the search of a picture is made by the desktop, and this desktop does not read the images of the machine."
        }
        20 => "the handler of an error is not carried: this runtime ends the script when it fails.",
        21 => crate::settings::NO_TEXT_OF_A_WINDOW,
        23 => "the registry is a thing of Windows, and this runtime does not carry it.",
        // No name of the surface has this variant: the `ObjBindMethod` was
        // the last one, and it is carried now. The arm is the fallback of a
        // variant that the table does not have.
        _ => crate::dialect::NOT_CARRIED_YET,
    }
}

/// A name that this runtime carries, and cannot answer.
///
/// The variant says why: the name is shaped for Windows, it is a
/// hotkey, or it is a name of the script that this runtime does not
/// have. The script knows which name it called, so the reason names the
/// group and not the name.
pub(crate) fn not_carried(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let message = refusal_message(variant.saturating_sub(REFUSAL));
    Err(RuntimeError {
        message: message.to_string(),
        line,
    })
}

// -- the environment ---------------------------------------------------------------

/// `EnvGet`: the value of an environment variable.
pub(crate) fn env_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = text_of(values, 0);
    // Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the
    // variable that the environment does not have is an empty text, and it is
    // not a failure. Measured on the binary of AutoHotkey v1.1.37.02 on
    // 2026-11-05: the `EnvGet` of a name that is not there leaves the output
    // empty, and the `ErrorLevel` is zero.
    let value = rt
        .desktop()
        .env_get(&name)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?
        .unwrap_or_default();
    Ok(Value::Text(value))
}

/// `EnvSet`: set an environment variable, and answer its value.
pub(crate) fn env_set(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = text_of(values, 0);
    let value = text_of(values, 1);
    rt.desktop()
        .env_set(&name, &value)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    Ok(Value::Text(value))
}

// -- the files of the disk ----------------------------------------------------------

/// `FileExist`: the attributes of the first entry that matches.
///
/// v2 answers with the attributes of the file and not with a number: a
/// file that is there is `A`, a folder is `D`, and a file that is not
/// there is the empty text.
///
/// Measured on the binary of v2.0.19 on 2026-10-28 and on 2026-10-31:
/// the pattern may carry the wildcards `*` and `?`, and the answer is
/// the attributes of the first entry that matches, a folder among them.
pub(crate) fn file_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let pattern = text_of(values, 0);
    let attributes = rt
        .desktop()
        .attributes_of_the_pattern(&pattern, "")
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    Ok(Value::Text(attributes.concat()))
}

/// `DirExist`: the attributes of the first folder that matches.
///
/// The answer of v2 is `D` when it is there, and the empty text when it
/// is not. A file that matches the pattern is not a folder, and the
/// answer is the empty text.
pub(crate) fn dir_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let pattern = text_of(values, 0);
    let attributes = rt
        .desktop()
        .attributes_of_the_pattern(&pattern, "D")
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    Ok(Value::Text(attributes.concat()))
}

/// `FileDelete`: take a file away, or the files that a pattern names.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the name may be a pattern
/// whose last part holds a `*`, which is any run of characters, and a `?`,
/// which is one character; a pattern that names no file is not a failure.
pub(crate) fn file_delete(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = crate::files::the_name_of_a_file(values, 0, 1, "FileDelete", line)?;
    let files = if crate::files::is_a_pattern(&path) {
        crate::files::the_files_of_the_pattern(rt, &path, line)?
    } else {
        vec![path]
    };
    for file in files {
        rt.desktop()
            .delete_file(&file)
            .map_err(|reason| RuntimeError {
                message: reason,
                line,
            })?;
    }
    // Measured on the binary of v2.0.19 on 2026-11-01: the answer of the
    // command is an empty text.
    Ok(Value::Text(String::new()))
}

/// `DirCreate`: make a directory.
pub(crate) fn dir_create(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    rt.desktop()
        .create_dir(&path)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    // Measured on the binary of v2.0.19 on 2026-11-01: the answer of the
    // command is an empty text.
    Ok(Value::Text(String::new()))
}

/// `DirDelete`: take a directory away.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the second parameter
/// is the recursion, and a folder that is not empty stays without it.
pub(crate) fn dir_delete(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    let recurse = crate::files::flag_of(values, 1, "DirDelete", line)?;
    rt.desktop()
        .dir_delete(&path, recurse)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    Ok(Value::Text(path))
}

/// `FileCreateShortcut(LinkFile, Target, WorkingDir, Args, Description, Icon,
/// IconNumber, Run)`: make a shortcut to a program.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `FileCreateShortcut`
/// answers the empty text and makes the file, and it makes it even for a
/// target that is not there.
pub(crate) fn file_create_shortcut(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    let shortcut = text_of(values, 1);
    let working_directory = text_of(values, 2);
    let arguments = text_of(values, 3);
    let description = text_of(values, 4);
    let icon = text_of(values, 5);
    rt.desktop()
        .create_shortcut(
            &target,
            &shortcut,
            &working_directory,
            &arguments,
            &description,
            &icon,
        )
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `FileGetShortcut(LinkFile, &OutTarget, &OutDir, &OutArgs, &OutDesc,
/// &OutIcon, &OutIconNum, &OutRun)`: read a shortcut back.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: all eight fields of a
/// shortcut `FileCreateShortcut` made come back -- target, working directory,
/// arguments, description, icon, icon number and run state. This tree reads
/// the `.desktop` file `FileCreateShortcut` wrote; the icon NUMBER and the run
/// state have no counterpart there, so those two answers are the empty text.
pub(crate) fn file_get_shortcut(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let shortcut = text_of(values, 0);
    let (target, dir, args, desc, icon) = rt
        .desktop()
        .read_shortcut(&shortcut)
        .map_err(|reason| desktop_failure(reason, line))?;
    let places: [(&str, Value); 7] = [
        ("target", Value::Text(target)),
        ("dir", Value::Text(dir)),
        ("args", Value::Text(args)),
        ("desc", Value::Text(desc)),
        ("icon", Value::Text(icon)),
        // A `.desktop` file has no icon index and no run state: the honest
        // answer is the empty text, not a number invented for the shape.
        ("iconnum", Value::Text(String::new())),
        ("run", Value::Text(String::new())),
    ];
    for (index, (name, value)) in places.iter().enumerate() {
        let at = index + 1;
        let Some(slot) = values.get(at) else {
            continue;
        };
        if !matches!(slot, Value::Reference(_)) {
            return Err(RuntimeError {
                message: format!(
                    "the {} of FileGetShortcut is written back, so parameter #{} wants a variable",
                    name,
                    at + 1
                ),
                line,
            });
        }
        rt.write_reference(slot, value.clone());
    }
    Ok(Value::Text(String::new()))
}

// -- the pieces of a text ----------------------------------------------------------

/// `StrSplit`: the pieces of a text, cut at the delimiters.
///
/// v2 cuts the text where a delimiter is, and a delimiter is a literal: a
/// text is one delimiter and an array of texts is a set of them, and the
/// first one of them that is there wins. The characters to omit are cut
/// from the beginning and the end of every piece, and the number of the
/// pieces says how many times the text is cut: the rest of the text is
/// the last piece.
///
/// Measured on the binary of v2.0.19 on 2026-10-31.
pub(crate) fn str_split(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = text_of(values, 0);
    let delimiters = the_delimiters(rt, values.get(1), line)?;
    let omit = text_of(values, 2);
    // The number of the pieces is not there: there is no limit.
    let max = match values.get(3) {
        None => -1.0,
        Some(value) => value.to_number().unwrap_or(-1.0),
    };
    let pieces = the_pieces(&text, &delimiters, &omit, max);
    let values: Vec<Value> = pieces.into_iter().map(Value::Text).collect();
    // The answer of v2 is an array.
    match crate::classes::construct("array", &values, rt, line) {
        Some(result) => result.map_err(|failure| crate::runtime::as_error(failure, line)),
        None => Ok(Value::List(values)),
    }
}

/// The delimiters of a `StrSplit`: the literals the text is cut at.
///
/// v2 takes a text or an array of texts, and refuses anything else with
/// "Parameter #2 of StrSplit is invalid.". An array that is empty is
/// refused as well: the delimiters that are blank are a text that is
/// empty, and not an array with nothing in it.
fn the_delimiters(
    rt: &Runtime<'_>,
    value: Option<&Value>,
    line: u32,
) -> Result<Vec<String>, RuntimeError> {
    let invalid = || RuntimeError {
        message: "Parameter #2 of StrSplit is invalid.".into(),
        line,
    };
    match value {
        None => Ok(Vec::new()),
        Some(Value::List(items)) => {
            if items.is_empty() {
                return Err(invalid());
            }
            Ok(items.iter().map(|item| item.to_text()).collect())
        }
        Some(value) => {
            // The array of the delimiters is a class of the runtime.
            if rt.class_of(value).as_deref() == Some("Array") {
                let items = crate::classes::array::the_items(value);
                if items.is_empty() {
                    return Err(invalid());
                }
                return items
                    .iter()
                    .map(|item| match item {
                        Value::Text(text) => Ok(text.clone()),
                        other => Err(RuntimeError {
                            message: crate::runtime::requires(
                                2,
                                "StrSplit",
                                TypeName::String,
                                other,
                            ),
                            line,
                        }),
                    })
                    .collect::<Result<Vec<String>, RuntimeError>>();
            }
            // The other objects are not delimiters.
            if matches!(value, Value::Object(_)) {
                return Err(invalid());
            }
            // A text that is empty is a blank delimiter: every character of
            // the text is a piece of its own.
            let text = value.to_text();
            if text.is_empty() {
                return Ok(Vec::new());
            }
            Ok(vec![text])
        }
    }
}

/// The pieces of a text, cut at the delimiters.
///
/// The text is cut where a delimiter is, and the delimiters are tried in
/// the order they were given: the first one of them that is there wins.
/// The characters to omit are cut from the beginning and the end of every
/// piece. When the delimiters are blank every character of the text is a
/// piece of its own, and the characters to omit are not pieces at all.
fn the_pieces(text: &str, delimiters: &[String], omit: &str, max: f64) -> Vec<String> {
    // The delimiters are blank: every character of the text is a piece.
    if delimiters.is_empty() {
        return text
            .chars()
            .filter(|character| !omit.contains(*character))
            .map(|character| character.to_string())
            .collect();
    }
    // The number of the pieces is zero: there is no piece at all.
    if max == 0.0 {
        return Vec::new();
    }
    // Measured on the binary of v2.0.19 on 2026-10-31: a text that is empty
    // has no piece at all, and the piece that is empty is not a piece.
    if text.is_empty() {
        return Vec::new();
    }
    // The number of the pieces says how many times the text is cut: the
    // rest of the text is the last piece.
    let cuts = if max > 0.0 { max as usize - 1 } else { 0 };
    let mut pieces: Vec<String> = Vec::new();
    let mut rest = text;
    let mut made = 0;
    while let Some((at, length)) = the_first_delimiter(rest, delimiters) {
        if max > 0.0 && made >= cuts {
            pieces.push(trim_the_omit(rest, omit));
            return pieces;
        }
        pieces.push(trim_the_omit(&rest[..at], omit));
        rest = &rest[at + length..];
        made += 1;
    }
    pieces.push(trim_the_omit(rest, omit));
    pieces
}

/// Where the text is cut: the place of the first delimiter that is there,
/// and how long it is.
///
/// The delimiters are tried in the order they were given, and the first
/// one of them that is there wins.
fn the_first_delimiter(text: &str, delimiters: &[String]) -> Option<(usize, usize)> {
    let mut found: Option<(usize, usize)> = None;
    for delimiter in delimiters {
        if delimiter.is_empty() {
            continue;
        }
        let Some(at) = text.find(delimiter.as_str()) else {
            continue;
        };
        match found {
            // The one that is there first wins, and the order of the
            // delimiters decides between the ones that are at the same
            // place: the first of them is the one that is kept.
            Some((first, _)) if first <= at => continue,
            _ => found = Some((at, delimiter.len())),
        }
    }
    found
}

/// The text without the characters to omit at its beginning and its end.
fn trim_the_omit(text: &str, omit: &str) -> String {
    if omit.is_empty() {
        return text.to_string();
    }
    let mut start = 0;
    while start < text.len() {
        let Some(character) = text[start..].chars().next() else {
            break;
        };
        if !omit.contains(character) {
            break;
        }
        start += character.len_utf8();
    }
    let mut end = text.len();
    while end > start {
        let Some(character) = text[..end].chars().next_back() else {
            break;
        };
        if !omit.contains(character) {
            break;
        }
        end -= character.len_utf8();
    }
    text[start..end].to_string()
}

/// `SplitPath`: the pieces of a path.
///
/// v2 writes the pieces into the variables of the caller, and it
/// answers with nothing. The pieces are the name of the file, the
/// directory, the extension, the name without the extension and the
/// drive.
pub(crate) fn split_path(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_argument("SplitPath", values, 0, line)?;
    let pieces = split_the_path(&path);
    for (index, piece) in pieces.into_iter().enumerate() {
        let Some(value) = values.get(index + 1) else {
            continue;
        };
        // The pieces are written into the variables of the caller, and
        // those are given by reference.
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    index + 2,
                    "SplitPath",
                    "a variable reference",
                    value,
                ),
                line,
            });
        }
        rt.write_reference(value, Value::Text(piece));
    }
    Ok(Value::Text(String::new()))
}

/// The pieces of a path, the way v2 cuts it.
///
/// The name of the file, the directory, the extension, the name
/// without the extension and the drive. A path of a file is cut at the
/// backslash and a URL at the slash, and v2 keeps that difference: the
/// backslash is the separator of a file and the slash is the one of a
/// URL.
fn split_the_path(path: &str) -> [String; 5] {
    // A URL: the drive is the scheme and the host.
    if let Some(at) = path.find("://") {
        let scheme = &path[..at];
        let rest = &path[at + 3..];
        let host_end = rest.find('/').unwrap_or(rest.len());
        let drive = format!("{scheme}://{}", &rest[..host_end]);
        let tail = &rest[host_end..];
        let separator = tail.rfind('/');
        let name = match separator {
            Some(at) => tail[at + 1..].to_string(),
            None => tail.to_string(),
        };
        let directory = match separator {
            Some(at) => format!("{drive}{}", &tail[..at]),
            None => drive.clone(),
        };
        let (stem, extension) = the_extension(&name);
        return [name, directory, extension, stem, drive];
    }
    // A file: the drive is the letters and the colon, or the server of
    // a share. The drive is cut off the path first: the name of v2 does
    // not carry it, and a path with a drive and no backslash keeps the
    // slash in the name.
    let (drive, rest) = if let Some(rest) = path.strip_prefix("\\\\") {
        let end = rest.find('\\').unwrap_or(rest.len());
        (format!("\\\\{}", &rest[..end]), &rest[end..])
    } else if path.len() >= 2 && path.as_bytes()[1] == b':' {
        (path[..2].to_string(), &path[2..])
    } else {
        (String::new(), path)
    };
    let separator = rest.rfind('\\');
    let name = match separator {
        Some(at) => rest[at + 1..].to_string(),
        None => rest.to_string(),
    };
    // Without a backslash the name is the whole path after the drive,
    // and the directory is the drive alone.
    let directory = match separator {
        Some(at) => format!("{drive}{}", &rest[..at]),
        None => drive.clone(),
    };
    let (stem, extension) = the_extension(&name);
    [name, directory, extension, stem, drive]
}

/// The name of a file without its extension, and the extension.
///
/// A dot that opens the name is not one: the name of a file that
/// begins with one has no extension.
fn the_extension(name: &str) -> (String, String) {
    match name.rfind('.') {
        Some(at) if at > 0 => (name[..at].to_string(), name[at + 1..].to_string()),
        _ => (name.to_string(), String::new()),
    }
}

// -- the objects -------------------------------------------------------------------

/// The text of an argument, when it is a text.
///
/// A reference is not a text, and the built-in that wants one says
/// which parameter got it.
fn text_argument(
    name: &str,
    values: &[Value],
    index: usize,
    line: u32,
) -> Result<String, RuntimeError> {
    match values.get(index) {
        None => Ok(String::new()),
        // Measured on the binary of v2.0.19 on 2026-11-10: the absent value is
        // no argument, and the text of no argument is the empty text.
        Some(Value::Unset) => Ok(String::new()),
        Some(Value::Reference(_)) => Err(RuntimeError {
            message: format!(
                "Parameter #{} of {} requires a String, but received a VarRef.",
                index + 1,
                name
            ),
            line,
        }),
        Some(value) => Ok(value.to_text()),
    }
}

/// `ObjBindMethod`: the function that calls the method of an object.
///
/// Measured on the binary of AutoHotkey v2.0.19 on 2026-11-05: the value is
/// of the class `BoundFunc`, and the call of it calls the method of the
/// object with the object as its `this`. The name of the method is not
/// checked when the value is made: the `ObjBindMethod(t, "Nope")` is made,
/// and the call of it fails.
///
/// The v1 makes the binding too, and it refuses the call of the name that
/// holds it: the v1 does not know that the name is a function.
pub(crate) fn obj_bind_method(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let object = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    if !matches!(object, Value::Object(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ObjBindMethod", TypeName::Object, &object),
            line,
        });
    }
    let method = text_of(values, 1);
    Ok(rt.bound_function(object, Value::Text(method)))
}

/// `HasProp`: whether an object has a property.
pub(crate) fn has_prop(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let name = text_of(values, 1);
    // Measured on the binary of v2.0.19 on 2026-10-31: a value that is
    // not an object has no property, and the answer is zero and not a
    // refusal. The one property that every value has is its class.
    if !matches!(target, Value::Object(_)) {
        return Ok(Value::Int(if name.eq_ignore_ascii_case("__class") {
            1
        } else {
            0
        }));
    }
    // A class is not an instance of itself: the question is about the
    // class, and the properties of the instances are not its own.
    if rt.class_name_of(&target).is_some() {
        return rt.base_object(&target, "hasprop", &[Value::Text(name)], line);
    }
    rt.own_method(&target, "hasprop", &[Value::Text(name)], line)
}

/// `HasMethod`: whether an object has a method.
pub(crate) fn has_method(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let name = text_of(values, 1);
    // The third parameter of v2 is the number of parameters that would
    // be passed to the method, and the tree asks the method whether it
    // could take them.
    let count = values.get(2).map(|value| value.to_number().unwrap_or(0.0));
    // Measured on the binary of v2.0.19 on 2026-10-31: the question with
    // no name asks whether the value is a class, and the name is not there
    // to be asked about.
    let mut arguments = Vec::new();
    if values.len() > 1 {
        arguments.push(Value::Text(name));
    }
    if let Some(count) = count {
        arguments.push(Value::Int(count as i64));
    }
    // A value that is not an object has no method, and the answer is zero.
    if !matches!(target, Value::Object(_)) {
        return Ok(Value::Int(0));
    }
    if rt.class_name_of(&target).is_some() {
        return rt.base_object(&target, "hasmethod", &arguments, line);
    }
    rt.own_method(&target, "hasmethod", &arguments, line)
}

/// `GetMethod`: the method of an object, as a value.
pub(crate) fn get_method(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let name = text_of(values, 1);
    // The third parameter of v2 is the number of parameters that would
    // be passed to the method.
    let count = values.get(2).map(|value| value.to_number().unwrap_or(0.0));
    let mut arguments = vec![Value::Text(name)];
    if let Some(count) = count {
        arguments.push(Value::Int(count as i64));
    }
    rt.own_method(&target, "getmethod", &arguments, line)
}

/// `HasBase`: whether the base of an object is another object.
pub(crate) fn has_base(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let base = values.get(1).cloned().unwrap_or(Value::Text(String::new()));
    // Measured on the binary of v2.0.19 on 2026-10-31: the base is an
    // object, and the refusal of a base that is not one comes before the
    // question of the object itself.
    if !matches!(base, Value::Object(_)) {
        return Err(RuntimeError {
            message: format!(
                "Expected an object but got {}.",
                crate::runtime::the_kind_of(&base)
            ),
            line,
        });
    }
    // A value that is not an object has no base, and the answer is zero.
    if !matches!(target, Value::Object(_)) {
        return Ok(Value::Int(0));
    }
    rt.own_method(&target, "hasbase", &[base], line)
}

/// `IsSetRef`: whether a variable holds a value.
///
/// v2 takes the variable by reference and answers one when the variable
/// is set and zero when it is not. A variable that was never given a
/// value is not set, and the reference to it is still a reference.
pub(crate) fn is_set_ref(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(value) = values.first() else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "IsSetRef"),
            line,
        });
    };
    let Value::Reference(reference) = value else {
        return Err(RuntimeError {
            message: crate::runtime::wants_a_reference(
                1,
                "IsSetRef",
                "a variable reference",
                value,
            ),
            line,
        });
    };
    Ok(Value::Int(rt.read_reference(reference).is_some() as i64))
}

// -- the keys ----------------------------------------------------------------------

/// `SendMode`: how the keys are sent.
///
/// The keys of this runtime go through the keyboard of the box, one at
/// a time, and that is the mode of the box. The other modes of v2 are
/// the ones of Windows.
pub(crate) fn send_mode(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The method of v2 is the way the keys are sent, and there is one
    // way here.
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the method of the sending is not carried yet.".into(),
            line,
        });
    }
    let mode = text_of(values, 0).to_lowercase();
    match mode.as_str() {
        "input" => {
            rt.note("the keys go through the keyboard of the box, one at a time");
            Ok(Value::Int(1))
        }
        _ => Err(RuntimeError {
            message: "the keys of this runtime go through the keyboard of the box, and that is the only mode there is.".into(),
            line,
        }),
    }
}

/// `KeyWait`: wait for a key to be up, or to go down.
///
/// The runtime does not keep the keys that are down: the box does, and
/// the runtime does not ask it.
pub(crate) fn key_wait(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "this runtime does not keep the keys that are down, so it cannot wait for one."
            .into(),
        line,
    })
}

// -- the timers ---------------------------------------------------------------------

/// `SetTimer`: a function of the script that runs between the statements.
///
/// The runtime is one thread, so the timer is not a thread of its own:
/// it runs between the statements of the script, and its budget is the
/// budget of the script.
pub(crate) fn set_timer(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The priority of v2 is the order of the timers, and the runtime
    // has one thread and one order.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the priority of the timer is not carried yet.".into(),
            line,
        });
    }
    let name = text_of(values, 0);
    let period = number_of(values, 1);
    let period = if period > 0.0 { period as u64 } else { 250 };
    rt.add_timer(&name, period);
    Ok(Value::Int(1))
}

// -- the sound ---------------------------------------------------------------------

/// `SoundBeep`: a tone of a frequency, for a number of milliseconds.
///
/// The frequency of v2 is between 37 and 32767, and it is 523 when the
/// script does not say. The duration is in milliseconds, and it is 150
/// when the script does not say.
pub(crate) fn sound_beep(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let frequency = match values.first() {
        Some(value) => value.to_number().unwrap_or(523.0),
        None => 523.0,
    };
    if !(37.0..=32767.0).contains(&frequency) {
        return Err(RuntimeError {
            message: "the frequency of a tone is between 37 and 32767.".into(),
            line,
        });
    }
    let duration = match values.get(1) {
        Some(value) => value.to_number().unwrap_or(150.0),
        None => 150.0,
    };
    let duration = if duration > 0.0 { duration as u64 } else { 150 };
    rt.desktop()
        .sound_beep(frequency, duration)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(1))
}

/// `SoundPlay`: a sound file.
///
/// The other parameters of v2 -- the volume, the speed, the pitch, the
/// wait and the options -- are not carried, and the desktop of the box
/// plays the file as it is.
pub(crate) fn sound_play(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the volume, the speed and the pitch of a sound are not carried yet.".into(),
            line,
        });
    }
    let path = text_of(values, 0);
    if path.is_empty() {
        return Err(RuntimeError {
            message: "the sound file is missing.".into(),
            line,
        });
    }
    rt.desktop()
        .sound_play(&path)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(1))
}

/// `SoundGetVolume`: the volume of a device, in percent.
///
/// The component of v2 is a part of a device -- the master volume, the
/// microphone -- and the box has one volume per device.
pub(crate) fn sound_get_volume(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 2 {
        return Err(RuntimeError {
            message:
                "the component of a sound is not carried yet: the box has one volume per device."
                    .into(),
            line,
        });
    }
    component_of(values, 0, line)?;
    let device = device_of(values, 1);
    let volume = rt
        .desktop()
        .sound_volume(&device)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Float(volume))
}

/// `SoundSetVolume`: the volume of a device, in percent.
///
/// The setting of v2 is a percentage between -100 and 100, and a sign
/// in front of it adjusts the volume instead of setting it.
pub(crate) fn sound_set_volume(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 3 {
        return Err(RuntimeError {
            message:
                "the component of a sound is not carried yet: the box has one volume per device."
                    .into(),
            line,
        });
    }
    let setting = text_of(values, 0);
    let (adjust, number) = match setting.strip_prefix('+') {
        Some(rest) => (true, rest.to_string()),
        None => match setting.strip_prefix('-') {
            Some(rest) => (true, format!("-{rest}")),
            None => (false, setting.clone()),
        },
    };
    let number: f64 = number.trim().parse().map_err(|_| RuntimeError {
        message: format!(
            "the volume of a device is a percentage between -100 and 100, and {setting:?} is not one."
        ),
        line,
    })?;
    if !(-100.0..=100.0).contains(&number) {
        return Err(RuntimeError {
            message: "the volume of a device is a percentage between -100 and 100.".into(),
            line,
        });
    }
    component_of(values, 1, line)?;
    let device = device_of(values, 2);
    if adjust {
        let current = rt
            .desktop()
            .sound_volume(&device)
            .map_err(|e| desktop_failure(e, line))?;
        let wanted = (current + number).clamp(0.0, 100.0);
        rt.desktop()
            .sound_set_volume(&device, wanted)
            .map_err(|e| desktop_failure(e, line))?;
    } else {
        rt.desktop()
            .sound_set_volume(&device, number)
            .map_err(|e| desktop_failure(e, line))?;
    }
    Ok(Value::Int(1))
}

/// `SoundGetMute`: whether a device is muted.
pub(crate) fn sound_get_mute(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 2 {
        return Err(RuntimeError {
            message:
                "the component of a sound is not carried yet: the box has one volume per device."
                    .into(),
            line,
        });
    }
    component_of(values, 0, line)?;
    let device = device_of(values, 1);
    let muted = rt
        .desktop()
        .sound_muted(&device)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(muted as i64))
}

/// `SoundSetMute`: mute a device, or unmute it.
///
/// The setting of v2 is 1 to mute, 0 to unmute, and -1 to turn the
/// mute of the device around.
pub(crate) fn sound_set_mute(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 3 {
        return Err(RuntimeError {
            message:
                "the component of a sound is not carried yet: the box has one volume per device."
                    .into(),
            line,
        });
    }
    let setting = number_of(values, 0);
    if !(-1.0..=1.0).contains(&setting) {
        return Err(RuntimeError {
            message: "the mute of a device is 1, 0 or -1.".into(),
            line,
        });
    }
    component_of(values, 1, line)?;
    let device = device_of(values, 2);
    let muted = if setting < 0.0 {
        let current = rt
            .desktop()
            .sound_muted(&device)
            .map_err(|e| desktop_failure(e, line))?;
        !current
    } else {
        setting != 0.0
    };
    rt.desktop()
        .sound_set_muted(&device, muted)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(1))
}

/// The component of the sound that the script asks about.
///
/// v2 names a part of a device -- the master volume, the microphone --
/// and the box has one volume per device: the master one. A component
/// that is not the master fails with the reason.
fn component_of(values: &[Value], index: usize, line: u32) -> Result<String, RuntimeError> {
    let component = match values.get(index) {
        Some(value) => value.to_text(),
        None => return Ok(String::new()),
    };
    if component.is_empty() || component.eq_ignore_ascii_case("master") {
        return Ok(String::new());
    }
    Err(RuntimeError {
        message: "the box has one volume per device: the master volume is the only one it has."
            .into(),
        line,
    })
}

/// The device that the script asks about.
///
/// v2 names a device by its name or by its number. The device of the
/// system is the empty name, and a number is written with a `#` in
/// front of it, so that the desktop can tell the two apart.
fn device_of(values: &[Value], index: usize) -> String {
    match values.get(index) {
        Some(Value::Int(number)) => format!("#{number}"),
        Some(value) => value.to_text(),
        None => String::new(),
    }
}

// -- the suspend and the pause ----------------------------------------------------

/// The number of `Suspend` and of `Pause`: on, off, or the toggle of the
/// omitted one.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the parameter is a Number,
/// and a text is the TypeError "Parameter #1 of Suspend requires a Number, but
/// received a String." with the text in the `Extra` -- "On", "Off" and
/// "Toggle" are not taken. The number one turns the state on, the zero turns
/// it off, and the minus one toggles, the way the omitted parameter toggles.
/// Any other number is "Parameter #1 of <name> is invalid." with the number in
/// the `Extra`: `Suspend 2` answers it.
fn the_on_or_off_of_a_command(
    values: &[Value],
    name: &str,
    line: u32,
) -> Result<Option<bool>, RuntimeError> {
    let Some(value) = values.first() else {
        return Ok(None);
    };
    match token_to_int64(value) {
        1 => Ok(Some(true)),
        0 => Ok(Some(false)),
        -1 => Ok(None),
        _ => Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, name),
            line,
        }),
    }
}

/// `Suspend`: the hotkeys of the script off, or on.
///
/// The answer is the empty text, and the command is observable through
/// `A_IsSuspended` and through the enabled flag of the hotkey table: the
/// runner has no keyboard, so no hotkey fires here, and a test reads the
/// table instead.
pub(crate) fn suspend(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match the_on_or_off_of_a_command(values, "Suspend", line)? {
        Some(suspended) => rt.set_suspended(suspended),
        None => {
            let now = rt.is_suspended();
            rt.set_suspended(!now);
        }
    }
    Ok(Value::Text(String::new()))
}

/// `Pause`: the script paused, or not.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the shapes of the
/// parameter are the ones of `Suspend`, and the answer is the empty text. A
/// `Pause` with no parameter pauses the *current thread* of the binary, which
/// waits for a key and hangs a script that has no keyboard -- the tree keeps a
/// state instead, and says so in `A_IsPaused`.
pub(crate) fn pause(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match the_on_or_off_of_a_command(values, "Pause", line)? {
        Some(paused) => rt.set_paused(paused),
        None => {
            let now = rt.is_paused();
            rt.set_paused(!now);
        }
    }
    Ok(Value::Text(String::new()))
}

// -- the script ---------------------------------------------------------------------

/// `Exit` and `ExitApp`: stop the script.
///
/// The code is kept and the script stops at the end of the statement
/// it was asked in, the way the statement of the same name stops it.
pub(crate) fn exit_script(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let code = number_of(values, 0) as i32;
    rt.exit_with(code);
    Ok(Value::Int(code as i64))
}

/// `OnExit`: the function the script asks to run when it ends.
///
/// The runtime is one script that ends when it ends, and the end is the
/// moment the runtime knows: the function runs then, whatever the reason
/// the script ended -- the end of the last statement, the code it asked to
/// stop with, or the error that stopped it.
///
/// The callback is a function object, and its prototype has to take the two
/// parameters of v2: the reason of the exit and the code.
pub(crate) fn on_exit(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let callback = rt.the_callback(values.first(), "OnExit", line)?;
    // The order of the callbacks: 1 calls it after the ones that are
    // registered, -1 before them, and 0 does not call it at all.
    match the_order(values.get(1), "OnExit", line)? {
        1 => rt.set_exit_callback(&callback.name, line),
        -1 => {
            rt.set_exit_callback(&callback.name, line);
            rt.order_exit_callback(&callback.name, true);
        }
        0 => rt.remove_exit_callback(&callback.name),
        _ => {
            return Err(RuntimeError {
                message: format!(
                    "{}\n     Specifically: {}",
                    crate::runtime::invalid_parameter(2, "OnExit"),
                    values
                        .get(1)
                        .map(|value| value.to_text())
                        .unwrap_or_default()
                ),
                line,
            });
        }
    }
    Ok(Value::Int(1))
}

/// `OnError`: the function the script asks to run when a failure is not
/// caught.
///
/// The callback is a function object, and its prototype has to take the two
/// parameters of v2: the value that was thrown and the mode of the
/// failure.
pub(crate) fn on_error(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let callback = rt.the_callback(values.first(), "OnError", line)?;
    match the_order(values.get(1), "OnError", line)? {
        1 => rt.set_error_callback(&callback.name, line),
        -1 => {
            rt.set_error_callback(&callback.name, line);
            rt.order_error_callback(&callback.name, true);
        }
        0 => rt.remove_error_callback(&callback.name),
        _ => {
            return Err(RuntimeError {
                message: format!(
                    "{}\n     Specifically: {}",
                    crate::runtime::invalid_parameter(2, "OnError"),
                    values
                        .get(1)
                        .map(|value| value.to_text())
                        .unwrap_or_default()
                ),
                line,
            });
        }
    }
    Ok(Value::Int(1))
}

/// The order of the callbacks: 1, -1 or 0.
///
/// The order is a number of v2, and it is cut to a whole number: 1.5 is
/// 1. The order that is not there is 1.
fn the_order(value: Option<&Value>, name: &str, line: u32) -> Result<i32, RuntimeError> {
    let Some(value) = value else { return Ok(1) };
    let number = value.to_number_strict().map_err(|_| RuntimeError {
        message: crate::runtime::wants_a_reference(2, name, "a Number", value),
        line,
    })?;
    Ok(number as i32)
}

/// What a parameter of a built-in wants.
///
/// The dialect has two ways of saying that a value is not the one it
/// wanted. A parameter that declares its kind says "Parameter #1 of Abs
/// requires a Number, but received a String.", and a check that the body
/// of the function makes says "Expected an Object but got a String.".
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Wants {
    /// A parameter that declares its kind: the dialect converts the value
    /// to it, and the message of the failure names it.
    Declared(TypeName),
    /// A check that the body of the function makes: the kind of the value
    /// is the kind itself.
    Checked(TypeName),
    /// A parameter that wants a reference. The wording is the one of the
    /// dialect: "a variable reference", "a VarRef".
    Reference(&'static str),
    /// A value of any kind.
    Value,
}

/// The type the parameters of a built-in declare.
///
/// The tables were measured on the binary of v2.0.19 on 2026-10-31:
/// every built-in of the tree was called with an object where the
/// parameter goes, and the refusal of the binary named the parameter and
/// the kind it wanted. A built-in that is not in them takes a value of
/// any kind, and the guard on a reference says so.
///
/// The number of the parameter is the one of the call: the first is the
/// first, and the two of `StrReplace` are the text and the needle.
/// The parameters that want a text.
const THE_TEXTS: &[(&str, &[u8])] = &[
    ("CoordMode", &[0, 1]),
    ("DateAdd", &[0, 2]),
    ("DateDiff", &[0, 1, 2]),
    ("DirCopy", &[0, 1]),
    ("DirCreate", &[0]),
    ("DirDelete", &[0]),
    ("DirExist", &[0]),
    ("DirMove", &[0, 1]),
    ("DirSelect", &[0, 2]),
    ("Download", &[0, 1]),
    ("EnvGet", &[0]),
    ("EnvSet", &[0, 1]),
    ("FileAppend", &[1, 2]),
    ("FileCopy", &[0, 1]),
    ("FileDelete", &[0]),
    ("FileEncoding", &[0]),
    ("FileExist", &[0]),
    ("FileGetAttrib", &[0]),
    ("FileGetSize", &[0, 1]),
    ("FileGetTime", &[0, 1]),
    ("FileInstall", &[0, 1]),
    ("FileMove", &[0, 1]),
    ("FileRead", &[0, 1]),
    ("FileSelect", &[0, 1, 2, 3]),
    ("FileSetAttrib", &[0, 1]),
    ("FileSetTime", &[0, 1, 2]),
    ("Format", &[0]),
    ("FormatTime", &[0, 1]),
    ("GetKeyName", &[0]),
    ("GetKeySC", &[0]),
    ("GetKeyState", &[0, 1]),
    ("GetKeyVK", &[0]),
    ("HotIfWinActive", &[0]),
    ("HotIfWinExist", &[0]),
    ("HotIfWinNotActive", &[0]),
    ("HotIfWinNotExist", &[0]),
    ("Hotkey", &[0, 2]),
    ("Hotstring", &[0, 2]),
    ("InStr", &[0, 1]),
    ("IniDelete", &[0, 1, 2]),
    ("IniRead", &[0, 1, 2, 3]),
    ("IniWrite", &[0, 1, 2, 3]),
    ("InputBox", &[0, 1, 2, 3]),
    ("IsAlnum", &[0, 1]),
    ("IsAlpha", &[0, 1]),
    ("IsDigit", &[0]),
    ("IsLabel", &[0]),
    ("IsLower", &[0, 1]),
    ("IsSpace", &[0]),
    ("IsTime", &[0]),
    ("IsUpper", &[0, 1]),
    ("IsXDigit", &[0]),
    ("KeyWait", &[0, 1]),
    ("LTrim", &[0, 1]),
    ("LoadPicture", &[0, 1]),
    ("MouseClick", &[0]),
    ("MouseClickDrag", &[0]),
    ("MouseMove", &[3]),
    ("MsgBox", &[0, 1, 2]),
    ("Ord", &[0]),
    ("RTrim", &[0, 1]),
    ("RegExMatch", &[0, 1]),
    ("RegExReplace", &[0, 1]),
    ("Run", &[0, 1, 2]),
    ("RunWait", &[0, 1, 2]),
    ("Send", &[0]),
    ("SendEvent", &[0]),
    ("SendInput", &[0]),
    ("SendMode", &[0]),
    ("SendPlay", &[0]),
    ("SendText", &[0]),
    ("SetKeyDelay", &[2]),
    ("SetMouseDelay", &[1]),
    ("SetWorkingDir", &[0]),
    ("Sort", &[0, 1]),
    ("SoundGetMute", &[0, 1]),
    ("SoundGetVolume", &[0, 1]),
    ("SoundPlay", &[0]),
    ("SoundSetMute", &[1, 2]),
    ("SoundSetVolume", &[1, 2]),
    ("SplitPath", &[0]),
    ("StrCompare", &[0, 1]),
    ("StrLen", &[0]),
    ("StrLower", &[0]),
    ("StrReplace", &[0, 1]),
    ("StrSplit", &[0, 2]),
    ("StrTitle", &[0]),
    ("StrUpper", &[0]),
    ("SubStr", &[0]),
    ("Trim", &[0, 1]),
    ("VerCompare", &[0, 1]),
    ("WinGetTitle", &[1, 2, 3]),
];

/// The parameters that want a number.
const THE_NUMBERS: &[(&str, &[u8])] = &[
    ("ACos", &[0]),
    ("ASin", &[0]),
    ("ATan", &[0]),
    ("Abs", &[0]),
    ("Ceil", &[0]),
    ("Chr", &[0]),
    ("ClipWait", &[0, 1]),
    ("Cos", &[0]),
    ("DateAdd", &[1]),
    ("DirSelect", &[1]),
    ("Exit", &[0]),
    ("ExitApp", &[0]),
    ("Exp", &[0]),
    ("FileCopy", &[2]),
    ("FileInstall", &[2]),
    ("FileMove", &[2]),
    ("Floor", &[0]),
    ("InStr", &[3, 4]),
    ("KeyHistory", &[0]),
    ("Ln", &[0]),
    ("Log", &[0]),
    ("MouseClick", &[1, 2, 3, 4]),
    ("MouseClickDrag", &[1, 2, 3, 4]),
    ("MouseMove", &[0, 1, 2]),
    ("PixelGetColor", &[0, 1]),
    ("Random", &[0, 1]),
    ("Round", &[0, 1]),
    ("SendLevel", &[0]),
    ("SetDefaultMouseSpeed", &[0]),
    ("SetKeyDelay", &[0, 1]),
    ("SetMouseDelay", &[0]),
    ("Sin", &[0]),
    ("Sleep", &[0]),
    ("SoundBeep", &[0, 1]),
    ("Sqrt", &[0]),
    ("StrSplit", &[3]),
    ("SubStr", &[1, 2]),
    ("Tan", &[0]),
];

/// The kinds of the parameters of the names the tree does not carry.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: every name that the
/// tree does not carry was called with a reference where the parameter
/// goes, and the refusal of the binary named the kind it wanted. The
/// dialect converts the arguments from the left, so a refusal about a
/// later parameter was read and the probe was asked again. A parameter
/// that wants a reference takes one, and it is not in this table: the
/// table of the references is the one of the binary.
const THE_REFUSED: &[(&str, usize, Wants)] = &[
    ("BlockInput", 0, Wants::Declared(TypeName::String)),
    ("CallbackFree", 0, Wants::Declared(TypeName::Number)),
    ("CaretGetPos", 0, Wants::Reference("a variable reference")),
    ("CaretGetPos", 1, Wants::Reference("a variable reference")),
    ("ComCall", 0, Wants::Declared(TypeName::Integer)),
    ("ComObjFlags", 0, Wants::Declared(TypeName::ComValue)),
    ("ComObjFromPtr", 0, Wants::Declared(TypeName::Number)),
    ("ComObjValue", 0, Wants::Declared(TypeName::ComValue)),
    ("ControlAddItem", 0, Wants::Declared(TypeName::String)),
    ("ControlAddItem", 3, Wants::Declared(TypeName::String)),
    ("ControlAddItem", 4, Wants::Declared(TypeName::String)),
    ("ControlAddItem", 5, Wants::Declared(TypeName::String)),
    ("ControlChooseIndex", 0, Wants::Declared(TypeName::Number)),
    ("ControlChooseIndex", 3, Wants::Declared(TypeName::String)),
    ("ControlChooseIndex", 4, Wants::Declared(TypeName::String)),
    ("ControlChooseIndex", 5, Wants::Declared(TypeName::String)),
    ("ControlChooseString", 0, Wants::Declared(TypeName::String)),
    ("ControlChooseString", 3, Wants::Declared(TypeName::String)),
    ("ControlChooseString", 4, Wants::Declared(TypeName::String)),
    ("ControlChooseString", 5, Wants::Declared(TypeName::String)),
    ("ControlClick", 2, Wants::Declared(TypeName::String)),
    ("ControlClick", 3, Wants::Declared(TypeName::String)),
    ("ControlClick", 4, Wants::Declared(TypeName::Number)),
    ("ControlClick", 5, Wants::Declared(TypeName::String)),
    ("ControlClick", 6, Wants::Declared(TypeName::String)),
    ("ControlClick", 7, Wants::Declared(TypeName::String)),
    ("ControlDeleteItem", 0, Wants::Declared(TypeName::Number)),
    ("ControlDeleteItem", 3, Wants::Declared(TypeName::String)),
    ("ControlDeleteItem", 4, Wants::Declared(TypeName::String)),
    ("ControlDeleteItem", 5, Wants::Declared(TypeName::String)),
    ("ControlFindItem", 0, Wants::Declared(TypeName::String)),
    ("ControlFindItem", 3, Wants::Declared(TypeName::String)),
    ("ControlFindItem", 4, Wants::Declared(TypeName::String)),
    ("ControlFindItem", 5, Wants::Declared(TypeName::String)),
    ("ControlFocus", 2, Wants::Declared(TypeName::String)),
    ("ControlFocus", 3, Wants::Declared(TypeName::String)),
    ("ControlFocus", 4, Wants::Declared(TypeName::String)),
    ("ControlGetChecked", 2, Wants::Declared(TypeName::String)),
    ("ControlGetChecked", 3, Wants::Declared(TypeName::String)),
    ("ControlGetChecked", 4, Wants::Declared(TypeName::String)),
    ("ControlGetChoice", 2, Wants::Declared(TypeName::String)),
    ("ControlGetChoice", 3, Wants::Declared(TypeName::String)),
    ("ControlGetChoice", 4, Wants::Declared(TypeName::String)),
    ("ControlGetClassNN", 2, Wants::Declared(TypeName::String)),
    ("ControlGetClassNN", 3, Wants::Declared(TypeName::String)),
    ("ControlGetClassNN", 4, Wants::Declared(TypeName::String)),
    ("ControlGetEnabled", 2, Wants::Declared(TypeName::String)),
    ("ControlGetEnabled", 3, Wants::Declared(TypeName::String)),
    ("ControlGetEnabled", 4, Wants::Declared(TypeName::String)),
    ("ControlGetExStyle", 2, Wants::Declared(TypeName::String)),
    ("ControlGetExStyle", 3, Wants::Declared(TypeName::String)),
    ("ControlGetExStyle", 4, Wants::Declared(TypeName::String)),
    ("ControlGetFocus", 1, Wants::Declared(TypeName::String)),
    ("ControlGetFocus", 2, Wants::Declared(TypeName::String)),
    ("ControlGetFocus", 3, Wants::Declared(TypeName::String)),
    ("ControlGetHwnd", 2, Wants::Declared(TypeName::String)),
    ("ControlGetHwnd", 3, Wants::Declared(TypeName::String)),
    ("ControlGetHwnd", 4, Wants::Declared(TypeName::String)),
    ("ControlGetIndex", 2, Wants::Declared(TypeName::String)),
    ("ControlGetIndex", 3, Wants::Declared(TypeName::String)),
    ("ControlGetIndex", 4, Wants::Declared(TypeName::String)),
    ("ControlGetItems", 2, Wants::Declared(TypeName::String)),
    ("ControlGetItems", 3, Wants::Declared(TypeName::String)),
    ("ControlGetItems", 4, Wants::Declared(TypeName::String)),
    ("ControlGetPos", 0, Wants::Reference("a VarRef")),
    ("ControlGetPos", 1, Wants::Reference("a VarRef")),
    ("ControlGetPos", 2, Wants::Reference("a VarRef")),
    ("ControlGetPos", 3, Wants::Reference("a VarRef")),
    ("ControlGetPos", 6, Wants::Declared(TypeName::String)),
    ("ControlGetPos", 7, Wants::Declared(TypeName::String)),
    ("ControlGetPos", 8, Wants::Declared(TypeName::String)),
    ("ControlGetStyle", 2, Wants::Declared(TypeName::String)),
    ("ControlGetStyle", 3, Wants::Declared(TypeName::String)),
    ("ControlGetStyle", 4, Wants::Declared(TypeName::String)),
    ("ControlGetText", 2, Wants::Declared(TypeName::String)),
    ("ControlGetText", 3, Wants::Declared(TypeName::String)),
    ("ControlGetText", 4, Wants::Declared(TypeName::String)),
    ("ControlGetVisible", 2, Wants::Declared(TypeName::String)),
    ("ControlGetVisible", 3, Wants::Declared(TypeName::String)),
    ("ControlGetVisible", 4, Wants::Declared(TypeName::String)),
    ("ControlHide", 2, Wants::Declared(TypeName::String)),
    ("ControlHide", 3, Wants::Declared(TypeName::String)),
    ("ControlHide", 4, Wants::Declared(TypeName::String)),
    ("ControlHideDropDown", 2, Wants::Declared(TypeName::String)),
    ("ControlHideDropDown", 3, Wants::Declared(TypeName::String)),
    ("ControlHideDropDown", 4, Wants::Declared(TypeName::String)),
    ("ControlMove", 0, Wants::Declared(TypeName::Number)),
    ("ControlMove", 1, Wants::Declared(TypeName::Number)),
    ("ControlMove", 2, Wants::Declared(TypeName::Number)),
    ("ControlMove", 3, Wants::Declared(TypeName::Number)),
    ("ControlMove", 6, Wants::Declared(TypeName::String)),
    ("ControlMove", 7, Wants::Declared(TypeName::String)),
    ("ControlMove", 8, Wants::Declared(TypeName::String)),
    ("ControlSend", 0, Wants::Declared(TypeName::String)),
    ("ControlSend", 3, Wants::Declared(TypeName::String)),
    ("ControlSend", 4, Wants::Declared(TypeName::String)),
    ("ControlSend", 5, Wants::Declared(TypeName::String)),
    ("ControlSendText", 0, Wants::Declared(TypeName::String)),
    ("ControlSendText", 3, Wants::Declared(TypeName::String)),
    ("ControlSendText", 4, Wants::Declared(TypeName::String)),
    ("ControlSendText", 5, Wants::Declared(TypeName::String)),
    ("ControlSetChecked", 0, Wants::Declared(TypeName::Number)),
    ("ControlSetChecked", 3, Wants::Declared(TypeName::String)),
    ("ControlSetChecked", 4, Wants::Declared(TypeName::String)),
    ("ControlSetChecked", 5, Wants::Declared(TypeName::String)),
    ("ControlSetEnabled", 0, Wants::Declared(TypeName::Number)),
    ("ControlSetEnabled", 3, Wants::Declared(TypeName::String)),
    ("ControlSetEnabled", 4, Wants::Declared(TypeName::String)),
    ("ControlSetEnabled", 5, Wants::Declared(TypeName::String)),
    ("ControlSetExStyle", 0, Wants::Declared(TypeName::String)),
    ("ControlSetExStyle", 3, Wants::Declared(TypeName::String)),
    ("ControlSetExStyle", 4, Wants::Declared(TypeName::String)),
    ("ControlSetExStyle", 5, Wants::Declared(TypeName::String)),
    ("ControlSetStyle", 0, Wants::Declared(TypeName::String)),
    ("ControlSetStyle", 3, Wants::Declared(TypeName::String)),
    ("ControlSetStyle", 4, Wants::Declared(TypeName::String)),
    ("ControlSetStyle", 5, Wants::Declared(TypeName::String)),
    ("ControlSetText", 0, Wants::Declared(TypeName::String)),
    ("ControlSetText", 3, Wants::Declared(TypeName::String)),
    ("ControlSetText", 4, Wants::Declared(TypeName::String)),
    ("ControlSetText", 5, Wants::Declared(TypeName::String)),
    ("ControlShow", 2, Wants::Declared(TypeName::String)),
    ("ControlShow", 3, Wants::Declared(TypeName::String)),
    ("ControlShow", 4, Wants::Declared(TypeName::String)),
    ("ControlShowDropDown", 2, Wants::Declared(TypeName::String)),
    ("ControlShowDropDown", 3, Wants::Declared(TypeName::String)),
    ("ControlShowDropDown", 4, Wants::Declared(TypeName::String)),
    ("Critical", 0, Wants::Declared(TypeName::String)),
    ("DriveEject", 0, Wants::Declared(TypeName::String)),
    ("DriveGetCapacity", 0, Wants::Declared(TypeName::String)),
    ("DriveGetFilesystem", 0, Wants::Declared(TypeName::String)),
    ("DriveGetLabel", 0, Wants::Declared(TypeName::String)),
    ("DriveGetList", 0, Wants::Declared(TypeName::String)),
    ("DriveGetSerial", 0, Wants::Declared(TypeName::String)),
    ("DriveGetSpaceFree", 0, Wants::Declared(TypeName::String)),
    ("DriveGetStatus", 0, Wants::Declared(TypeName::String)),
    ("DriveGetStatusCD", 0, Wants::Declared(TypeName::String)),
    ("DriveGetType", 0, Wants::Declared(TypeName::String)),
    ("DriveLock", 0, Wants::Declared(TypeName::String)),
    ("DriveRetract", 0, Wants::Declared(TypeName::String)),
    ("DriveSetLabel", 0, Wants::Declared(TypeName::String)),
    ("DriveSetLabel", 1, Wants::Declared(TypeName::String)),
    ("DriveUnlock", 0, Wants::Declared(TypeName::String)),
    ("EditGetCurrentCol", 2, Wants::Declared(TypeName::String)),
    ("EditGetCurrentCol", 3, Wants::Declared(TypeName::String)),
    ("EditGetCurrentCol", 4, Wants::Declared(TypeName::String)),
    ("EditGetCurrentLine", 2, Wants::Declared(TypeName::String)),
    ("EditGetCurrentLine", 3, Wants::Declared(TypeName::String)),
    ("EditGetCurrentLine", 4, Wants::Declared(TypeName::String)),
    ("EditGetLine", 0, Wants::Declared(TypeName::Number)),
    ("EditGetLine", 3, Wants::Declared(TypeName::String)),
    ("EditGetLine", 4, Wants::Declared(TypeName::String)),
    ("EditGetLine", 5, Wants::Declared(TypeName::String)),
    ("EditGetLineCount", 2, Wants::Declared(TypeName::String)),
    ("EditGetLineCount", 3, Wants::Declared(TypeName::String)),
    ("EditGetLineCount", 4, Wants::Declared(TypeName::String)),
    ("EditGetSelectedText", 2, Wants::Declared(TypeName::String)),
    ("EditGetSelectedText", 3, Wants::Declared(TypeName::String)),
    ("EditGetSelectedText", 4, Wants::Declared(TypeName::String)),
    ("EditPaste", 0, Wants::Declared(TypeName::String)),
    ("EditPaste", 3, Wants::Declared(TypeName::String)),
    ("EditPaste", 4, Wants::Declared(TypeName::String)),
    ("EditPaste", 5, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 0, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 1, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 2, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 3, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 4, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 5, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 6, Wants::Declared(TypeName::String)),
    ("FileCreateShortcut", 7, Wants::Declared(TypeName::Number)),
    ("FileCreateShortcut", 8, Wants::Declared(TypeName::Number)),
    ("FileGetShortcut", 0, Wants::Declared(TypeName::String)),
    ("FileGetShortcut", 1, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 2, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 3, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 4, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 5, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 6, Wants::Reference("a VarRef")),
    ("FileGetShortcut", 7, Wants::Reference("a VarRef")),
    ("FileGetVersion", 0, Wants::Declared(TypeName::String)),
    ("FileRecycle", 0, Wants::Declared(TypeName::String)),
    ("FileRecycleEmpty", 0, Wants::Declared(TypeName::String)),
    ("GroupActivate", 0, Wants::Declared(TypeName::String)),
    ("GroupActivate", 1, Wants::Declared(TypeName::String)),
    ("GroupAdd", 0, Wants::Declared(TypeName::String)),
    ("GroupAdd", 1, Wants::Declared(TypeName::String)),
    ("GroupAdd", 2, Wants::Declared(TypeName::String)),
    ("GroupAdd", 3, Wants::Declared(TypeName::String)),
    ("GroupAdd", 4, Wants::Declared(TypeName::String)),
    ("GroupClose", 0, Wants::Declared(TypeName::String)),
    ("GroupClose", 1, Wants::Declared(TypeName::String)),
    ("GroupDeactivate", 0, Wants::Declared(TypeName::String)),
    ("GroupDeactivate", 1, Wants::Declared(TypeName::String)),
    ("GuiCtrlFromHwnd", 0, Wants::Declared(TypeName::Number)),
    ("GuiFromHwnd", 0, Wants::Declared(TypeName::Number)),
    ("IL_Add", 0, Wants::Declared(TypeName::Number)),
    ("IL_Add", 1, Wants::Declared(TypeName::String)),
    ("IL_Add", 2, Wants::Declared(TypeName::Number)),
    ("IL_Create", 0, Wants::Declared(TypeName::Number)),
    ("IL_Create", 1, Wants::Declared(TypeName::Number)),
    ("IL_Destroy", 0, Wants::Declared(TypeName::Number)),
    ("ListLines", 0, Wants::Declared(TypeName::Number)),
    ("ListViewGetContent", 0, Wants::Declared(TypeName::String)),
    ("ListViewGetContent", 3, Wants::Declared(TypeName::String)),
    ("ListViewGetContent", 4, Wants::Declared(TypeName::String)),
    ("ListViewGetContent", 5, Wants::Declared(TypeName::String)),
    ("MenuFromHandle", 0, Wants::Declared(TypeName::Number)),
    ("MenuSelect", 1, Wants::Declared(TypeName::String)),
    ("MenuSelect", 2, Wants::Declared(TypeName::String)),
    ("MenuSelect", 3, Wants::Declared(TypeName::String)),
    ("MenuSelect", 4, Wants::Declared(TypeName::String)),
    ("MenuSelect", 5, Wants::Declared(TypeName::String)),
    ("MenuSelect", 6, Wants::Declared(TypeName::String)),
    ("MenuSelect", 7, Wants::Declared(TypeName::String)),
    ("MenuSelect", 8, Wants::Declared(TypeName::String)),
    ("MenuSelect", 9, Wants::Declared(TypeName::String)),
    ("MenuSelect", 10, Wants::Declared(TypeName::String)),
    ("MonitorGet", 0, Wants::Declared(TypeName::Number)),
    // The four that follow are values of the kind VarRef in the table of the
    // binary, and the kind is named by the match at the end of this function:
    // a `Wants::Reference` here would say the same words but would put the
    // empty text in the `What`, and the binary puts the name of the built-in
    // there (measured on 2026-11-09).
    ("MonitorGetName", 0, Wants::Declared(TypeName::Number)),
    ("MonitorGetWorkArea", 0, Wants::Declared(TypeName::Number)),
    ("OnMessage", 0, Wants::Declared(TypeName::Number)),
    ("OutputDebug", 0, Wants::Declared(TypeName::String)),
    ("Pause", 0, Wants::Declared(TypeName::Number)),
    ("PostMessage", 0, Wants::Declared(TypeName::Number)),
    ("PostMessage", 5, Wants::Declared(TypeName::String)),
    ("PostMessage", 6, Wants::Declared(TypeName::String)),
    ("PostMessage", 7, Wants::Declared(TypeName::String)),
    ("ProcessClose", 0, Wants::Declared(TypeName::String)),
    ("ProcessExist", 0, Wants::Declared(TypeName::String)),
    ("ProcessGetName", 0, Wants::Declared(TypeName::String)),
    ("ProcessGetParent", 0, Wants::Declared(TypeName::String)),
    ("ProcessGetPath", 0, Wants::Declared(TypeName::String)),
    ("ProcessSetPriority", 0, Wants::Declared(TypeName::String)),
    ("ProcessSetPriority", 1, Wants::Declared(TypeName::String)),
    ("ProcessWait", 0, Wants::Declared(TypeName::String)),
    ("ProcessWait", 1, Wants::Declared(TypeName::Number)),
    ("ProcessWaitClose", 0, Wants::Declared(TypeName::String)),
    ("ProcessWaitClose", 1, Wants::Declared(TypeName::Number)),
    ("RunAs", 0, Wants::Declared(TypeName::String)),
    ("RunAs", 1, Wants::Declared(TypeName::String)),
    ("RunAs", 2, Wants::Declared(TypeName::String)),
    ("SendMessage", 0, Wants::Declared(TypeName::Number)),
    ("SendMessage", 5, Wants::Declared(TypeName::String)),
    ("SendMessage", 6, Wants::Declared(TypeName::String)),
    ("SendMessage", 7, Wants::Declared(TypeName::String)),
    ("SendMessage", 8, Wants::Declared(TypeName::Number)),
    ("SetCapsLockState", 0, Wants::Declared(TypeName::String)),
    ("SetNumLockState", 0, Wants::Declared(TypeName::String)),
    ("SetScrollLockState", 0, Wants::Declared(TypeName::String)),
    ("Shutdown", 0, Wants::Declared(TypeName::Number)),
    ("SoundGetName", 0, Wants::Declared(TypeName::String)),
    ("SoundGetName", 1, Wants::Declared(TypeName::String)),
    ("StatusBarGetText", 0, Wants::Declared(TypeName::Number)),
    ("StatusBarGetText", 2, Wants::Declared(TypeName::String)),
    ("StatusBarGetText", 3, Wants::Declared(TypeName::String)),
    ("StatusBarGetText", 4, Wants::Declared(TypeName::String)),
    ("StatusBarWait", 0, Wants::Declared(TypeName::String)),
    ("StatusBarWait", 1, Wants::Declared(TypeName::Number)),
    ("StatusBarWait", 2, Wants::Declared(TypeName::Number)),
    ("StatusBarWait", 4, Wants::Declared(TypeName::String)),
    ("StatusBarWait", 5, Wants::Declared(TypeName::Number)),
    ("StatusBarWait", 6, Wants::Declared(TypeName::String)),
    ("StatusBarWait", 7, Wants::Declared(TypeName::String)),
    ("StrPtr", 0, Wants::Checked(TypeName::String)),
    ("StrPut", 0, Wants::Declared(TypeName::String)),
    ("Suspend", 0, Wants::Declared(TypeName::Number)),
    ("SysGet", 0, Wants::Declared(TypeName::Number)),
    ("Thread", 0, Wants::Declared(TypeName::String)),
    ("Thread", 1, Wants::Declared(TypeName::Number)),
    ("Thread", 2, Wants::Declared(TypeName::Number)),
    ("ToolTip", 0, Wants::Declared(TypeName::String)),
    ("ToolTip", 1, Wants::Declared(TypeName::Number)),
    ("ToolTip", 2, Wants::Declared(TypeName::Number)),
    ("ToolTip", 3, Wants::Declared(TypeName::Number)),
    ("TraySetIcon", 0, Wants::Declared(TypeName::String)),
    ("TraySetIcon", 1, Wants::Declared(TypeName::Number)),
    ("TrayTip", 0, Wants::Declared(TypeName::String)),
    ("TrayTip", 1, Wants::Declared(TypeName::String)),
    ("TrayTip", 2, Wants::Declared(TypeName::String)),
    ("WinActivate", 1, Wants::Declared(TypeName::String)),
    ("WinActivate", 2, Wants::Declared(TypeName::String)),
    ("WinActivate", 3, Wants::Declared(TypeName::String)),
    ("WinActivateBottom", 1, Wants::Declared(TypeName::String)),
    ("WinActivateBottom", 2, Wants::Declared(TypeName::String)),
    ("WinActivateBottom", 3, Wants::Declared(TypeName::String)),
    ("WinClose", 1, Wants::Declared(TypeName::String)),
    ("WinClose", 2, Wants::Declared(TypeName::Number)),
    ("WinClose", 3, Wants::Declared(TypeName::String)),
    ("WinClose", 4, Wants::Declared(TypeName::String)),
    ("WinGetClass", 1, Wants::Declared(TypeName::String)),
    ("WinGetClass", 2, Wants::Declared(TypeName::String)),
    ("WinGetClass", 3, Wants::Declared(TypeName::String)),
    ("WinGetClientPos", 0, Wants::Reference("a VarRef")),
    ("WinGetClientPos", 1, Wants::Reference("a VarRef")),
    ("WinGetClientPos", 2, Wants::Reference("a VarRef")),
    ("WinGetClientPos", 3, Wants::Reference("a VarRef")),
    ("WinGetClientPos", 5, Wants::Declared(TypeName::String)),
    ("WinGetClientPos", 6, Wants::Declared(TypeName::String)),
    ("WinGetClientPos", 7, Wants::Declared(TypeName::String)),
    ("WinGetControls", 1, Wants::Declared(TypeName::String)),
    ("WinGetControls", 2, Wants::Declared(TypeName::String)),
    ("WinGetControls", 3, Wants::Declared(TypeName::String)),
    ("WinGetControlsHwnd", 1, Wants::Declared(TypeName::String)),
    ("WinGetControlsHwnd", 2, Wants::Declared(TypeName::String)),
    ("WinGetControlsHwnd", 3, Wants::Declared(TypeName::String)),
    ("WinGetCount", 1, Wants::Declared(TypeName::String)),
    ("WinGetCount", 2, Wants::Declared(TypeName::String)),
    ("WinGetCount", 3, Wants::Declared(TypeName::String)),
    ("WinGetExStyle", 1, Wants::Declared(TypeName::String)),
    ("WinGetExStyle", 2, Wants::Declared(TypeName::String)),
    ("WinGetExStyle", 3, Wants::Declared(TypeName::String)),
    ("WinGetID", 1, Wants::Declared(TypeName::String)),
    ("WinGetID", 2, Wants::Declared(TypeName::String)),
    ("WinGetID", 3, Wants::Declared(TypeName::String)),
    ("WinGetIDLast", 1, Wants::Declared(TypeName::String)),
    ("WinGetIDLast", 2, Wants::Declared(TypeName::String)),
    ("WinGetIDLast", 3, Wants::Declared(TypeName::String)),
    ("WinGetList", 1, Wants::Declared(TypeName::String)),
    ("WinGetList", 2, Wants::Declared(TypeName::String)),
    ("WinGetList", 3, Wants::Declared(TypeName::String)),
    ("WinGetMinMax", 1, Wants::Declared(TypeName::String)),
    ("WinGetMinMax", 2, Wants::Declared(TypeName::String)),
    ("WinGetMinMax", 3, Wants::Declared(TypeName::String)),
    ("WinGetPID", 1, Wants::Declared(TypeName::String)),
    ("WinGetPID", 2, Wants::Declared(TypeName::String)),
    ("WinGetPID", 3, Wants::Declared(TypeName::String)),
    ("WinGetPos", 0, Wants::Reference("a VarRef")),
    ("WinGetPos", 1, Wants::Reference("a VarRef")),
    ("WinGetPos", 2, Wants::Reference("a VarRef")),
    ("WinGetPos", 3, Wants::Reference("a VarRef")),
    ("WinGetPos", 5, Wants::Declared(TypeName::String)),
    ("WinGetPos", 6, Wants::Declared(TypeName::String)),
    ("WinGetPos", 7, Wants::Declared(TypeName::String)),
    ("WinGetProcessName", 1, Wants::Declared(TypeName::String)),
    ("WinGetProcessName", 2, Wants::Declared(TypeName::String)),
    ("WinGetProcessName", 3, Wants::Declared(TypeName::String)),
    ("WinGetProcessPath", 1, Wants::Declared(TypeName::String)),
    ("WinGetProcessPath", 2, Wants::Declared(TypeName::String)),
    ("WinGetProcessPath", 3, Wants::Declared(TypeName::String)),
    ("WinGetStyle", 1, Wants::Declared(TypeName::String)),
    ("WinGetStyle", 2, Wants::Declared(TypeName::String)),
    ("WinGetStyle", 3, Wants::Declared(TypeName::String)),
    ("WinGetText", 1, Wants::Declared(TypeName::String)),
    ("WinGetText", 2, Wants::Declared(TypeName::String)),
    ("WinGetText", 3, Wants::Declared(TypeName::String)),
    ("WinGetTransColor", 1, Wants::Declared(TypeName::String)),
    ("WinGetTransColor", 2, Wants::Declared(TypeName::String)),
    ("WinGetTransColor", 3, Wants::Declared(TypeName::String)),
    ("WinGetTransparent", 1, Wants::Declared(TypeName::String)),
    ("WinGetTransparent", 2, Wants::Declared(TypeName::String)),
    ("WinGetTransparent", 3, Wants::Declared(TypeName::String)),
    ("WinHide", 1, Wants::Declared(TypeName::String)),
    ("WinHide", 2, Wants::Declared(TypeName::String)),
    ("WinHide", 3, Wants::Declared(TypeName::String)),
    ("WinKill", 1, Wants::Declared(TypeName::String)),
    ("WinKill", 2, Wants::Declared(TypeName::Number)),
    ("WinKill", 3, Wants::Declared(TypeName::String)),
    ("WinKill", 4, Wants::Declared(TypeName::String)),
    ("WinMaximize", 1, Wants::Declared(TypeName::String)),
    ("WinMaximize", 2, Wants::Declared(TypeName::String)),
    ("WinMaximize", 3, Wants::Declared(TypeName::String)),
    ("WinMinimize", 1, Wants::Declared(TypeName::String)),
    ("WinMinimize", 2, Wants::Declared(TypeName::String)),
    ("WinMinimize", 3, Wants::Declared(TypeName::String)),
    ("WinMove", 0, Wants::Declared(TypeName::Number)),
    ("WinMove", 1, Wants::Declared(TypeName::Number)),
    ("WinMove", 2, Wants::Declared(TypeName::Number)),
    ("WinMove", 3, Wants::Declared(TypeName::Number)),
    ("WinMove", 5, Wants::Declared(TypeName::String)),
    ("WinMove", 6, Wants::Declared(TypeName::String)),
    ("WinMove", 7, Wants::Declared(TypeName::String)),
    ("WinMoveBottom", 1, Wants::Declared(TypeName::String)),
    ("WinMoveBottom", 2, Wants::Declared(TypeName::String)),
    ("WinMoveBottom", 3, Wants::Declared(TypeName::String)),
    ("WinMoveTop", 1, Wants::Declared(TypeName::String)),
    ("WinMoveTop", 2, Wants::Declared(TypeName::String)),
    ("WinMoveTop", 3, Wants::Declared(TypeName::String)),
    ("WinRedraw", 1, Wants::Declared(TypeName::String)),
    ("WinRedraw", 2, Wants::Declared(TypeName::String)),
    ("WinRedraw", 3, Wants::Declared(TypeName::String)),
    ("WinRestore", 1, Wants::Declared(TypeName::String)),
    ("WinRestore", 2, Wants::Declared(TypeName::String)),
    ("WinRestore", 3, Wants::Declared(TypeName::String)),
    ("WinSetAlwaysOnTop", 0, Wants::Declared(TypeName::Number)),
    ("WinSetAlwaysOnTop", 2, Wants::Declared(TypeName::String)),
    ("WinSetAlwaysOnTop", 3, Wants::Declared(TypeName::String)),
    ("WinSetAlwaysOnTop", 4, Wants::Declared(TypeName::String)),
    ("WinSetEnabled", 0, Wants::Declared(TypeName::Number)),
    ("WinSetEnabled", 2, Wants::Declared(TypeName::String)),
    ("WinSetEnabled", 3, Wants::Declared(TypeName::String)),
    ("WinSetEnabled", 4, Wants::Declared(TypeName::String)),
    ("WinSetExStyle", 0, Wants::Declared(TypeName::String)),
    ("WinSetExStyle", 2, Wants::Declared(TypeName::String)),
    ("WinSetExStyle", 3, Wants::Declared(TypeName::String)),
    ("WinSetExStyle", 4, Wants::Declared(TypeName::String)),
    ("WinSetRegion", 0, Wants::Declared(TypeName::String)),
    ("WinSetRegion", 2, Wants::Declared(TypeName::String)),
    ("WinSetRegion", 3, Wants::Declared(TypeName::String)),
    ("WinSetRegion", 4, Wants::Declared(TypeName::String)),
    ("WinSetStyle", 0, Wants::Declared(TypeName::String)),
    ("WinSetStyle", 2, Wants::Declared(TypeName::String)),
    ("WinSetStyle", 3, Wants::Declared(TypeName::String)),
    ("WinSetStyle", 4, Wants::Declared(TypeName::String)),
    ("WinSetTitle", 0, Wants::Declared(TypeName::String)),
    ("WinSetTitle", 2, Wants::Declared(TypeName::String)),
    ("WinSetTitle", 3, Wants::Declared(TypeName::String)),
    ("WinSetTitle", 4, Wants::Declared(TypeName::String)),
    ("WinSetTransColor", 2, Wants::Declared(TypeName::String)),
    ("WinSetTransColor", 3, Wants::Declared(TypeName::String)),
    ("WinSetTransColor", 4, Wants::Declared(TypeName::String)),
    ("WinSetTransparent", 0, Wants::Declared(TypeName::String)),
    ("WinSetTransparent", 2, Wants::Declared(TypeName::String)),
    ("WinSetTransparent", 3, Wants::Declared(TypeName::String)),
    ("WinSetTransparent", 4, Wants::Declared(TypeName::String)),
    ("WinShow", 1, Wants::Declared(TypeName::String)),
    ("WinShow", 2, Wants::Declared(TypeName::String)),
    ("WinShow", 3, Wants::Declared(TypeName::String)),
    ("WinWait", 1, Wants::Declared(TypeName::String)),
    ("WinWait", 2, Wants::Declared(TypeName::Number)),
    ("WinWait", 3, Wants::Declared(TypeName::String)),
    ("WinWait", 4, Wants::Declared(TypeName::String)),
    ("WinWaitActive", 1, Wants::Declared(TypeName::String)),
    ("WinWaitActive", 2, Wants::Declared(TypeName::Number)),
    ("WinWaitActive", 3, Wants::Declared(TypeName::String)),
    ("WinWaitActive", 4, Wants::Declared(TypeName::String)),
    ("WinWaitClose", 1, Wants::Declared(TypeName::String)),
    ("WinWaitClose", 2, Wants::Declared(TypeName::Number)),
    ("WinWaitClose", 3, Wants::Declared(TypeName::String)),
    ("WinWaitClose", 4, Wants::Declared(TypeName::String)),
    ("WinWaitNotActive", 1, Wants::Declared(TypeName::String)),
    ("WinWaitNotActive", 2, Wants::Declared(TypeName::Number)),
    ("WinWaitNotActive", 3, Wants::Declared(TypeName::String)),
    ("WinWaitNotActive", 4, Wants::Declared(TypeName::String)),
    // The parameters that the caller passes a variable reference to.
    // Measured on the binary of v2.0.19 on 2026-11-09: a value that is not
    // a reference is refused with "requires a variable reference, but
    // received a ...", and the failure carries no name of the built-in in
    // its `What` -- the caller's check makes it, and not the built-in.
    ("RegExMatch", 2, Wants::Reference("a variable reference")),
    ("RegExReplace", 3, Wants::Reference("a variable reference")),
    (
        "VarSetStrCapacity",
        0,
        Wants::Reference("a variable reference"),
    ),
];

pub fn wants(name: &str, index: usize) -> Wants {
    let place = index as u8;
    if THE_TEXTS
        .iter()
        .any(|(built_in, indexes)| *built_in == name && indexes.contains(&place))
    {
        return Wants::Declared(TypeName::String);
    }
    if THE_NUMBERS
        .iter()
        .any(|(built_in, indexes)| *built_in == name && indexes.contains(&place))
    {
        return Wants::Declared(TypeName::Number);
    }
    if let Some((_, _, kind)) = THE_REFUSED
        .iter()
        .find(|(built_in, place, _)| *built_in == name && *place == index)
    {
        return *kind;
    }
    match (name, place) {
        // Every parameter of the two is a number, and there is no telling
        // how many of them there are.
        ("Min" | "Max", _) => Wants::Declared(TypeName::Number),
        ("ObjOwnProps" | "ObjOwnPropCount" | "ObjHasOwnProp" | "ObjSetBase", 0) => {
            Wants::Checked(TypeName::Object)
        }
        // Measured on the binary of v2.0.19 on 2026-11-09: the last four
        // parameters of the two monitor commands are values of the kind
        // `VarRef`, and v2 names the kind in the failure of another one with
        // "requires a VarRef, but received ..." -- the wording of a declared
        // kind, and the name of the built-in in the `What`.
        ("MonitorGet" | "MonitorGetWorkArea", 1..=4) => Wants::Declared(TypeName::VarRef),
        _ => Wants::Value,
    }
}

/// The built-ins that refuse the parameter themselves.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the `Mod` says
/// "Invalid parameter(s)." for anything that is not a number -- a text,
/// an object and a reference alike -- and it does not name the type that
/// was wrong. The tree says it in its handler, and the guard above lets
/// it speak.
pub fn refuses_itself(name: &str) -> bool {
    matches!(name, "Mod")
}

/// The handlers of the object model.
///
/// The names of v2 reach the object model from here: the base of an
/// object, the properties it owns, and the room it has for them.
pub(crate) fn obj_get_base(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    rt.base_of(&target).ok_or_else(|| RuntimeError {
        message: crate::runtime::expected_type(TypeName::Object, target.type_name()),
        line,
    })
}

pub(crate) fn obj_set_base(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let base = values.get(1).cloned().unwrap_or(Value::Text(String::new()));
    if !matches!(base, Value::Object(_)) {
        return Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::Object, base.type_name()),
            line,
        });
    }
    // The answer is the base the object had, and an object of a script
    // has none until the script gives it one.
    let old = rt
        .stored_base_of(&target)
        .unwrap_or(Value::Text(String::new()));
    rt.set_base_of(&target, base, line)?;
    Ok(old)
}

pub(crate) fn obj_own_props(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    rt.own_method(&target, "ownprops", &[], line)
}

pub(crate) fn obj_own_prop_count(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let names = rt.own_method(&target, "ownprops", &[], line)?;
    // The own properties of v2 are an enumerator, and the count of them is
    // the number of the turns it has left.
    Ok(Value::Int(crate::classes::enumerator::the_count(&names)))
}

pub(crate) fn obj_has_own_prop(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let name = values.get(1).cloned().unwrap_or(Value::Text(String::new()));
    rt.own_method(&target, "hasownprop", &[name], line)
}

pub(crate) fn obj_get_capacity(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    if !matches!(target, Value::Object(_)) {
        return Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::Object, target.type_name()),
            line,
        });
    }
    // The room an object has is the capacity of its properties, and an
    // object without any has none.
    Ok(rt
        .property_of(&target, "capacity", line)
        .unwrap_or(Value::Int(0)))
}

pub(crate) fn obj_set_capacity(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let capacity = values.get(1).cloned().unwrap_or(Value::Int(0));
    if !matches!(target, Value::Object(_)) {
        return Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::Object, target.type_name()),
            line,
        });
    }
    rt.write_property_of(&target, "capacity", capacity, line)?;
    Ok(Value::Int(1))
}

/// `ObjAddRef`: the reference count of an object, one more.
///
/// v2 counts the references of a COM object, and an object of a script
/// has no such count: the built-in says that the parameter is invalid.
pub(crate) fn obj_add_ref(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: crate::runtime::invalid_parameter(1, "ObjAddRef"),
        line,
    })
}

// -- the helpers ----------------------------------------------------------------

/// The text of the argument at this place, or the empty string.
fn text_of(values: &[Value], index: usize) -> String {
    values
        .get(index)
        .map(|value| value.to_text())
        .unwrap_or_default()
}

/// The number of the argument at this place, or zero.
fn number_of(values: &[Value], index: usize) -> f64 {
    values
        .get(index)
        .and_then(|value| value.to_number())
        .unwrap_or(0.0)
}

/// The number a value holds, and the kind it has.
///
/// A text that holds a number is a number: a whole one is an integer and
/// one with a point is a float, the way v2 reads them.
fn number_value(value: &Value) -> Option<Value> {
    match value {
        Value::Int(_) | Value::Float(_) => Some(value.clone()),
        Value::Text(text) => {
            let trimmed = text.trim();
            if trimmed.is_empty() {
                return None;
            }
            let number: f64 = trimmed.parse().ok()?;
            if trimmed.contains('.') || trimmed.contains('e') || trimmed.contains('E') {
                Some(Value::Float(number))
            } else {
                Some(Value::Int(number as i64))
            }
        }
        _ => None,
    }
}

/// Whether a value is a number, the way a parameter that wants one is
/// checked.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a value is a number when
/// it is one, and a text is one when it holds a number and nothing else. The
/// spaces and tabs at the two ends are allowed, the `0x` of a hex number is
/// allowed, a fraction and an exponent are allowed, and a letter after the
/// number is not.
pub(crate) fn is_numeric_value(value: &Value) -> bool {
    match value {
        Value::Int(_) | Value::Float(_) => true,
        Value::Text(text) => is_numeric_text(text),
        _ => false,
    }
}

/// Whether the text holds a number and nothing else.
///
/// The rule is the one of `IsNumeric` of the binary: the leading spaces and
/// tabs are skipped, the sign is allowed, a `0x` prefix makes it hex, a
/// fraction and an exponent are allowed for a decimal number, and only spaces
/// and tabs may follow it.
fn is_numeric_text(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut at = 0;
    while at < bytes.len() && (bytes[at] == b' ' || bytes[at] == b'\t') {
        at += 1;
    }
    if at >= bytes.len() {
        return false;
    }
    if bytes[at] == b'-' || bytes[at] == b'+' {
        at += 1;
    }
    let hex = is_hex_at(bytes, at);
    if hex {
        at += 2;
    }
    let mut point = false;
    let mut exponent = false;
    let mut digit = false;
    while at < bytes.len() {
        let character = bytes[at];
        if character == b' ' || character == b'\t' {
            // The number ends here when nothing but spaces or tabs follows.
            let mut next = at;
            while next < bytes.len() && (bytes[next] == b' ' || bytes[next] == b'\t') {
                next += 1;
            }
            if next < bytes.len() {
                return false;
            }
            break;
        }
        if character == b'.' {
            if point || hex {
                return false;
            }
            point = true;
            at += 1;
            continue;
        }
        let is_digit = if hex {
            character.is_ascii_hexdigit()
        } else {
            character.is_ascii_digit()
        };
        if !is_digit {
            // Only a decimal number may carry an exponent, and the exponent
            // has to hold at least one digit.
            if hex || (character != b'e' && character != b'E') || !digit || exponent {
                return false;
            }
            let mut next = at + 1;
            if next < bytes.len() && (bytes[next] == b'+' || bytes[next] == b'-') {
                next += 1;
            }
            if next >= bytes.len() || !bytes[next].is_ascii_digit() {
                return false;
            }
            exponent = true;
            point = true;
            at = next + 1;
            continue;
        }
        digit = true;
        at += 1;
    }
    digit
}

/// Whether a `0x` prefix of a hex number starts at this byte.
fn is_hex_at(bytes: &[u8], at: usize) -> bool {
    at + 2 < bytes.len()
        && bytes[at] == b'0'
        && (bytes[at + 1] == b'x' || bytes[at + 1] == b'X')
        && bytes[at + 2].is_ascii_hexdigit()
}

/// The value of one hex digit.
fn hex_digit(character: u8) -> u64 {
    match character {
        b'0'..=b'9' => (character - b'0') as u64,
        b'a'..=b'f' => (character - b'a') as u64 + 10,
        _ => (character - b'A') as u64 + 10,
    }
}

/// The whole number a value holds, the way the conversion of the binary
/// reads it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a float is cut toward
/// zero, and a number that a 64-bit integer cannot hold answers the smallest
/// one -- the cast of the machine, and not a saturation. A text is read by
/// [`text_to_int64`].
pub(crate) fn token_to_int64(value: &Value) -> i64 {
    match value {
        Value::Int(number) => *number,
        Value::Float(number) => double_to_int64(*number),
        Value::Text(text) => text_to_int64(text),
        _ => 0,
    }
}

/// The whole number of a float, the way the cast of the binary reads it.
///
/// The cast of the machine answers the smallest 64-bit integer for a number
/// that is out of its range, and for a number that is not one at all.
fn double_to_int64(number: f64) -> i64 {
    if !(-9223372036854775808.0..9223372036854775808.0).contains(&number) {
        return i64::MIN;
    }
    number as i64
}

/// The number a value holds, the way the conversion of the binary reads it.
pub(crate) fn token_to_double(value: &Value) -> f64 {
    match value {
        Value::Int(number) => *number as f64,
        Value::Float(number) => *number,
        Value::Text(text) => text_to_double(text),
        _ => 0.0,
    }
}

/// The whole number at the front of a text.
///
/// The rule is the one of `nstrtoi64` of the binary, measured on 2026-11-09:
/// a decimal number with a fraction and an exponent, or a hex number with the
/// `0x` prefix; the leading spaces and tabs are skipped; a leading zero does
/// not make it octal; and the overflow wraps the way the arithmetic of a
/// script wraps. `"1e3"` is 1000, `"1.9"` is 1, `"010"` is 10 and `"0x1F"`
/// is 31.
pub(crate) fn text_to_int64(text: &str) -> i64 {
    let bytes = text.as_bytes();
    let mut at = 0;
    while at < bytes.len() && (bytes[at] == b' ' || bytes[at] == b'\t') {
        at += 1;
    }
    let negative = at < bytes.len() && bytes[at] == b'-';
    if negative || (at < bytes.len() && bytes[at] == b'+') {
        at += 1;
    }
    let mut value: u64;
    if is_hex_at(bytes, at) {
        at += 2;
        value = 0;
        while at < bytes.len() && bytes[at].is_ascii_hexdigit() {
            value = value.wrapping_mul(16).wrapping_add(hex_digit(bytes[at]));
            at += 1;
        }
    } else {
        value = 0;
        while at < bytes.len() && bytes[at].is_ascii_digit() {
            value = value
                .wrapping_mul(10)
                .wrapping_add((bytes[at] - b'0') as u64);
            at += 1;
        }
        let end_integer = at;
        if at < bytes.len() && bytes[at] == b'.' {
            at += 1;
            while at < bytes.len() && bytes[at].is_ascii_digit() {
                at += 1;
            }
        }
        let end_fraction = at;
        if at < bytes.len() && (bytes[at] == b'e' || bytes[at] == b'E') {
            at += 1;
            let exponent_negative = at < bytes.len() && bytes[at] == b'-';
            if exponent_negative || (at < bytes.len() && bytes[at] == b'+') {
                at += 1;
            }
            let digits_start = at;
            let mut exponent: u64 = 0;
            while at < bytes.len() && bytes[at].is_ascii_digit() {
                exponent = exponent
                    .wrapping_mul(10)
                    .wrapping_add((bytes[at] - b'0') as u64);
                at += 1;
            }
            if at > digits_start {
                // The digits of the fraction that the exponent carries into
                // the whole number are applied first.
                if !exponent_negative && end_integer < end_fraction && bytes[end_integer] == b'.' {
                    let mut next = end_integer + 1;
                    while next < end_fraction && exponent > 0 {
                        value = value
                            .wrapping_mul(10)
                            .wrapping_add((bytes[next] - b'0') as u64);
                        next += 1;
                        exponent -= 1;
                    }
                }
                if exponent >= if exponent_negative { 20 } else { 64 } {
                    value = 0;
                } else if exponent != 0 {
                    let mut multiplier: u64 = 1;
                    let mut base: u64 = 10;
                    let mut left = exponent;
                    while left > 1 {
                        if left & 1 == 1 {
                            multiplier = multiplier.wrapping_mul(base);
                        }
                        left >>= 1;
                        base = base.wrapping_mul(base);
                    }
                    multiplier = multiplier.wrapping_mul(base);
                    if exponent_negative {
                        value /= multiplier;
                    } else {
                        value = value.wrapping_mul(multiplier);
                    }
                }
            }
        }
    }
    if negative {
        -(value as i64)
    } else {
        value as i64
    }
}

/// The number at the front of a text.
///
/// The rule is the one of `ATOF` of the binary, measured on 2026-11-09: a hex
/// number is read as a whole number, and a decimal number is the number at
/// the front of the text -- `"1e3"` is 1000 and `"5abc"` is 5.
pub(crate) fn text_to_double(text: &str) -> f64 {
    let bytes = text.as_bytes();
    let mut at = 0;
    while at < bytes.len() && (bytes[at] == b' ' || bytes[at] == b'\t') {
        at += 1;
    }
    let mut probe = at;
    if probe < bytes.len() && (bytes[probe] == b'-' || bytes[probe] == b'+') {
        probe += 1;
    }
    if is_hex_at(bytes, probe) {
        return text_to_int64(text) as f64;
    }
    let start = at;
    if at < bytes.len() && (bytes[at] == b'-' || bytes[at] == b'+') {
        at += 1;
    }
    let mut digit = false;
    while at < bytes.len() && bytes[at].is_ascii_digit() {
        at += 1;
        digit = true;
    }
    if at < bytes.len() && bytes[at] == b'.' {
        at += 1;
        while at < bytes.len() && bytes[at].is_ascii_digit() {
            at += 1;
            digit = true;
        }
    }
    if digit && at < bytes.len() && (bytes[at] == b'e' || bytes[at] == b'E') {
        let mut next = at + 1;
        if next < bytes.len() && (bytes[next] == b'+' || bytes[next] == b'-') {
            next += 1;
        }
        if next < bytes.len() && bytes[next].is_ascii_digit() {
            while next < bytes.len() && bytes[next].is_ascii_digit() {
                next += 1;
            }
            at = next;
        }
    }
    if !digit {
        return 0.0;
    }
    text[start..at].parse::<f64>().unwrap_or(0.0)
}

/// Whether the number a text holds is a whole number.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `Number("0x10")` is the
/// integer 16 and `Number("1.5")` is the float 1.5, so the shape the number
/// was written with is the shape of the answer.
pub(crate) fn text_holds_an_integer(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut at = 0;
    while at < bytes.len() && (bytes[at] == b' ' || bytes[at] == b'\t') {
        at += 1;
    }
    if at < bytes.len() && (bytes[at] == b'-' || bytes[at] == b'+') {
        at += 1;
    }
    if is_hex_at(bytes, at) {
        return true;
    }
    !bytes[at..]
        .iter()
        .any(|character| *character == b'.' || *character == b'e' || *character == b'E')
}

/// The number of the argument at this place, as the maths wants it.
///
/// A string that holds a number is a number; a string that holds anything
/// else is not one, and the runtime says so the way v2 says it:
/// "Parameter #1 of Abs requires a Number, but received a String."
fn number_argument(
    values: &[Value],
    index: usize,
    line: u32,
    name: &str,
) -> Result<f64, RuntimeError> {
    let value = values.get(index).cloned().unwrap_or(Value::Int(0));
    value.to_number_strict().map_err(|_| RuntimeError {
        message: crate::runtime::requires(index + 1, name, TypeName::Number, &value),
        line,
    })
}

/// The numbers of the arguments, as the maths wants them.
///
/// Every one of them has to be a number, and the message names the one
/// that was not.
fn numbers_argument(values: &[Value], line: u32, name: &str) -> Result<Vec<f64>, RuntimeError> {
    let mut numbers = Vec::with_capacity(values.len());
    for (index, value) in values.iter().enumerate() {
        numbers.push(value.to_number_strict().map_err(|_| RuntimeError {
            message: crate::runtime::requires(index + 1, name, TypeName::Number, value),
            line,
        })?);
    }
    Ok(numbers)
}

/// The whole number of the argument at this place.
fn integer_argument(values: &[Value], index: usize, line: u32) -> Result<i64, RuntimeError> {
    match values.get(index) {
        Some(Value::Int(number)) => Ok(*number),
        Some(other) => Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::Integer, other.type_name()),
            line,
        }),
        None => Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::Integer, TypeName::String),
            line,
        }),
    }
}

/// The sense of the case, the way v2 reads it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the parameter takes a
/// whole number -- 1 is case-sensitive and 0 is not -- or a text. The text
/// "On" or "1" is case-sensitive, "Off" or "0" is case-insensitive,
/// "Locale" looks at the letters through the locale, and "Logical" is the
/// logical order, which reads the run of digits of a name as a number
/// ("A2" comes before "A10"). A float is not a value the parameter takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CaseSense {
    Sensitive,
    Insensitive,
    Locale,
    Logical,
}

/// The sense of the case of one parameter.
fn case_sense(
    values: &[Value],
    index: usize,
    name: &str,
    line: u32,
) -> Result<CaseSense, RuntimeError> {
    let invalid = || RuntimeError {
        message: crate::runtime::invalid_parameter(index + 1, name),
        line,
    };
    match values.get(index) {
        None => Ok(CaseSense::Insensitive),
        Some(Value::Unset) => Ok(CaseSense::Insensitive),
        Some(Value::Int(1)) => Ok(CaseSense::Sensitive),
        Some(Value::Int(0)) => Ok(CaseSense::Insensitive),
        Some(Value::Text(text)) => case_sense_of_a_text(text).ok_or_else(invalid),
        Some(_) => Err(invalid()),
    }
}

/// The sense of the case that a text names, when it names one.
fn case_sense_of_a_text(text: &str) -> Option<CaseSense> {
    if text.eq_ignore_ascii_case("On") || text == "1" {
        Some(CaseSense::Sensitive)
    } else if text.eq_ignore_ascii_case("Off") || text == "0" {
        Some(CaseSense::Insensitive)
    } else if text.eq_ignore_ascii_case("Locale") {
        Some(CaseSense::Locale)
    } else if text.eq_ignore_ascii_case("Logical") {
        Some(CaseSense::Logical)
    } else {
        None
    }
}

/// How two texts stand to each other, in this sense of the case.
fn compare_texts(left: &str, right: &str, sense: CaseSense) -> Ordering {
    match sense {
        CaseSense::Sensitive => left.cmp(right),
        CaseSense::Logical => compare_logically(left, right),
        // The locale of the machine is not the tree's to look at, and the
        // letters of the two texts are compared without the case, which is
        // what the locale does for the letters a script sorts.
        CaseSense::Insensitive | CaseSense::Locale => {
            left.to_lowercase().cmp(&right.to_lowercase())
        }
    }
}

/// How two texts stand to each other in the logical order.
///
/// The run of digits of a name is a number there: "A2" comes before "A10".
/// The letters themselves are compared without the case.
fn compare_logically(left: &str, right: &str) -> Ordering {
    let left: Vec<char> = left.chars().collect();
    let right: Vec<char> = right.chars().collect();
    let mut at = 0usize;
    while at < left.len() && at < right.len() {
        let a = left[at];
        let b = right[at];
        if a.is_ascii_digit() && b.is_ascii_digit() {
            // The two runs of digits are the numbers they write, and the
            // shorter run is the smaller one when the numbers are equal.
            let mut end_a = at;
            while end_a < left.len() && left[end_a].is_ascii_digit() {
                end_a += 1;
            }
            let mut end_b = at;
            while end_b < right.len() && right[end_b].is_ascii_digit() {
                end_b += 1;
            }
            let number_a: &str = &left[at..end_a].iter().collect::<String>();
            let number_b: &str = &right[at..end_b].iter().collect::<String>();
            let trimmed_a = number_a.trim_start_matches('0');
            let trimmed_b = number_b.trim_start_matches('0');
            let order = trimmed_a
                .len()
                .cmp(&trimmed_b.len())
                .then_with(|| trimmed_a.cmp(trimmed_b))
                .then_with(|| number_a.len().cmp(&number_b.len()));
            if order != Ordering::Equal {
                return order;
            }
            at = end_a.min(end_b);
            continue;
        }
        let folded_a = a.to_lowercase().next().unwrap_or(a);
        let folded_b = b.to_lowercase().next().unwrap_or(b);
        if folded_a != folded_b {
            return folded_a.cmp(&folded_b);
        }
        at += 1;
    }
    left.len().cmp(&right.len())
}

/// Whether two letters are the same, with or without the case.
fn same_letter(left: char, right: char, sense: CaseSense) -> bool {
    match sense {
        CaseSense::Sensitive => left == right,
        // The locale is read as the case-insensitive compare of the tree.
        CaseSense::Insensitive | CaseSense::Locale | CaseSense::Logical => {
            left.to_lowercase().eq(right.to_lowercase())
        }
    }
}

/// Where the needle is in the haystack, without regard to the case.
///
/// The place is the one of a byte, and the text that is not there is
/// answered with nothing.
fn find_ignoring_case(haystack: &str, needle: &str) -> Option<usize> {
    let hay: Vec<char> = haystack.chars().collect();
    let pin: Vec<char> = needle.chars().collect();
    if pin.is_empty() || pin.len() > hay.len() {
        return None;
    }
    for at in 0..=(hay.len() - pin.len()) {
        let same = hay[at..at + pin.len()]
            .iter()
            .zip(pin.iter())
            .all(|(left, right)| same_letter(*left, *right, CaseSense::Insensitive));
        if same {
            return haystack.char_indices().nth(at).map(|(byte, _)| byte);
        }
    }
    None
}

/// Where the needle is in the text, in this sense of the case.
fn find_in_sense(text: &str, needle: &str, sense: CaseSense) -> Option<usize> {
    match sense {
        CaseSense::Sensitive => text.find(needle),
        // The locale is read as the case-insensitive compare of the tree.
        CaseSense::Insensitive | CaseSense::Locale | CaseSense::Logical => {
            find_ignoring_case(text, needle)
        }
    }
}

/// An error the desktop reported, with the line of the statement.
fn desktop_failure(message: String, line: u32) -> RuntimeError {
    RuntimeError { message, line }
}

// -- the numbers ----------------------------------------------------------------

/// `Abs`: the distance from zero.
///
/// An integer stays an integer, which is what AutoHotkey v2 does: the
/// handler keeps the whole number and only the rest becomes a float.
pub(crate) fn abs(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first().cloned().unwrap_or(Value::Int(0));
    // The number is checked first, so that the message of v2 comes
    // before the answer.
    number_argument(values, 0, line, "Abs")?;
    Ok(match number_value(&value) {
        Some(Value::Int(number)) => Value::Int(number.abs()),
        Some(Value::Float(number)) => Value::Float(number.abs()),
        _ => Value::Int(0),
    })
}

/// `Ceil` and `Floor`: the whole number above or below.
///
/// They share one handler, and the variant says which of the two it is.
pub(crate) fn round_to(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = if variant == 1 { "Ceil" } else { "Floor" };
    let number = number_argument(values, 0, line, name)?;
    let rounded = if variant == 1 {
        crate::runtime::ceil(number)
    } else {
        crate::runtime::floor(number)
    };
    Ok(Value::from_number(rounded))
}

/// `Max` and `Min`: the largest and the smallest of the numbers.
///
/// They share one handler, and the variant says which of the two it is.
pub(crate) fn extreme(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = if variant == 1 { "Max" } else { "Min" };
    let numbers = numbers_argument(values, line, name)?;
    let mut result = numbers.first().copied().unwrap_or(0.0);
    for number in numbers.iter().skip(1) {
        if (variant == 1 && *number > result) || (variant == 0 && *number < result) {
            result = *number;
        }
    }
    Ok(Value::from_number(result))
}

/// `Mod`: the remainder of a division.
///
/// The sign of the remainder is the sign of the dividend, and the answer
/// is a whole number when both of the arguments are.
pub(crate) fn modulo(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let dividend = values.first().cloned().unwrap_or(Value::Int(0));
    let divisor = values.get(1).cloned().unwrap_or(Value::Int(0));
    // v2 does not name the type that was wrong here: it says that the
    // parameters are invalid.
    let invalid = || RuntimeError {
        message: "Invalid parameter(s).".into(),
        line,
    };
    let left = number_value(&dividend).ok_or_else(invalid)?;
    let right = number_value(&divisor).ok_or_else(invalid)?;
    if right.to_number() == Some(0.0) {
        return Err(RuntimeError {
            message: "Divide by zero.".into(),
            line,
        });
    }
    Ok(match (left, right) {
        (Value::Int(left), Value::Int(right)) => Value::Int(left.wrapping_rem(right)),
        (left, right) => {
            let left = left.to_number().unwrap_or(0.0);
            let right = right.to_number().unwrap_or(0.0);
            Value::Float(left % right)
        }
    })
}

/// `Round`: the number to the number of decimals the caller asks for.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: with a positive number of
/// decimals the answer is a text of exactly that many digits after the point,
/// zeros kept -- `Round(2.567, 2)` is "2.57", `Round(2, 2)` is "2.00" and
/// `Round(1.005, 2)` is "1.00" -- and with the number omitted, zero or
/// negative it is a whole number. The number is scaled by the power of ten
/// and rounded away from zero on the half, and the two parameters are
/// numbers: a text that does not hold one is refused.
pub(crate) fn round_to_digits(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let decimals = match values.get(1) {
        None => 0i32,
        Some(value) => {
            if !is_numeric_value(value) {
                return Err(RuntimeError {
                    message: crate::runtime::requires(2, "Round", TypeName::Number, value),
                    line,
                });
            }
            token_to_int64(value) as i32
        }
    };
    let number = match values.first() {
        None => 0.0,
        Some(value) => {
            if !is_numeric_value(value) {
                return Err(RuntimeError {
                    message: crate::runtime::requires(1, "Round", TypeName::Number, value),
                    line,
                });
            }
            token_to_double(value)
        }
    };
    let multiplier = crate::runtime::powi(10.0, decimals);
    let rounded = if number >= 0.0 {
        crate::runtime::floor(number * multiplier + 0.5)
    } else {
        crate::runtime::ceil(number * multiplier - 0.5)
    } / multiplier;
    if decimals > 0 {
        // The text is a text of the given number of decimals, and the shape
        // of a text that large is not one a script writes: the answer is
        // refused rather than allocated, and the reason says the parameter.
        if decimals as usize > 100_000 {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(2, "Round"),
                line,
            });
        }
        let body = if rounded.is_nan() {
            if rounded.is_sign_negative() {
                "-nan(ind)".to_string()
            } else {
                "nan(ind)".to_string()
            }
        } else if rounded.is_infinite() {
            if rounded < 0.0 {
                "-inf".to_string()
            } else {
                "inf".to_string()
            }
        } else {
            format!("{:.*}", decimals as usize, rounded)
        };
        return Ok(Value::Text(body));
    }
    // The whole number the rounded value is, with the nudge of the binary
    // that keeps a value such as 1039.9999999999999 out of the answer.
    let nudged = rounded + if rounded > 0.0 { 0.2 } else { -0.2 };
    Ok(Value::Int(double_to_int64(nudged)))
}

/// `Sqrt`: the square root.
pub(crate) fn square_root(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_argument(values, 0, line, "Sqrt")?;
    if number < 0.0 {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "Sqrt"),
            line,
        });
    }
    // AutoHotkey v2 always answers a float here, even for a square.
    Ok(Value::Float(crate::runtime::sqrt(number)))
}

/// `Cos`, `Sin` and `Tan`: the trigonometry of a number.
///
/// They share one handler, and the variant says which of the three it is.
/// AutoHotkey v2 answers a float here, whatever went in.
pub(crate) fn trigonometry(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = match variant {
        0 => "Sin",
        1 => "Cos",
        _ => "Tan",
    };
    let number = number_argument(values, 0, line, name)?;
    let result = match variant {
        0 => crate::runtime::sin(number),
        1 => crate::runtime::cos(number),
        _ => crate::runtime::tan(number),
    };
    Ok(Value::Float(result))
}

/// `ASin`, `ACos` and `ATan`: the angle whose sine, cosine or tangent is
/// the number.
pub(crate) fn inverse_trigonometry(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = match variant {
        0 => "ASin",
        1 => "ACos",
        _ => "ATan",
    };
    let number = number_argument(values, 0, line, name)?;
    if variant != 2 && !(-1.0..=1.0).contains(&number) {
        // The sine and the cosine are not there outside the unit range,
        // and v2 says that the parameter is invalid.
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, name),
            line,
        });
    }
    let result = match variant {
        0 => crate::runtime::asin(number),
        1 => crate::runtime::acos(number),
        _ => crate::runtime::atan(number),
    };
    Ok(Value::Float(result))
}

/// `Exp`: e raised to the number.
pub(crate) fn exponential(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Float(crate::runtime::exp(number_argument(
        values, 0, line, "Exp",
    )?)))
}

/// `Ln` and `Log`: the logarithm of the number.
///
/// `Ln` is the natural one and `Log` the one of base ten.
pub(crate) fn logarithm(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = if variant == 1 { "Log" } else { "Ln" };
    let number = number_argument(values, 0, line, name)?;
    if number < 0.0 {
        // The logarithm of a negative number is not there, and v2 says
        // that the parameter is invalid.
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, name),
            line,
        });
    }
    let result = if variant == 0 {
        crate::runtime::ln(number)
    } else {
        crate::runtime::log10(number)
    };
    Ok(Value::Float(result))
}

/// The state of the generator of the random numbers.
///
/// The crate builds for a target that has no `std`, so there is no random
/// crate and no clock of its own: the generator is a small xorshift, and
/// the clock the host gave us is mixed into the seed, so that two runs do
/// not answer the same.
static RANDOM_STATE: AtomicU32 = AtomicU32::new(0);

/// The next number of the generator, as a whole number.
fn next_random(now_ms: u64) -> u32 {
    let mut state = RANDOM_STATE.load(AtomicOrder::Relaxed);
    if state == 0 {
        // The first call seeds the generator.
        state = (now_ms as u32) ^ 0x9E37_79B9 | 1;
    }
    state ^= state << 13;
    state ^= state >> 17;
    state ^= state << 5;
    RANDOM_STATE.store(state, AtomicOrder::Relaxed);
    state
}

/// The next number of the generator, between zero and one.
fn unit_random(now_ms: u64) -> f64 {
    next_random(now_ms) as f64 / (u32::MAX as f64 + 1.0)
}

/// `Random`: a number between the two the caller names.
///
/// Without arguments it is a number between zero and one; with one it is
/// a whole number below it; with two it is a whole number between them,
/// both ends counted.
pub(crate) fn random(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The seed a call of RandomSeed left is mixed into the entropy of the
    // machine, so that a seeded run of the same script asks the same numbers
    // of the machine.
    let now = rt.now_ms() ^ rt.the_seed_of_the_random();
    match values.len() {
        0 => Ok(Value::Float(unit_random(now))),
        1 => {
            let bound = number_argument(values, 0, line, "Random")?;
            if bound <= 0.0 {
                return Ok(Value::Int(0));
            }
            if values[0].type_name() == TypeName::Float {
                return Ok(Value::Float(unit_random(now) * bound));
            }
            Ok(Value::Int(next_random(now) as i64 % bound as i64))
        }
        _ => {
            let mut low = number_argument(values, 0, line, "Random")?;
            let mut high = number_argument(values, 1, line, "Random")?;
            if low > high {
                core::mem::swap(&mut low, &mut high);
            }
            let whole = values[0].type_name() != TypeName::Float
                && values[1].type_name() != TypeName::Float;
            if whole {
                let span = (high - low) as u64;
                let offset = if span == 0 {
                    0
                } else {
                    next_random(now) as u64 % (span + 1)
                };
                Ok(Value::Int((low as i64).saturating_add(offset as i64)))
            } else {
                Ok(Value::Float(low + unit_random(now) * (high - low)))
            }
        }
    }
}

/// `NumGet`: the number the bytes of a buffer hold.
///
/// v2 reads the memory of an address as well, and this runtime does
/// not: the source of a number is a buffer, and the bytes of a buffer
/// live in the runtime.
pub(crate) fn num_get(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let source = values.first().cloned().unwrap_or(Value::Int(0));
    if !matches!(source, Value::Object(_)) {
        // The memory of an address is not read here: the source of a
        // number is a buffer.
        let message = match source {
            Value::Int(_) => "this runtime does not read the memory of an address: the source of a number is a buffer.".to_string(),
            other => expected_type(TypeName::Object, other.type_name()),
        };
        return Err(RuntimeError { message, line });
    }
    // The offset is the second parameter when the type is the third.
    let (offset, type_name) = if values.len() > 2 {
        (integer_argument(values, 1, line)?, text_of(values, 2))
    } else {
        (0, text_of(values, 1))
    };
    let kind = crate::classes::buffer::number_type(&type_name).ok_or_else(|| RuntimeError {
        message: "the type of a number is one of UInt, Int, Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr.".into(),
        line,
    })?;
    match crate::classes::buffer::read_number(&source, offset, kind, line) {
        Ok(number) => Ok(number),
        Err(RuntimeFailure::Error(error)) => Err(error),
        Err(RuntimeFailure::Detailed(error, _)) => Err(error),
        Err(_) => Err(RuntimeError {
            message: "the buffer did not answer.".into(),
            line,
        }),
    }
}

/// `NumPut`: a number, into the bytes of a buffer.
///
/// The types and the numbers come in pairs, and the target and the
/// offset come after them: v2 writes the target last.
pub(crate) fn num_put(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The target is the last object of the arguments: the pairs come
    // before it, and the offset comes after it.
    let Some(index) = values
        .iter()
        .rposition(|value| matches!(value, Value::Object(_)))
    else {
        let message = match values.last() {
            Some(Value::Int(_)) => "this runtime does not write to the memory of an address: the target of a number is a buffer.".to_string(),
            Some(other) => expected_type(TypeName::Object, other.type_name()),
            None => expected_type(TypeName::Object, TypeName::String),
        };
        return Err(RuntimeError { message, line });
    };
    let pairs = &values[..index];
    if pairs.len() % 2 != 0 {
        return Err(RuntimeError {
            message: "the types and the numbers of a write come in pairs.".into(),
            line,
        });
    }
    if index + 2 < values.len() {
        return Err(RuntimeError {
            message: "a write takes the target and the offset after the pairs.".into(),
            line,
        });
    }
    let offset = match values.get(index + 1) {
        Some(_) => integer_argument(values, index + 1, line)?,
        None => 0,
    };
    let mut numbers = Vec::with_capacity(pairs.len() / 2);
    let mut at = 0;
    while at < pairs.len() {
        let kind = crate::classes::buffer::number_type(&text_of(pairs, at)).ok_or_else(|| RuntimeError {
            message: "the type of a number is one of UInt, Int, Int64, Short, UShort, Char, UChar, Double, Float, Ptr or UPtr.".into(),
            line,
        })?;
        let number = pairs[at + 1].clone();
        let number = number_value(&number).ok_or_else(|| RuntimeError {
            message: crate::runtime::requires(at + 2, "NumPut", TypeName::Number, &number),
            line,
        })?;
        numbers.push((kind, number));
        at += 2;
    }
    let target = &values[index];
    match crate::classes::buffer::write_numbers(target, offset, &numbers, line) {
        Ok(address) => Ok(Value::Int(address)),
        Err(RuntimeFailure::Error(error)) => Err(error),
        Err(RuntimeFailure::Detailed(error, _)) => Err(error),
        Err(_) => Err(RuntimeError {
            message: "the buffer did not answer.".into(),
            line,
        }),
    }
}

// -- the text -------------------------------------------------------------------

/// `Chr`: the character with that code point.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the parameter wants
/// a number and not a whole one, and the point that is not whole is the
/// one before it.
pub(crate) fn chr(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let code = number_argument(values, 0, line, "Chr")? as i64;
    // Measured on the binary of v2.0.19 on 2026-11-10: a surrogate code unit
    // is a text of its own -- `StrLen(Chr(0xD83D))` is one -- and a value
    // outside Unicode is an invalid parameter.
    if !(0..=0x10FFFF).contains(&code) {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "Chr"),
            line,
        });
    }
    // A surrogate is one code unit of its own, and every other code is the
    // character of it -- the pair of units of a character above the plane of
    // BMP is written by the text of it.
    let text = if (0xD800..=0xDFFF).contains(&code) {
        crate::text16::the_text_of(&[code as u16])
    } else {
        let Some(character) = char::from_u32(code as u32) else {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(1, "Chr"),
                line,
            });
        };
        character.to_string()
    };
    Ok(Value::Text(text))
}

/// `Format`: a pattern with the values in it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the pattern is the one of
/// the C library, with the placeholders of the dialect. A pattern that is one
/// argument is answered as the text of it, and the arguments a placeholder
/// names are read through their references, the way the binary reads them.
pub(crate) fn format(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(first) = values.first() else {
        return Ok(Value::Text(String::new()));
    };
    if matches!(first, Value::Object(_) | Value::List(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "Format", TypeName::String, first),
            line,
        });
    }
    // A reference reads through, the way the binary reads the variable it
    // points at.
    let mut arguments = Vec::with_capacity(values.len());
    for value in values {
        arguments.push(match value {
            Value::Reference(reference) => rt
                .read_reference(reference)
                .unwrap_or_else(|| Value::Text(String::new())),
            other => other.clone(),
        });
    }
    let pattern = match arguments.first() {
        Some(value @ (Value::Object(_) | Value::List(_))) => {
            return Err(RuntimeError {
                message: crate::runtime::requires(1, "Format", TypeName::String, value),
                line,
            });
        }
        Some(value) => value.to_text(),
        None => String::new(),
    };
    Ok(Value::Text(format_pattern(&pattern, &arguments, line)?))
}

/// `InStr`: where the needle is in the haystack.
///
/// The position counts from one, and it is zero when the needle is not
/// there at all. The third parameter is the sense of the case, the fourth is
/// the place where the search begins and the fifth is the occurrence the
/// caller wants.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, and read out of the
/// `BIF_InStr` of the source:
///
/// - a negative place is a place counted from the end -- `len + 1 + place`
///   -- and the search runs from the right, so `InStr("hello", "l", "On",
///   -2)` is 4; when the occurrence is not given with it, the search from
///   the right is the default;
/// - a negative occurrence is the search from the right, and the fourth
///   parameter then limits the haystack to the place it names;
/// - the matches of a search from the left do not overlap: after a match the
///   search goes on after it, so `InStr("aaaa", "aa", "On", 1, 2)` is 3 and
///   not 2;
/// - the place zero and the occurrence zero are refused, and a place or an
///   occurrence that is not a number is refused with the kind it got.
pub(crate) fn in_str(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let haystack: Vec<char> = text_of(values, 0).chars().collect();
    let needle: Vec<char> = text_of(values, 1).chars().collect();
    if needle.is_empty() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(2, "InStr"),
            line,
        });
    }
    let sense = case_sense(values, 2, "InStr", line)?;
    // The logical order is not a sense of the case that a search can use,
    // and the binary refuses it here.
    if sense == CaseSense::Logical {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(3, "InStr"),
            line,
        });
    }
    let start_given = values.get(3).is_some();
    let mut offset: i64 = 1;
    if let Some(value) = values.get(3) {
        if !is_numeric_value(value) {
            return Err(RuntimeError {
                message: crate::runtime::requires(4, "InStr", TypeName::Number, value),
                line,
            });
        }
        offset = token_to_int64(value);
        if offset == 0 {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(4, "InStr"),
                line,
            });
        }
    }
    let mut occurrence: i64 = 1;
    if let Some(value) = values.get(4) {
        if !is_numeric_value(value) {
            return Err(RuntimeError {
                message: crate::runtime::requires(5, "InStr", TypeName::Number, value),
                line,
            });
        }
        // The binary reads the occurrence through an `int`.
        occurrence = token_to_int64(value) as i32 as i64;
        if occurrence == 0 {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(5, "InStr"),
                line,
            });
        }
    }
    let length = haystack.len() as i64;
    if offset < 0 {
        if values.get(4).is_none() {
            // A place from the right with no occurrence is the search from
            // the right.
            occurrence = -1;
        }
        // A place at the very front of a 64-bit integer would run over the
        // edge of it: the sum is taken to the edge, and the place is the
        // first character after that.
        offset = offset.saturating_add(length + 1);
    }
    if occurrence > 0 {
        offset = offset.saturating_sub(1);
    }
    if offset < 0 {
        offset = 0;
    } else if offset > length {
        offset = length;
    }
    if occurrence < 0 {
        // The search from the right, over the part of the haystack that the
        // fourth parameter leaves.
        let end = if start_given {
            offset as usize
        } else {
            haystack.len()
        };
        let wanted = (-occurrence) as u64;
        let mut found = 0u64;
        if needle.len() <= end {
            for at in (0..=(end - needle.len())).rev() {
                if haystack[at..at + needle.len()]
                    .iter()
                    .zip(needle.iter())
                    .all(|(left, right)| same_letter(*left, *right, sense))
                {
                    found += 1;
                    if found == wanted {
                        return Ok(Value::Int(at as i64 + 1));
                    }
                }
            }
        }
        return Ok(Value::Int(0));
    }
    // The search from the left: after a match it goes on after it.
    let mut at = offset as usize;
    let mut count: i64 = 1;
    while at + needle.len() <= haystack.len() {
        if haystack[at..at + needle.len()]
            .iter()
            .zip(needle.iter())
            .all(|(left, right)| same_letter(*left, *right, sense))
        {
            if count == occurrence {
                return Ok(Value::Int(at as i64 + 1));
            }
            count += 1;
            at += needle.len();
        } else {
            at += 1;
        }
    }
    Ok(Value::Int(0))
}

/// `Ord`: the code point of the first character.
///
/// An empty text has no character, and the code point of it is zero.
pub(crate) fn ord(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = text_of(values, 0);
    // Measured on the binary of v2.0.19 on 2026-11-10: the code of the first
    // character -- `Ord(Chr(0x1F600))` is 0x1F600 -- and the code unit of a
    // lone surrogate -- `Ord(SubStr(Chr(0x1F600), 2))` is 0xDE00. A text of no
    // character has the code zero.
    let code = match text.chars().next() {
        None => 0,
        Some(character) => match crate::text16::the_surrogate_of_a_character(character) {
            Some(unit) => unit as i64,
            None => character as u32 as i64,
        },
    };
    Ok(Value::Int(code))
}

/// The options of a `Sort`, read out of the second parameter.
struct SortOptions {
    /// The character that ends an item: a linefeed unless `Dx` says another.
    delimiter: char,
    /// How the letters are compared.
    sense: CaseSense,
    /// `N`: each item is read as a number.
    numeric: bool,
    /// `R`: the order is reversed.
    reverse: bool,
    /// `Pn`: the compare begins this many characters into each item.
    column: usize,
    /// `Z`: the blank item after a trailing delimiter is an item of its own.
    blank_trailing: bool,
    /// `\`: the name after the last backslash is what is compared.
    naked_filename: bool,
    /// `Random`: the items are shuffled.
    random: bool,
    /// `U`: the duplicates that end up next to each other are removed.
    unique: bool,
}

/// The options of a `Sort`, read out of its second parameter.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, and read out of the
/// `BIF_Sort` of the source: the letters are read without the case, a letter
/// the binary does not know is ignored, and the `Random` of `R` wins over
/// the reverse order.
fn sort_options(text: &str) -> SortOptions {
    let chars: Vec<char> = text.chars().collect();
    let mut options = SortOptions {
        delimiter: '\n',
        sense: CaseSense::Insensitive,
        numeric: false,
        reverse: false,
        column: 0,
        blank_trailing: false,
        naked_filename: false,
        random: false,
        unique: false,
    };
    let mut at = 0usize;
    while at < chars.len() {
        match chars[at].to_ascii_uppercase() {
            'C' => {
                if chars.get(at + 1).map(|c| c.to_ascii_uppercase()) == Some('L') {
                    let rest: String = chars[at + 2..].iter().take(6).collect();
                    if rest.eq_ignore_ascii_case("ogical") {
                        options.sense = CaseSense::Logical;
                        at += 8;
                    } else {
                        let rest: String = chars[at + 2..].iter().take(5).collect();
                        if rest.eq_ignore_ascii_case("ocale") {
                            at += 7;
                        } else {
                            at += 2;
                        }
                        options.sense = CaseSense::Locale;
                    }
                } else {
                    let rest: String = chars[at + 1..].iter().take(3).collect();
                    if rest.eq_ignore_ascii_case("Off") {
                        options.sense = CaseSense::Insensitive;
                        at += 4;
                    } else if chars.get(at + 1) == Some(&'0') {
                        options.sense = CaseSense::Insensitive;
                        at += 1;
                    } else {
                        let rest: String = chars[at + 1..].iter().take(2).collect();
                        if rest.eq_ignore_ascii_case("On") {
                            at += 3;
                        } else {
                            at += 1;
                        }
                        options.sense = CaseSense::Sensitive;
                    }
                }
            }
            'D' => {
                // The character after the `D` is the delimiter itself.
                if at + 1 < chars.len() {
                    options.delimiter = chars[at + 1];
                    at += 2;
                } else {
                    at += 1;
                }
            }
            'N' => {
                options.numeric = true;
                at += 1;
            }
            'P' => {
                // The number after the `P` is the column, and a number that
                // is not one starts at the first character.
                let mut next = at + 1;
                while next < chars.len() && chars[next].is_ascii_whitespace() {
                    next += 1;
                }
                let negative = next < chars.len() && chars[next] == '-';
                if negative || (next < chars.len() && chars[next] == '+') {
                    next += 1;
                }
                let mut value: i64 = 0;
                while next < chars.len() && chars[next].is_ascii_digit() {
                    value = value
                        .saturating_mul(10)
                        .saturating_add((chars[next] as u8 - b'0') as i64);
                    next += 1;
                }
                if negative {
                    value = -value;
                }
                options.column = if value < 1 { 1 } else { value as usize } - 1;
                at += 1;
            }
            'R' => {
                let rest: String = chars[at..].iter().take(6).collect();
                if rest.eq_ignore_ascii_case("Random") {
                    options.random = true;
                    at += 6;
                } else {
                    options.reverse = true;
                    at += 1;
                }
            }
            'U' => {
                options.unique = true;
                at += 1;
            }
            'Z' => {
                options.blank_trailing = true;
                at += 1;
            }
            '\\' => {
                options.naked_filename = true;
                at += 1;
            }
            _ => at += 1,
        }
    }
    options
}

/// The key of an item: the part of it that the options compare.
fn sort_key(item: &str, options: &SortOptions) -> String {
    if options.column == 0 {
        return item.to_string();
    }
    item.chars().skip(options.column).collect()
}

/// The name of an item after the last backslash.
fn naked_filename(item: &str) -> &str {
    match item.rfind('\\') {
        Some(at) => &item[at + 1..],
        None => item,
    }
}

/// `Sort`: the items of a text in order.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, and read out of the
/// `BIF_Sort` of the source:
///
/// - the second parameter is the options, read letter by letter: `C`, `C1`
///   and `COn` take the case into the sort, `C0`, `COff` and the default
///   leave it out, `CL`/`CLocale` look at the letters through the locale and
///   `CLogical` reads a run of digits as a number; `Dx` sets the delimiter to
///   the character after it; `N` reads each item as a number; `Pn` starts the
///   compare at the nth character; `R` reverses the order; `Random` shuffles;
///   `U` removes the adjacent duplicates; `Z` counts the blank item after a
///   trailing delimiter; `\` compares the name after the last backslash. A
///   letter the binary does not know is ignored.
/// - the third parameter is a callback, called with the two items and the
///   offset of the second from the first in the original text; the sign of
///   the number it answers orders the two, and zero leaves them in place.
/// - the first parameter is a text; an array is refused with the reason, and
///   so is a value that is not a function when the third one is given.
pub(crate) fn sort(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let contents = sort_text(values, 0, line)?;
    let options = sort_options(&sort_text(values, 1, line)?);
    let callback = match values.get(2) {
        None => None,
        Some(value @ (Value::Object(_) | Value::List(_) | Value::Reference(_))) => {
            Some(value.clone())
        }
        Some(_) => {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(3, "Sort"),
                line,
            });
        }
    };
    if contents.is_empty() {
        return Ok(Value::Text(String::new()));
    }
    // A trailing delimiter is the terminator of the last item unless `Z`
    // says that the blank item after it is an item of its own.
    let mut working = contents.clone();
    let mut terminate_last = false;
    let mut trailing_crlf = false;
    if !options.blank_trailing && working.ends_with(options.delimiter) {
        terminate_last = true;
    } else if options.delimiter == '\n' {
        // The lines of a CRLF list are sorted as if the delimiter were the
        // linefeed alone, and the carriage return stays at the end of the
        // item: measured on 2026-11-09, "B`r`nA" sorts to "A`r`nB".
        let chars: Vec<char> = working.chars().collect();
        if let Some(at) = chars.iter().position(|c| *c == '\n') {
            if at > 0 && chars[at - 1] == '\r' {
                trailing_crlf = true;
                terminate_last = true;
                working.push_str("\r\n");
            }
        }
    }
    let mut items: Vec<String> = working
        .split(options.delimiter)
        .map(|item| item.to_string())
        .collect();
    if terminate_last {
        // The blank item that the last delimiter makes is not an item.
        items.pop();
    }
    if items.len() == 1 {
        return Ok(Value::Text(contents));
    }
    // Where each item begins in the text being sorted: the callback is told
    // the distance between the two items it compares.
    let mut positions: Vec<usize> = Vec::with_capacity(items.len());
    let mut position = 0usize;
    for item in &items {
        positions.push(position);
        position += item.chars().count() + 1;
    }
    let keys: Vec<String> = items.iter().map(|item| sort_key(item, &options)).collect();
    let mut order: Vec<usize> = (0..items.len()).collect();
    let mut failure: Option<RuntimeError> = None;
    if let Some(callback) = &callback {
        // A function is called as a value, and any other object is asked for
        // its `Call` method: measured on the binary of v2.0.19 on 2026-11-09,
        // an array as the third parameter of a `Sort` answers "This value of
        // type "Array" has no method named "Call".".
        let is_a_function = match callback {
            Value::Object(object) => {
                let class = object.borrow().class.to_lowercase();
                class == "func" || class == "boundfunc" || class == "closure"
            }
            _ => false,
        };
        let no_method = |value: &Value| RuntimeError {
            message: format!(
                "This value of type \"{}\" has no method named \"Call\".",
                value.the_kind()
            ),
            line,
        };
        // The callback is called with the two items and the distance
        // between them, and a zero leaves them as they are.
        order.sort_by(|&left, &right| {
            if failure.is_some() {
                return Ordering::Equal;
            }
            let offset = positions[right] as i64 - positions[left] as i64;
            let arguments = [
                Value::Text(items[left].clone()),
                Value::Text(items[right].clone()),
                Value::Int(offset),
            ];
            let called = if is_a_function {
                match crate::classes::func::call_the_value(callback, &arguments, rt, line) {
                    Some(Ok(value)) => Ok(value),
                    Some(Err(error)) => Err(the_failure_in_one(error, line)),
                    None => Err(no_method(callback)),
                }
            } else {
                match rt.call_a_method_of_an_object(callback, "Call", &arguments, line) {
                    Ok(value) => Ok(value),
                    Err(error) => Err(the_failure_in_one(error, line)),
                }
            };
            match called {
                Ok(value) => match token_to_int64(&value) {
                    number if number < 0 => Ordering::Less,
                    number if number > 0 => Ordering::Greater,
                    _ => Ordering::Equal,
                },
                Err(error) => {
                    failure = Some(error);
                    Ordering::Equal
                }
            }
        });
    } else if options.random {
        // A shuffle: the items are put in a random order, and the options
        // of `N`, `C` and `CL` are still what the duplicates are read by.
        // The seed a call of RandomSeed left is mixed into the entropy of the
        // machine, so that a seeded run of the same script asks the same numbers
        // of the machine.
        let now = rt.now_ms() ^ rt.the_seed_of_the_random();
        for at in (1..order.len()).rev() {
            let pick = (unit_random(now) * (at as f64 + 1.0)) as usize;
            order.swap(at, pick.min(at));
        }
    } else {
        order.sort_by(|&left, &right| {
            let order = if options.naked_filename {
                compare_texts(
                    naked_filename(&items[left]),
                    naked_filename(&items[right]),
                    options.sense,
                )
            } else if options.numeric {
                let a = text_to_double(&keys[left]);
                let b = text_to_double(&keys[right]);
                // A tie keeps the two in the order they came in.
                a.partial_cmp(&b).unwrap_or(Ordering::Equal)
            } else {
                compare_texts(&keys[left], &keys[right], options.sense)
            };
            // A value that compares equal keeps the place it had, and the
            // reverse order turns that place around too.
            let order = if order == Ordering::Equal {
                left.cmp(&right)
            } else {
                order
            };
            if options.reverse {
                order.reverse()
            } else {
                order
            }
        });
    }
    if let Some(failure) = failure {
        return Err(failure);
    }
    // The duplicates that ended up next to each other are removed, and the
    // rule of a duplicate is the rule of the sort that made them adjacent.
    let mut kept: Vec<usize> = Vec::with_capacity(order.len());
    for &index in &order {
        if options.unique {
            if let Some(&previous) = kept.last() {
                if sort_duplicates(&items[previous], &items[index], &options) {
                    continue;
                }
            }
        }
        kept.push(index);
    }
    let mut out = String::with_capacity(contents.len());
    for (at, &index) in kept.iter().enumerate() {
        out.push_str(&items[index]);
        if at + 1 < kept.len() || terminate_last {
            out.push(options.delimiter);
        }
    }
    if trailing_crlf && out.ends_with("\r\n") {
        out.truncate(out.len() - 2);
    }
    Ok(Value::Text(out))
}

/// The text of one parameter of a `Sort`.
fn sort_text(values: &[Value], index: usize, line: u32) -> Result<String, RuntimeError> {
    match values.get(index) {
        None => Ok(String::new()),
        // Measured on the binary of v2.0.19 on 2026-11-10: the absent value is
        // no argument, and the text of no argument is the empty text.
        Some(Value::Unset) => Ok(String::new()),
        Some(value @ (Value::Object(_) | Value::List(_) | Value::Reference(_))) => {
            Err(RuntimeError {
                message: crate::runtime::requires(index + 1, "Sort", TypeName::String, value),
                line,
            })
        }
        Some(value) => Ok(value.to_text()),
    }
}

/// Whether two items of a sort are a duplicate of each other.
///
/// The rule is the one of the binary: a numeric sort compares the numbers,
/// the logical order compares the names in that order, and the other sorts
/// compare the two items with their sense of the case.
fn sort_duplicates(left: &str, right: &str, options: &SortOptions) -> bool {
    if options.numeric && options.column == 0 {
        text_to_double(left) == text_to_double(right)
    } else if options.sense == CaseSense::Logical {
        compare_logically(left, right) == Ordering::Equal
    } else {
        compare_texts(left, right, options.sense) == Ordering::Equal
    }
}

/// The failure of a call, as the failure of the built-in that made it.
///
/// The details of the failure are not carried here: a built-in answers with
/// the message and the line, and the runtime names the built-in in the
/// `What`.
fn the_failure_in_one(error: RuntimeFailure, line: u32) -> RuntimeError {
    match error {
        RuntimeFailure::Error(error)
        | RuntimeFailure::Detailed(error, _)
        | RuntimeFailure::Fatal(error) => error,
        RuntimeFailure::Thrown(value) => RuntimeError {
            message: value.to_text(),
            line,
        },
        _ => RuntimeError {
            message: "the sort stopped the run.".to_string(),
            line,
        },
    }
}

/// `StrCompare`: how two texts stand to each other.
///
/// The answer is -1, 0 or 1, and the case sense says whether the letters
/// are taken as they are.
pub(crate) fn str_compare(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let left = text_of(values, 0);
    let right = text_of(values, 1);
    let order = compare_texts(&left, &right, case_sense(values, 2, "StrCompare", line)?);
    Ok(Value::Int(match order {
        Ordering::Less => -1,
        Ordering::Equal => 0,
        Ordering::Greater => 1,
    }))
}

/// `StrLen`: how many characters the text has.
pub(crate) fn str_len(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // Measured on the binary of v2.0.19 on 2026-11-10: the length is counted in
    // the code units of UTF-16, so `StrLen(Chr(0x1F600))` is two.
    Ok(Value::Int(
        crate::text16::the_number_of_the_code_units(&text_of(values, 0)) as i64,
    ))
}

/// `StrLower` and `StrUpper`: the text in the other case.
///
/// They share one handler, and the variant says which of the two it is.
pub(crate) fn change_case(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let text = text_of(values, 0);
    Ok(Value::Text(if variant == 1 {
        text.to_uppercase()
    } else {
        text.to_lowercase()
    }))
}

/// `StrReplace`: the text with one part of it swapped for another.
///
/// v2 writes the number of the swaps into the variable of the caller, and
/// the limit says how many of them are swapped: none of them means all of
/// them. The case sense says whether the letters are taken as they are,
/// and it is off when the caller does not say.
pub(crate) fn str_replace(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let haystack = text_argument("StrReplace", values, 0, line)?;
    let needle = text_argument("StrReplace", values, 1, line)?;
    let replacement = text_argument("StrReplace", values, 2, line)?;
    // Measured on the binary of v2.0.19 on 2026-11-10: the fourth parameter of
    // the call is the sense of the case, the fifth is the variable that takes
    // the number of the swaps, and the sixth is the limit. An argument that is
    // the absent value is no argument: the case is the one of the dialect, the
    // number of the swaps is not written, and the limit is all of them.
    let sense = match values.get(3) {
        Some(Value::Unset) | None => CaseSense::Insensitive,
        Some(_) => case_sense(values, 3, "StrReplace", line)?,
    };
    // The logical order is not a sense of the case that a replacement can
    // use, and the binary refuses it here.
    if sense == CaseSense::Logical {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(4, "StrReplace"),
            line,
        });
    }
    let limit = match values.get(5) {
        Some(Value::Unset) | None => 0,
        Some(_) => number_of(values, 5) as i64,
    };
    let mut out = String::with_capacity(haystack.len());
    let mut rest = haystack.as_str();
    let mut replaced = 0i64;
    // Measured on the binary of v2.0.19 on 2026-10-31: a needle that is
    // empty changes nothing, and the text comes back as it is.
    while !needle.is_empty() {
        let found = find_in_sense(rest, &needle, sense);
        let Some(at) = found else {
            break;
        };
        out.push_str(&rest[..at]);
        out.push_str(&replacement);
        rest = &rest[at + needle.len()..];
        replaced += 1;
        if limit > 0 && replaced >= limit {
            break;
        }
    }
    out.push_str(rest);
    // The number of the swaps goes into the variable of the caller.
    if let Some(value) = values.get(4) {
        if matches!(value, Value::Unset) {
            return Ok(Value::Text(out));
        }
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    5,
                    "StrReplace",
                    "a variable reference",
                    value,
                ),
                line,
            });
        }
        rt.write_reference(value, Value::Int(replaced));
    }
    Ok(Value::Text(out))
}

/// The encodings the string functions of v2 name.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `UTF-8`, `UTF-16` and
/// `CP0` are the names it takes, the case does not matter, and the two
/// names that are spelled without the hyphen -- `UTF8`, `UTF16` -- are not
/// names. The encoding of a call that does not name one is `UTF-16`, the
/// text of the machine.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TextEncoding {
    Utf8,
    Utf16,
    /// The code page of the machine. The tree is UTF-8 everywhere, and the
    /// code page of the box is not asked: the letters of ASCII are the
    /// same bytes in both, and the others are the ones the tree can hold.
    Cp0,
}

/// The encoding a string function was given.
fn the_encoding_of(name: Option<&Value>) -> Result<TextEncoding, String> {
    match name {
        None => Ok(TextEncoding::Utf16),
        Some(Value::Text(text)) => match text.to_ascii_lowercase().as_str() {
            "utf-8" => Ok(TextEncoding::Utf8),
            "utf-16" => Ok(TextEncoding::Utf16),
            "cp0" => Ok(TextEncoding::Cp0),
            _ => Err("Invalid Encoding.".to_string()),
        },
        Some(_) => Err("Invalid Encoding.".to_string()),
    }
}

/// The bytes of a text, in an encoding.
fn the_bytes_of(text: &str, encoding: TextEncoding) -> Vec<u8> {
    match encoding {
        TextEncoding::Utf8 | TextEncoding::Cp0 => text.as_bytes().to_vec(),
        TextEncoding::Utf16 => {
            let mut bytes: Vec<u8> = Vec::with_capacity(text.len() * 2);
            for unit in text.encode_utf16() {
                bytes.extend_from_slice(&unit.to_le_bytes());
            }
            bytes
        }
    }
}

/// The terminator of an encoding: the bytes that end a text in it.
fn the_terminator_of(encoding: TextEncoding) -> Vec<u8> {
    match encoding {
        TextEncoding::Utf8 | TextEncoding::Cp0 => vec![0],
        TextEncoding::Utf16 => vec![0, 0],
    }
}

/// The text of some bytes, in an encoding, up to a terminator or a length.
///
/// The length is the number of the units of the encoding: the bytes of
/// `UTF-8` and the sixteen-bit units of `UTF-16`. Measured on the binary of
/// v2.0.19 on 2026-11-09: `StrGet(buf, 2, "UTF-8")` answers the first two
/// characters of a text of ASCII.
fn the_text_of(bytes: &[u8], encoding: TextEncoding, length: Option<usize>) -> String {
    match encoding {
        TextEncoding::Utf8 | TextEncoding::Cp0 => {
            let end = bytes
                .iter()
                .position(|byte| *byte == 0)
                .unwrap_or(bytes.len());
            let end = length.map(|length| end.min(length)).unwrap_or(end);
            String::from_utf8_lossy(&bytes[..end]).into_owned()
        }
        TextEncoding::Utf16 => {
            let mut units: Vec<u16> = Vec::new();
            let mut at = 0;
            while at + 1 < bytes.len() {
                let unit = u16::from_le_bytes([bytes[at], bytes[at + 1]]);
                if unit == 0 {
                    break;
                }
                units.push(unit);
                at += 2;
                if let Some(length) = length {
                    if units.len() >= length {
                        break;
                    }
                }
            }
            String::from_utf16_lossy(&units)
        }
    }
}

/// `StrPtr`: the address of the text of a string.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the parameter is a
/// text, and nothing else -- a number and an object are refused with the
/// kind they are -- and the answer is the address of the buffer of the
/// text, which is a number above zero and the same number for the same
/// variable read twice. The tree keeps the addresses of the texts that a
/// script asks for; the same text answers the same address.
pub(crate) fn str_ptr(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = match values.first() {
        Some(Value::Text(text)) => text.clone(),
        Some(value) => {
            return Err(RuntimeError {
                message: crate::runtime::expected_type(TypeName::String, value.type_name()),
                line,
            });
        }
        None => String::new(),
    };
    Ok(Value::Int(rt.the_address_of_a_text(&text)))
}

/// `StrGet`: the text at an address, or the text of a buffer.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the source is a buffer
/// or an address, and a text there is refused with "Parameter #1 invalid.";
/// the length and the encoding are the second and the third parameters,
/// and a second parameter that is a text is the encoding, with the length
/// left to the terminator. The encoding of a name the binary does not know
/// is refused with "Invalid Encoding.".
pub(crate) fn str_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(source) = values.first() else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "StrGet"),
            line,
        });
    };
    let bytes: Vec<u8> = match source {
        // The bytes of a buffer are the bytes of the buffer.
        Value::Object(_) => {
            crate::classes::buffer::raw_bytes(source, line).map_err(|failure| RuntimeError {
                message: the_message_of(failure),
                line,
            })?
        }
        // The address of a text of the script: the text is a UTF-16 text,
        // and the reading of it with another encoding reads the bytes of
        // it, the way the binary reads the buffer of the variable.
        Value::Int(address) => match rt.the_text_at_an_address(*address) {
            Some(text) => the_bytes_of(&text, TextEncoding::Utf16),
            None => {
                return Err(RuntimeError {
                    message: crate::runtime::invalid_parameter(1, "StrGet"),
                    line,
                });
            }
        },
        Value::Text(_) => {
            return Err(RuntimeError {
                message: "Parameter #1 invalid.".to_string(),
                line,
            });
        }
        _ => {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(1, "StrGet"),
                line,
            });
        }
    };
    // The second parameter is the length when it is a number, and the
    // encoding when it is a text; the third one is the encoding.
    let (length, encoding_name) = match values.get(1) {
        Some(value) if is_numeric_value(value) => {
            (Some(token_to_int64(value).max(0) as usize), values.get(2))
        }
        Some(value) => (None, Some(value)),
        None => (None, None),
    };
    let encoding =
        the_encoding_of(encoding_name).map_err(|message| RuntimeError { message, line })?;
    Ok(Value::Text(the_text_of(&bytes, encoding, length)))
}

/// `StrPut`: write a text into a buffer, or say how many bytes it needs.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the parameters are the
/// text, the target, the encoding and the length; a second parameter that
/// is a text is the encoding, with the target left out -- the order of the
/// v1 -- and a target that is not a buffer is refused with "Parameter #2 of
/// StrPut is invalid.". Without a target the answer is the number of the
/// bytes the text needs, terminator included. The third parameter may be a
/// number: it is the size the caller says the target has, in characters,
/// and a text that does not fit in it is refused with "Invalid Length.".
pub(crate) fn str_put(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let _ = &rt;
    let text = match values.first() {
        Some(Value::Text(text)) => text.clone(),
        Some(value @ (Value::Object(_) | Value::List(_) | Value::Reference(_))) => {
            return Err(RuntimeError {
                message: crate::runtime::requires(1, "StrPut", TypeName::String, value),
                line,
            });
        }
        Some(value) => value.to_text(),
        None => String::new(),
    };
    // The parameters, in the two orders that the binary takes.
    let (target, encoding_name, length_name) = match values.get(1) {
        None => (None, values.get(2), values.get(3)),
        Some(value @ Value::Object(_)) => (Some(value), values.get(2), values.get(3)),
        Some(value @ Value::Text(_)) => (None, Some(value), values.get(2)),
        Some(_) => {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(2, "StrPut"),
                line,
            });
        }
    };
    // A length with no target is not a use of v2.
    if target.is_none() && length_name.is_some() {
        return Err(RuntimeError {
            message: "Invalid parameter(s).".to_string(),
            line,
        });
    }
    // The size the caller says the target has, when the third parameter is
    // a number instead of the name of an encoding.
    let mut capacity: Option<i64> = None;
    let encoding = match encoding_name {
        Some(value) if is_numeric_value(value) => {
            capacity = Some(token_to_int64(value));
            TextEncoding::Utf16
        }
        other => the_encoding_of(other).map_err(|message| RuntimeError { message, line })?,
    };
    let characters = text.chars().count() as i64;
    let mut bytes = the_bytes_of(&text, encoding);
    let mut terminator = true;
    if let Some(capacity) = capacity {
        if capacity < 0 || capacity < characters {
            return Err(RuntimeError {
                message: "Invalid Length.".to_string(),
                line,
            });
        }
        // A text that fits exactly fills the buffer it was told about, and
        // there is no room for the terminator: that is the answer of the
        // binary, which counts the bytes it wrote.
        if capacity == characters {
            terminator = false;
        }
    }
    if terminator {
        bytes.extend_from_slice(&the_terminator_of(encoding));
    }
    let Some(target) = target else {
        return Ok(Value::Int(bytes.len() as i64));
    };
    // The target is a buffer, and it has to hold the text.
    let size = match crate::classes::buffer::size_of(target, line) {
        Ok(size) => size,
        Err(_) => {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(2, "StrPut"),
                line,
            });
        }
    };
    if bytes.len() as i64 > size {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(2, "StrPut"),
            line,
        });
    }
    match crate::classes::buffer::fill(target, &bytes, line) {
        Ok(_) => Ok(Value::Int(bytes.len() as i64)),
        Err(_) => Err(RuntimeError {
            message: crate::runtime::invalid_parameter(2, "StrPut"),
            line,
        }),
    }
}

/// The message of a failure, for a handler that has no room for the whole
/// of it.
fn the_message_of(failure: crate::runtime::RuntimeFailure) -> String {
    match failure {
        crate::runtime::RuntimeFailure::Error(error) => error.message,
        crate::runtime::RuntimeFailure::Detailed(error, _) => error.message,
        _ => "the runtime cannot answer that.".to_string(),
    }
}

/// `VarSetStrCapacity`: the room of the string of a variable.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, with the source of the
/// binary read beside the measurements:
///
/// - with a capacity the variable is emptied -- the buffer of it is made
///   again, and the text in it is the text of nothing -- and the answer is
///   the capacity of the variable, which is the one asked for when it is
///   greater than the one the variable had;
/// - with zero the buffer is freed and the text is emptied, and the answer
///   is the capacity the variable had: a text of the tree has no buffer to
///   give back, and the capacity of it stays the one of the size class;
/// - with nothing the variable is not touched, and the answer is the
///   capacity it has; a variable that holds a number or an object is
///   refused with the kind it holds, because a capacity is a capacity of a
///   text;
/// - with minus one the answer is the length of the text, and not the
///   capacity of it;
/// - a capacity that is negative and not minus one is an invalid
///   parameter, and so is one that can not be a number of characters.
pub(crate) fn var_set_str_capacity(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(value) = values.first() else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "VarSetStrCapacity"),
            line,
        });
    };
    let Value::Reference(reference) = value else {
        return Err(RuntimeError {
            message: crate::runtime::wants_a_reference(
                1,
                "VarSetStrCapacity",
                "a variable reference",
                value,
            ),
            line,
        });
    };
    let Some(capacity) = values.get(1) else {
        // The capacity that the variable has, and the refusal of a value
        // that is not a text at all.
        return match rt.read_reference(reference) {
            Some(Value::Text(_)) | None => Ok(Value::Int(rt.string_capacity(reference))),
            Some(other) => Err(RuntimeError {
                message: crate::runtime::expected_type(TypeName::String, other.type_name()),
                line,
            }),
        };
    };
    // The number is read the way the binary reads it: a value of any kind
    // is a number, and the text of it is parsed.
    let requested = token_to_int64(capacity);
    if requested == -1 {
        // The one capacity that answers the length of the text.
        let length = rt
            .read_reference(reference)
            .map(|value| value.to_text().chars().count() as i64)
            .unwrap_or(0);
        return Ok(Value::Int(length));
    }
    if !(0..=i64::MAX / 2).contains(&requested) {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(2, "VarSetStrCapacity"),
            line,
        });
    }
    let current = rt.string_capacity(reference);
    let asked_for = rt.keeps_a_string_capacity(reference);
    // The variable is emptied by the call, whether the capacity grows or
    // not: the buffer that holds it is made again.
    rt.write_reference(value, Value::Text(String::new()));
    let capacity = if requested > 0 {
        rt.set_string_capacity(reference, requested.max(current));
        requested.max(current)
    } else if asked_for {
        // The free of the binary gives a buffer that was asked for back,
        // and leaves the simple allocation of a text alone.
        rt.forget_a_string_capacity(reference);
        0
    } else {
        current
    };
    Ok(Value::Int(capacity))
}

/// `SubStr`: the part of the text between two positions.
///
/// AutoHotkey counts positions from one, and a negative position counts
/// from the end: -1 is the last character.
pub(crate) fn sub_str(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // Measured on the binary of v2.0.19 on 2026-11-10: the text is cut in the
    // code units of UTF-16, so the second unit of a surrogate pair is a text of
    // its own -- `Ord(SubStr(Chr(0x1F600), 2))` is 0xDE00.
    let text = crate::text16::the_code_units_of(&text_of(values, 0));
    let start = number_of(values, 1) as i64;
    let from = start_index(start, text.len()).min(text.len());
    let sliced: Vec<u16> = match values.get(2).and_then(|value| value.to_number()) {
        Some(length) => {
            let length = length as i64;
            if length < 0 {
                // A negative length leaves that many units out at the end of
                // the text.
                let to = text.len().saturating_sub((-length) as usize).max(from);
                text[from..to].to_vec()
            } else {
                let to = (from + length as usize).min(text.len());
                text[from..to].to_vec()
            }
        }
        None => text[from..].to_vec(),
    };
    Ok(Value::Text(crate::text16::the_text_of(&sliced)))
}

/// The place a position points at, counting from one.
///
/// A negative position counts from the end, and a position that is out of
/// the text is the end of it.
fn start_index(start: i64, length: usize) -> usize {
    if start < 0 {
        (length as i64 + start).max(0) as usize
    } else if start == 0 {
        length
    } else {
        (start - 1) as usize
    }
}

/// `Trim`, `LTrim` and `RTrim`: the text without the characters at the end.
///
/// They share one handler, and the variant says which end: `Trim` takes
/// both of them, `LTrim` the left one and `RTrim` the right one. The
/// characters are the space and the tab, unless the caller names others.
pub(crate) fn trim(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let characters: Vec<char> = text_of(values, 0).chars().collect();
    let set: Vec<char> = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_else(|| " \t".to_string())
        .chars()
        .collect();
    let mut start = 0usize;
    let mut end = characters.len();
    if variant != 2 {
        while start < end && set.contains(&characters[start]) {
            start += 1;
        }
    }
    if variant != 1 {
        while end > start && set.contains(&characters[end - 1]) {
            end -= 1;
        }
    }
    Ok(Value::Text(characters[start..end].iter().collect()))
}

// -- the predicates -------------------------------------------------------------

/// The `Is` functions: what the value is.
///
/// They share one handler, and the variant says which question is being
/// asked; the numbers are the ones the binary uses. The second argument
/// of the ones that take one is the mode of AutoHotkey, and the letters
/// of this tree are the Latin ones in either mode.
pub(crate) fn is_value(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    // The second parameter of v2 is the code page the text is read
    // with, and the text of this tree is always the text it holds.
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the code page of the text is not carried yet.".into(),
            line,
        });
    }
    let value = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let answer = match variant {
        1 => is_number(&value),
        2 => is_integer(&value),
        3 => is_float(&value),
        4 => is_time(&value),
        5 => is_digits(&text_of_value(&value, line)?),
        6 => is_hex_digits(&text_of_value(&value, line)?),
        7 => is_alnum(&text_of_value(&value, line)?),
        8 => is_alpha(&text_of_value(&value, line)?),
        9 => is_upper(&text_of_value(&value, line)?),
        10 => is_lower(&text_of_value(&value, line)?),
        _ => is_space(&text_of_value(&value, line)?),
    };
    Ok(Value::Int(if answer { 1 } else { 0 }))
}

/// `IsObject`: whether the value is an object.
///
/// The objects of this tree are the lists and the class instances, and
/// both of them are objects the way an array is one in AutoHotkey.
pub(crate) fn is_object(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first().cloned().unwrap_or(Value::Int(0));
    // Measured on the binary of v2.0.19 on 2026-10-31: everything that is
    // not a number and not a text is an object -- an array, a map, a class
    // and a reference too.
    let answer = !matches!(value, Value::Int(_) | Value::Float(_) | Value::Text(_));
    Ok(Value::Int(if answer { 1 } else { 0 }))
}

/// `Type`: the name of the type of the value.
pub(crate) fn type_of(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first().cloned().unwrap_or(Value::Int(0));
    let name = match value.type_name() {
        TypeName::Integer => "Integer",
        TypeName::Float => "Float",
        TypeName::String => "String",
        TypeName::Object => "Object",
        TypeName::VarRef => "VarRef",
        TypeName::Number => "Number",
        TypeName::Class => "Class",
        TypeName::ComValue => "ComValue",
    };
    // A class is a class: v2 names it so.
    if rt.class_name_of(&value).is_some() {
        return Ok(Value::Text("Class".into()));
    }
    // An object is named after the class it is an instance of.
    if let Value::Object(_) = &value {
        if let Some(class) = rt.class_of(&value) {
            return Ok(Value::Text(class));
        }
    }
    Ok(Value::Text(name.into()))
}

/// `IsSet`: whether the variable of the caller has a value.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a variable that has no
/// value is zero and not a failure, a name that was never written is zero,
/// and an argument that is not a variable is refused with "IsSet requires a
/// variable.".
pub(crate) fn is_set(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match values.first() {
        // The runtime hands the argument over as a reference only when the
        // script wrote a variable: a reference of its own -- `&x` -- is a
        // value, and v2 refuses it.
        Some(Value::Reference(reference)) if reference.alias => {
            // Measured on the test suite of KeySharp (the corpus script
            // `op-null-assign.ahk`) and on the notes of v2.1-alpha: a variable
            // that holds the absent value, or the result of an access that the
            // mark of the v2.1 passed over, does not have a value, and `IsSet`
            // is zero for both of them.
            let set = match rt.read_reference(reference) {
                Some(Value::Unset) | Some(Value::Skipped) => false,
                Some(_) => true,
                None => false,
            };
            Ok(Value::Int(if set { 1 } else { 0 }))
        }
        _ => Err(RuntimeError {
            message: "IsSet requires a variable.".to_string(),
            line,
        }),
    }
}

/// The text of the value, when it is text.
///
/// The questions that are about the letters of a value are not about
/// numbers, and AutoHotkey says so when it is given one.
fn text_of_value(value: &Value, line: u32) -> Result<String, RuntimeError> {
    match value {
        Value::Text(text) => Ok(text.clone()),
        other => Err(RuntimeError {
            message: crate::runtime::expected_type(TypeName::String, other.type_name()),
            line,
        }),
    }
}

/// Whether the value is a number: an integer, a float, or a text that
/// holds one.
fn is_number(value: &Value) -> bool {
    is_integer(value) || is_float(value)
}

/// Whether the value is a whole number.
fn is_integer(value: &Value) -> bool {
    match value {
        Value::Int(_) => true,
        Value::Float(_) => false,
        Value::Text(text) => is_integer_text(text),
        _ => false,
    }
}

/// Whether the value is a number with a point in it.
fn is_float(value: &Value) -> bool {
    match value {
        Value::Float(_) => true,
        Value::Int(_) => false,
        Value::Text(text) => is_float_text(text),
        _ => false,
    }
}

/// Whether the text is a whole number written out.
///
/// A hexadecimal number is a whole number too, and AutoHotkey counts one
/// as an integer.
fn is_integer_text(text: &str) -> bool {
    let text = text.trim_matches(&[' ', '\t'][..]);
    let rest = text.strip_prefix(&['+', '-'][..]).unwrap_or(text);
    if rest.is_empty() {
        return false;
    }
    if let Some(digits) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
        return !digits.is_empty()
            && digits
                .chars()
                .all(|character| character.is_ascii_hexdigit());
    }
    rest.chars().all(|character| character.is_ascii_digit())
}

/// Whether the text is a number with a point in it.
fn is_float_text(text: &str) -> bool {
    let text = text.trim_matches(&[' ', '\t'][..]);
    let rest = text.strip_prefix(&['+', '-'][..]).unwrap_or(text);
    let (mantissa, exponent) = match rest.find(['e', 'E']) {
        Some(at) => (&rest[..at], Some(&rest[at + 1..])),
        None => (rest, None),
    };
    if let Some(exponent) = exponent {
        let exponent = exponent.strip_prefix(&['+', '-'][..]).unwrap_or(exponent);
        if exponent.is_empty() || !exponent.chars().all(|character| character.is_ascii_digit()) {
            return false;
        }
    }
    let Some(point) = mantissa.find('.') else {
        return false;
    };
    let (whole, fraction) = mantissa.split_at(point);
    let fraction = &fraction[1..];
    if whole.is_empty() && fraction.is_empty() {
        return false;
    }
    whole.chars().all(|character| character.is_ascii_digit())
        && fraction.chars().all(|character| character.is_ascii_digit())
}

/// Whether the text holds nothing but the digits.
fn is_digits(text: &str) -> bool {
    text.chars().all(|character| character.is_ascii_digit())
}

/// Whether the text holds nothing but the hexadecimal digits.
///
/// A prefix of `0x` is tolerated, the way AutoHotkey tolerates it.
fn is_hex_digits(text: &str) -> bool {
    let rest = text
        .strip_prefix("0x")
        .or_else(|| text.strip_prefix("0X"))
        .unwrap_or(text);
    rest.chars().all(|character| character.is_ascii_hexdigit())
}

/// Whether the text holds nothing but the letters.
fn is_alpha(text: &str) -> bool {
    text.chars()
        .all(|character| character.is_ascii_alphabetic())
}

/// Whether the text holds nothing but the letters and the digits.
fn is_alnum(text: &str) -> bool {
    text.chars()
        .all(|character| character.is_ascii_alphanumeric())
}

/// Whether the text holds nothing but the capital letters.
fn is_upper(text: &str) -> bool {
    text.chars().all(|character| character.is_ascii_uppercase())
}

/// Whether the text holds nothing but the small letters.
fn is_lower(text: &str) -> bool {
    text.chars().all(|character| character.is_ascii_lowercase())
}

/// Whether the text holds nothing but the white space.
///
/// The white space of AutoHotkey is the space, the tab, the linefeed, the
/// return, the vertical tab and the formfeed.
fn is_space(text: &str) -> bool {
    text.chars()
        .all(|character| matches!(character, ' ' | '\t' | '\n' | '\r' | '\u{b}' | '\u{c}'))
}

/// Whether the value is a time.
///
/// The rule is the one of AutoHotkey: the value is written as
/// `YYYYMMDDHH24MISS`, so it is a time when it holds an even number of
/// digits, from four to fourteen, and the year is one the system knows.
fn is_time(value: &Value) -> bool {
    let text = value.to_text();
    if !text.chars().all(|character| character.is_ascii_digit()) {
        return false;
    }
    let digits = text.len();
    if !(4..=14).contains(&digits) || digits % 2 != 0 {
        return false;
    }
    let year: u32 = text[..4].parse().unwrap_or(0);
    (1601..=9999).contains(&year)
}

// -- the patterns ---------------------------------------------------------------

/// `RegExMatch`: where the pattern is in the text.
///
/// The position counts from one, and it is zero when the pattern is not
/// there at all. The third parameter is the variable that the match is
/// written into, and the fourth is the place where the search begins.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, with the source of it
/// read beside the measurements:
///
/// - the match is an object of the class `RegExMatchInfo`, and a text that
///   does not match leaves the variable with the empty text in it -- set,
///   and not unset;
/// - the place counts from one, and a place that is zero or negative is a
///   place from the end of the text: `len + place`, and zero when that is
///   before the first character, so the place zero is the end of the text;
/// - a value that is not a variable reference is refused with "Parameter
///   #3 of RegExMatch requires a variable reference, but received a ...".
pub(crate) fn regex_match(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The output variable, when the caller gives one.
    let output = match values.get(2) {
        None => None,
        Some(value @ Value::Reference(_)) => Some(value.clone()),
        Some(value) => {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    3,
                    "RegExMatch",
                    "a variable reference",
                    value,
                ),
                line,
            });
        }
    };
    let text = regex_text(values, 0, "RegExMatch", line)?;
    let pattern = regex_text(values, 1, "RegExMatch", line)?;
    // The place where the search begins, the way `BIF_RegEx` reads it.
    let mut starting = 0usize;
    if let Some(value) = values.get(3) {
        if !is_numeric_value(value) {
            return Err(RuntimeError {
                message: crate::runtime::requires(4, "RegExMatch", TypeName::Number, value),
                line,
            });
        }
        let length = text.chars().count() as i64;
        let mut place = token_to_int64(value) as i32 as i64;
        if place <= 0 {
            place += length;
            if place < 0 {
                place = 0;
            }
        } else if place > length {
            place = length;
        } else {
            place -= 1;
        }
        starting = place as usize;
    }
    let regex = crate::regex::Regex::new(&pattern).map_err(|reason| RuntimeError {
        message: reason,
        line,
    })?;
    let found = regex
        .find_at(&text, starting)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    let Some(found) = found else {
        // The text that does not match leaves the variable with the empty
        // text in it: the variable is set, and it holds nothing.
        if let Some(output) = &output {
            rt.write_reference(output, Value::Text(String::new()));
        }
        return Ok(Value::Int(0));
    };
    let place = found.span().0 as i64 + 1;
    if let Some(output) = &output {
        rt.write_reference(
            output,
            crate::classes::regexmatchinfo::of(&text, &regex, &found),
        );
    }
    Ok(Value::Int(place))
}

/// The text of one pattern parameter of a `RegExMatch` or a `RegExReplace`.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: an object is refused
/// with the kind it got, and a value that is not an object is written as
/// its text.
fn regex_text(
    values: &[Value],
    index: usize,
    name: &str,
    line: u32,
) -> Result<String, RuntimeError> {
    match values.get(index) {
        None => Ok(String::new()),
        // Measured on the binary of v2.0.19 on 2026-11-10: the absent value is
        // no argument, and the text of no argument is the empty text.
        Some(Value::Unset) => Ok(String::new()),
        Some(value @ (Value::Object(_) | Value::List(_) | Value::Reference(_))) => {
            Err(RuntimeError {
                message: crate::runtime::requires(index + 1, name, TypeName::String, value),
                line,
            })
        }
        Some(value) => Ok(value.to_text()),
    }
}

/// `RegExReplace`: the text with the matches of the pattern replaced.
///
/// The replacement may name the groups of the pattern with `$1` or `\1`.
/// v2 writes the number of the swaps into the variable of the caller, and
/// the case of the letters is the one of the options of the pattern: the
/// pattern begins with `(?i)` when the case is not to be looked at.
pub(crate) fn regex_replace(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = regex_text(values, 0, "RegExReplace", line)?;
    let pattern = regex_text(values, 1, "RegExReplace", line)?;
    let replacement = text_argument("RegExReplace", values, 2, line)?;
    let limit = number_of(values, 4) as i64;
    // The place where the search starts counts from one, the way
    // AutoHotkey counts the places.
    let starting = (number_of(values, 5) as i64).max(1) as usize - 1;
    let regex = crate::regex::Regex::new(&pattern).map_err(|reason| RuntimeError {
        message: reason,
        line,
    })?;
    let characters: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut at = starting.min(characters.len());
    out.extend(characters[..at].iter());
    let mut replaced = 0i64;
    while at <= characters.len() {
        let found = regex.find_at(&text, at).map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
        let Some(found) = found else {
            break;
        };
        let (start, end) = found.span();
        out.extend(characters[at..start].iter());
        out.push_str(&expand_replacement(
            &replacement,
            &regex,
            &found,
            &characters,
        ));
        replaced += 1;
        if end == start {
            // A match of no characters: the search has to move on, or it
            // would never end.
            if end < characters.len() {
                out.push(characters[end]);
            }
            at = end + 1;
        } else {
            at = end;
        }
        if limit > 0 && replaced >= limit {
            break;
        }
    }
    if at <= characters.len() {
        out.extend(characters[at..].iter());
    }
    // The number of the swaps goes into the variable of the caller.
    if let Some(value) = values.get(3) {
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    4,
                    "RegExReplace",
                    "a variable reference",
                    value,
                ),
                line,
            });
        }
        rt.write_reference(value, Value::Int(replaced));
    }
    Ok(Value::Text(out))
}

/// Put the groups of the match into the replacement.
///
/// A group is named with `$1` or `\1`, and `$$` is a dollar of its own.
fn expand_replacement(
    replacement: &str,
    regex: &crate::regex::Regex,
    found: &crate::regex::Match,
    characters: &[char],
) -> String {
    let mut out = String::new();
    let mut rest = replacement;
    while let Some(at) = rest.find(['$', '\\']) {
        out.push_str(&rest[..at]);
        let marker = rest[at..].chars().next().unwrap_or('$');
        let tail = &rest[at + marker.len_utf8()..];
        if marker == '$' && tail.starts_with('$') {
            out.push('$');
            rest = &tail[1..];
            continue;
        }
        // The group may be named in braces: `${1}`.
        let (name, after) = match tail.strip_prefix('{') {
            Some(braced) => match braced.find('}') {
                Some(close) => (&braced[..close], &braced[close + 1..]),
                None => ("", tail),
            },
            None => {
                let count = tail
                    .chars()
                    .take_while(|character| character.is_ascii_digit())
                    .count();
                (&tail[..count], &tail[count..])
            }
        };
        match name.parse::<usize>() {
            Ok(group) => {
                out.push_str(&found.group(group, characters).unwrap_or_default());
                rest = after;
            }
            // A group that is named: `${year}`. Measured on the binary of
            // v2.0.19 on 2026-11-09: the braced name is read, and the name
            // that is not a group is left as the text it was written as.
            Err(_) => match regex.group_number(name) {
                Some(group) => {
                    out.push_str(&found.group(group, characters).unwrap_or_default());
                    rest = after;
                }
                None => {
                    out.push(marker);
                    rest = tail;
                }
            },
        }
    }
    out.push_str(rest);
    out
}

// -- the screen -----------------------------------------------------------------

/// `Click`: a click at a place on the screen.
/// `Click`: the components of a click.
///
/// The v2 documentation says that the components may be spread across
/// the parameters, and that they are the place, the button, the number
/// of clicks, the pressing or the releasing of the button, and the way
/// the place is read. The tree carries the first three, and it says so
/// when a call asks for one of the others.
///
/// The place is two numbers, so a number that is not followed by another
/// one is the number of clicks: `Click 2` is a double click where the
/// pointer is, and not a click at (2, 0).
pub(crate) fn click(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The components are the words of the parameters, and a parameter
    // may hold more than one of them.
    let mut words: Vec<String> = Vec::new();
    for value in values {
        for word in value.to_text().split_whitespace() {
            words.push(word.to_string());
        }
    }
    let mut place: Option<(i64, i64)> = None;
    let mut button = "left".to_string();
    let mut count = 1u32;
    let mut at = 0usize;
    while at < words.len() {
        let word = words[at].clone();
        if let Ok(number) = word.parse::<f64>() {
            // The place is two numbers, and it comes before the number
            // of clicks.
            let next_is_a_number = words
                .get(at + 1)
                .map(|next| next.parse::<f64>().is_ok())
                .unwrap_or(false);
            if place.is_none() && next_is_a_number {
                let y = words[at + 1].parse::<f64>().unwrap_or(0.0);
                place = Some((number as i64, y as i64));
                at += 2;
                continue;
            }
            count = number.max(1.0) as u32;
            at += 1;
            continue;
        }
        match word.to_lowercase().as_str() {
            "left" | "l" => button = "left".to_string(),
            "right" | "r" => button = "right".to_string(),
            "middle" | "m" => button = "middle".to_string(),
            // The fourth and the fifth button are the ones that the
            // desktop of the tree does not carry.
            "x1" => {
                return Err(RuntimeError {
                    message: "the fourth button is not carried yet.".into(),
                    line,
                });
            }
            "x2" => {
                return Err(RuntimeError {
                    message: "the fifth button is not carried yet.".into(),
                    line,
                });
            }
            "down" | "d" | "up" | "u" => {
                return Err(RuntimeError {
                    message: "the pressing of the button is not carried yet.".into(),
                    line,
                });
            }
            "rel" | "relative" => {
                return Err(RuntimeError {
                    message: "the place relative to the pointer is not carried yet.".into(),
                    line,
                });
            }
            other
                if other.starts_with("wheel")
                    || other == "wu"
                    || other == "wd"
                    || other == "wl"
                    || other == "wr" =>
            {
                return Err(RuntimeError {
                    message: "the wheel is not carried yet.".into(),
                    line,
                });
            }
            other => {
                return Err(RuntimeError {
                    message: format!("{other} is not a part of a click."),
                    line,
                });
            }
        }
        at += 1;
    }
    // A click with no place is a click where the pointer is.
    let (x, y) = match place {
        Some(place) => place,
        None => {
            let (pointer_x, pointer_y) = rt
                .desktop()
                .mouse_position()
                .map_err(|e| desktop_failure(e, line))?;
            (pointer_x, pointer_y)
        }
    };
    let detail = rt
        .desktop()
        .click(x, y, &button, count)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(detail))
}

/// `MouseClick`: the button goes first, and the parameters are the ones of
/// the function of v2.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the button of a
/// `MouseClick` is the first parameter, and it is a text that is not
/// spread -- `MouseClick "R D"` is refused, and so is `MouseClick 10, 20`,
/// with the "10" in the `Extra`. A button that is not one of the words of
/// v2 is refused with "Parameter #1 of MouseClick is invalid." and the
/// value in the `Extra`, with the space at the end of it cut. A button
/// that is not there is the left one, and the space alone is not a button
/// either.
///
/// The wheel and the fourth and the fifth button are the ones that the
/// desktop of the tree does not carry, and the refusal says so.
pub(crate) fn mouse_click(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let spelled = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    // A button that is not there is the left one.
    let button = if spelled.is_empty() {
        "left".to_string()
    } else {
        spelled
    };
    let name = match button.to_lowercase().as_str() {
        "left" | "l" => "left",
        "right" | "r" => "right",
        "middle" | "m" => "middle",
        "x1" => {
            return Err(RuntimeError {
                message: "the fourth button is not carried yet.".into(),
                line,
            });
        }
        "x2" => {
            return Err(RuntimeError {
                message: "the fifth button is not carried yet.".into(),
                line,
            });
        }
        "wheelup" | "wu" | "wheeldown" | "wd" | "wheelleft" | "wl" | "wheelright" | "wr" => {
            return Err(RuntimeError {
                message: "the wheel is not carried yet.".into(),
                line,
            });
        }
        _ => {
            return Err(RuntimeError {
                message: "Parameter #1 of MouseClick is invalid.".into(),
                line,
            });
        }
    };
    // The place is the second and the third parameters, and the number of
    // the clicks is the fourth. The speed is the fifth, and the tree does
    // not carry it.
    let x = values
        .get(1)
        .and_then(|value| value.to_number())
        .map(|number| number as i64);
    let y = values
        .get(2)
        .and_then(|value| value.to_number())
        .map(|number| number as i64);
    let count = values
        .get(3)
        .and_then(|value| value.to_number())
        .unwrap_or(1.0)
        .max(1.0) as u32;
    // The pressing and the releasing of the button are the sixth parameter,
    // and the place relative to the pointer is the seventh.
    if values
        .get(5)
        .map(|value| !value.to_text().trim().is_empty())
        .unwrap_or(false)
    {
        return Err(RuntimeError {
            message: "the pressing of the button is not carried yet.".into(),
            line,
        });
    }
    if values
        .get(6)
        .map(|value| !value.to_text().trim().is_empty())
        .unwrap_or(false)
    {
        return Err(RuntimeError {
            message: "the place relative to the pointer is not carried yet.".into(),
            line,
        });
    }
    // A click with no place is a click where the pointer is.
    let (x, y) = match (x, y) {
        (Some(x), Some(y)) => (x, y),
        _ => {
            let (pointer_x, pointer_y) = rt
                .desktop()
                .mouse_position()
                .map_err(|e| desktop_failure(e, line))?;
            (pointer_x, pointer_y)
        }
    };
    let detail = rt
        .desktop()
        .click(x, y, name, count)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(detail))
}

/// `MouseClickDrag`: a click that drags.
///
/// The button goes down at the first place, the pointer moves to the
/// second one, and the button comes up there.
pub(crate) fn mouse_click_drag(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let words = words_of(values);
    let mut at = 0usize;
    let mut button = "left".to_string();
    if let Some(word) = words.first() {
        if let Some(name) = button_of(word) {
            button = name.to_string();
            at = 1;
        } else if word.parse::<f64>().is_err() {
            // The button comes first, and the tree carries the three
            // buttons of a mouse and not the fourth, the fifth or the
            // wheel.
            return Err(RuntimeError {
                message: format!(
                    "{word} is not a button of a mouse: the tree carries the left, the right and the middle one."
                ),
                line,
            });
        }
    }
    let mut numbers: Vec<i64> = Vec::new();
    for word in &words[at..] {
        match word.parse::<f64>() {
            Ok(number) => numbers.push(number as i64),
            Err(_) => {
                // The tree carries the two places of the drag and not the
                // speed or the relative mode.
                return Err(RuntimeError {
                    message: format!(
                        "{word} is not a part of a drag: the tree carries the two places and not the speed or the relative mode."
                    ),
                    line,
                });
            }
        }
    }
    if numbers.len() < 4 {
        return Err(RuntimeError {
            message: "a drag wants the two places: the one where the button goes down and the one where it comes up."
                .into(),
            line,
        });
    }
    let (x1, y1, x2, y2) = (numbers[0], numbers[1], numbers[2], numbers[3]);
    rt.desktop()
        .mouse_down(Some(x1), Some(y1), &button)
        .map_err(|e| desktop_failure(e, line))?;
    rt.desktop()
        .move_pointer(x2, y2)
        .map_err(|e| desktop_failure(e, line))?;
    rt.desktop()
        .mouse_up(None, None, &button)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(1))
}

/// `SetWorkingDir`: the working directory of the script.
///
/// The name of the directory is a subfolder of the working directory when
/// it is not an absolute path, the way v2 says it.
pub(crate) fn set_working_dir(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let directory = text_of(values, 0);
    if directory.is_empty() {
        return Err(RuntimeError {
            message: "the name of the directory is missing.".into(),
            line,
        });
    }
    rt.desktop()
        .set_working_directory(&directory)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(1))
}

/// `StrTitle`: a string in title case.
///
/// The rule is the one of the title case: the first letter of each word
/// is uppercased and the rest of the word is lowercased. A word is a run
/// of letters and of digits, so `GONE with the WIND` becomes `Gone With
/// The Wind`.
pub(crate) fn str_title(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(title_case(&text_of(values, 0))))
}

/// The text with the first letter of each word in the upper case and the
/// rest of it in the lower case.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: a word begins at the
/// start of the text and after the whitespace, and at nothing else --
/// `hello-world` becomes `Hello-world` and `ab-cd` becomes `Ab-cd` -- and the
/// first *letter* of the word is the one in the upper case: the digits in
/// front of it keep the word waiting, so `123abc` becomes `123Abc`, and a
/// word that has begun keeps the letters after its digits in the lower case,
/// so `abc123def` becomes `Abc123def`.
fn title_case(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut at_a_word = true;
    for character in text.chars() {
        if character.is_alphabetic() {
            if at_a_word {
                out.extend(character.to_uppercase());
                at_a_word = false;
            } else {
                out.extend(character.to_lowercase());
            }
        } else {
            out.push(character);
            // The whitespace begins a word, and the other characters leave the
            // word that has begun as it is and the one that has not begun
            // waiting for its first letter.
            if character.is_whitespace() {
                at_a_word = true;
            }
        }
    }
    out
}

/// `VerCompare`: two version strings, compared.
///
/// The rule is the one of `#Requires`: the numbers of the two versions
/// are compared one by one, and the component that is missing is a zero.
/// A version with a pre-release suffix is older than the same version
/// without it.
///
/// The second version may carry an operator -- `<`, `<=`, `>`, `>=` or
/// `=` -- and then the answer is whether the relation holds.
pub(crate) fn ver_compare(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let first = text_of(values, 0);
    let second = text_of(values, 1);
    if let Some((operator, wanted)) = split_operator(&second) {
        let order = compare_versions(&first, wanted.trim());
        let answer = match operator {
            "<" => order < 0,
            "<=" => order <= 0,
            ">" => order > 0,
            ">=" => order >= 0,
            _ => order == 0,
        };
        return Ok(Value::Int(answer as i64));
    }
    Ok(Value::Int(compare_versions(&first, second.trim()) as i64))
}

/// `IsLabel`: whether a label of the script is there.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the label is asked in
/// the scope that runs: the scope of the script, or the scope of the
/// function or of the method. The answer is one when the label is there
/// and zero when it is not, and the name of a label does not know its
/// case. A name that is empty is a name that is not there.
pub(crate) fn is_label(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = text_of(values, 0);
    Ok(Value::Int(if rt.has_label(&name) { 1 } else { 0 }))
}

/// The words of the arguments, one by one.
///
/// v2 writes the parts of a command in the parameters and the parameters
/// may hold more than one of them.
fn words_of(values: &[Value]) -> Vec<String> {
    let mut words = Vec::new();
    for value in values {
        for word in value.to_text().split_whitespace() {
            words.push(word.to_string());
        }
    }
    words
}

/// The button that a word names, when it names one.
fn button_of(word: &str) -> Option<&'static str> {
    match word.to_lowercase().as_str() {
        "left" | "l" => Some("left"),
        "right" | "r" => Some("right"),
        "middle" | "m" => Some("middle"),
        _ => None,
    }
}

/// The operator of a comparison, when the second version carries one.
fn split_operator(version: &str) -> Option<(&'static str, &str)> {
    let trimmed = version.trim_start();
    for operator in ["<=", ">=", "<", ">", "="] {
        if let Some(rest) = trimmed.strip_prefix(operator) {
            return Some((operator, rest));
        }
    }
    None
}

/// The order of two version strings.
///
/// The numbers are compared one by one, and the component that is missing
/// is a zero. A version with a pre-release suffix is older than the same
/// version without one.
///
/// The known limitation of v2 is carried: a component that is bigger
/// than 2147483647 is the same as 2147483647.
fn compare_versions(first: &str, second: &str) -> i32 {
    let (first_numbers, first_pre) = split_version(first);
    let (second_numbers, second_pre) = split_version(second);
    let order = compare_numbers(&first_numbers, &second_numbers);
    if order != 0 {
        return order;
    }
    match (first_pre, second_pre) {
        (None, None) => 0,
        (Some(_), None) => -1,
        (None, Some(_)) => 1,
        (Some(first_pre), Some(second_pre)) => compare_pre(first_pre, second_pre),
    }
}

/// The numbers of a version, and its pre-release suffix.
fn split_version(version: &str) -> (Vec<u64>, Option<&str>) {
    let trimmed = version.trim();
    let (numbers, pre) = match trimmed.split_once('-') {
        Some((numbers, pre)) => (numbers, Some(pre)),
        None => (trimmed, None),
    };
    let numbers = numbers
        .split('.')
        .map(|part| part.trim().parse::<u64>().unwrap_or(0).min(2147483647))
        .collect();
    (numbers, pre)
}

/// The order of the numbers of two versions.
fn compare_numbers(first: &[u64], second: &[u64]) -> i32 {
    let count = first.len().max(second.len());
    for index in 0..count {
        let left = first.get(index).copied().unwrap_or(0);
        let right = second.get(index).copied().unwrap_or(0);
        if left != right {
            return if left < right { -1 } else { 1 };
        }
    }
    0
}

/// The order of two pre-release suffixes.
///
/// A suffix of numbers is compared as a number, and a suffix of text is
/// compared as text.
fn compare_pre(first: &str, second: &str) -> i32 {
    match (first.parse::<u64>(), second.parse::<u64>()) {
        (Ok(left), Ok(right)) => {
            if left == right {
                0
            } else if left < right {
                -1
            } else {
                1
            }
        }
        (Ok(_), Err(_)) => -1,
        (Err(_), Ok(_)) => 1,
        (Err(_), Err(_)) => match first.cmp(second) {
            core::cmp::Ordering::Less => -1,
            core::cmp::Ordering::Equal => 0,
            core::cmp::Ordering::Greater => 1,
        },
    }
}

/// `MouseGetPos`: where the pointer is.
///
/// v2 writes the place of the pointer into the variables of the caller,
/// and it answers with nothing. The window and the control are empty: the
/// box has no window to ask. The flag of v2 says how the control is to be
/// found, and there is no control to find.
pub(crate) fn mouse_get_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (x, y) = rt
        .desktop()
        .mouse_position()
        .map_err(|e| desktop_failure(e, line))?;
    let places = [
        Value::Int(x),
        Value::Int(y),
        Value::Text(String::new()),
        Value::Text(String::new()),
    ];
    for (index, place) in places.into_iter().enumerate() {
        let Some(value) = values.get(index) else {
            continue;
        };
        // The place is written into the variables of the caller, and
        // those are given by reference.
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    index + 1,
                    "MouseGetPos",
                    "a VarRef",
                    value,
                ),
                line,
            });
        }
        rt.write_reference(value, place);
    }
    Ok(Value::Text(String::new()))
}

/// `MouseMove`: the pointer to a place on the screen.
pub(crate) fn mouse_move(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The relative place of the move is not carried: the box moves the
    // pointer to the place, and not from where it is.
    if values.len() > 3 {
        return Err(RuntimeError {
            message: "the relative place of the move is not carried yet.".into(),
            line,
        });
    }
    // The speed of the move is not carried either: the box moves the pointer
    // at its own speed. The speed of zero is the speed of nothing, and the
    // pointer goes to the place at once.
    if let Some(speed) = values.get(2) {
        if speed.to_number().unwrap_or(0.0) != 0.0 {
            return Err(RuntimeError {
                message: "the speed of the move is not carried yet.".into(),
                line,
            });
        }
    }
    let x = number_of(values, 0) as i64;
    let y = number_of(values, 1) as i64;
    let detail = rt
        .desktop()
        .move_pointer(x, y)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(detail))
}

/// `PixelGetColor`: the colour of one pixel.
pub(crate) fn pixel_get_color(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (x, y) = if values.len() >= 2 {
        (number_of(values, 0) as i64, number_of(values, 1) as i64)
    } else {
        let (pointer_x, pointer_y) = rt
            .desktop()
            .mouse_position()
            .map_err(|e| desktop_failure(e, line))?;
        (pointer_x, pointer_y)
    };
    let colour = rt
        .desktop()
        .pixel(x, y)
        .map_err(|e| desktop_failure(e, line))?;
    rt.set_global("pixel", Value::Text(colour.clone()));
    Ok(Value::Text(colour))
}

/// `PixelSearch`: where a colour is on the screen.
///
/// The place is written in the two variables of the caller and the answer
/// is one when the colour is there and zero when it is not, the way v2
/// does it.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the command takes
/// seven parameters and the first two are references -- `PixelSearch
/// &OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ColorID` -- and the
/// documentation of the v2.0.19 says the two variables are made blank
/// when the colour is not there.
pub(crate) fn pixel_search(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The place of the colour is written in the first two parameters, and
    // they are given by reference.
    for index in 0..2 {
        let Some(value) = values.get(index) else {
            continue;
        };
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    index + 1,
                    "PixelSearch",
                    "a VarRef",
                    value,
                ),
                line,
            });
        }
    }
    let x1 = number_of(values, 2) as i64;
    let y1 = number_of(values, 3) as i64;
    let x2 = number_of(values, 4) as i64;
    let y2 = number_of(values, 5) as i64;
    let colour = text_of(values, 6);
    let found = rt
        .desktop()
        .pixel_search(x1, y1, x2, y2, &colour)
        .map_err(|e| desktop_failure(e, line))?;
    match found {
        Some((x, y)) => {
            rt.write_reference(&values[0], Value::Int(x));
            rt.write_reference(&values[1], Value::Int(y));
            Ok(Value::Int(1))
        }
        None => {
            // The place of v2 is blank when the colour is not there.
            rt.write_reference(&values[0], Value::Text(String::new()));
            rt.write_reference(&values[1], Value::Text(String::new()));
            Ok(Value::Int(0))
        }
    }
}

/// `Screenshot`: a picture of a part of the screen.
///
/// AutoHotkey v2 has no such built-in; this one is ours, and it is the
/// only name in the language that v2 would not have.
pub(crate) fn screenshot(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let x = number_of(values, 0) as i64;
    let y = number_of(values, 1) as i64;
    let width = number_of(values, 2) as i64;
    let height = number_of(values, 3) as i64;
    let name = text_of(values, 4);
    let path = rt
        .desktop()
        .capture(x, y, width, height, &name)
        .map_err(|e| desktop_failure(e, line))?;
    rt.set_global("screenshot", Value::Text(path.clone()));
    Ok(Value::Text(path))
}

// -- the windows ----------------------------------------------------------------

/// Whether a title matches the text that is wanted, the way v2 matches it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a pattern of the `RegEx`
/// mode that does not compile is not a failure of the question about a
/// window -- the question answers that no window matches -- while a direct
/// `RegExMatch` of the same pattern is a failure. The error of the pattern is
/// therefore dropped here, and only here.
fn a_title_matches(mode: crate::desktop::TitleMatch, title: &str, wanted: &str) -> bool {
    mode.matches(title, wanted).unwrap_or(false)
}

/// The window a call of the family names, inside a listing of the windows.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a number is the id of a
/// window of this runtime, and a text is a title matched the way the script
/// matches it -- the mode of the settings. The empty text and the omitted one
/// ask about the active window, which is the way this tree has always asked.
fn the_window_in(
    windows: &[crate::desktop::WindowInfo],
    value: Option<&Value>,
) -> Result<Option<crate::desktop::WindowInfo>, RuntimeError> {
    match value {
        Some(Value::Int(id)) => Ok(windows.iter().find(|window| window.id == *id).cloned()),
        Some(value) if !value.to_text().is_empty() => {
            let wanted = value.to_text();
            let mode = crate::settings::title_match_mode();
            for window in windows {
                if a_title_matches(mode, &window.title, &wanted) {
                    return Ok(Some(window.clone()));
                }
            }
            Ok(None)
        }
        _ => Ok(windows.iter().find(|window| window.active).cloned()),
    }
}

/// The failure of a window query that found nothing.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `WinGetID`, `WinGetIDLast`
/// and `WinGetClass` of a window that is not there answer "Target window not
/// found.", and the `Extra` of the failure is the title that was asked about.
fn no_window(line: u32) -> RuntimeError {
    RuntimeError {
        message: "Target window not found.".to_string(),
        line,
    }
}

pub(crate) fn window_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The other parameters of v2 are the text of the window and the two
    // exclusions, and the desktop of the box has none of them.
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    // The listing names the window the way v2 answers it: measured on the
    // binary of v2.0.19 on 2026-11-09, `WinActive("A")` is the id of the
    // active window, and not one.
    match rt.desktop().windows() {
        Ok(windows) => {
            let window = the_window_in(&windows, values.first())?;
            return Ok(Value::Int(match window {
                Some(window) if window.active => window.id,
                _ => 0,
            }));
        }
        Err(reason) => {
            // A window of the listing that is not there is the answer of the
            // desktop itself, and a window that is named by its id cannot be
            // looked up without the listing.
            if matches!(values.first(), Some(Value::Int(_))) {
                return Err(RuntimeError {
                    message: format!("WinActive cannot look a window up by its id: {reason}"),
                    line,
                });
            }
        }
    }
    let title = text_of(values, 0);
    let mode = crate::settings::title_match_mode();
    match rt
        .desktop()
        .window_active(&title, mode)
        .map_err(|e| desktop_failure(e, line))?
    {
        WindowAnswer::Active => Ok(Value::Int(1)),
        // A window that is not there is not the active one, and a window
        // that is there but is not in front is not the active one either.
        WindowAnswer::NotActive | WindowAnswer::Absent => Ok(Value::Int(0)),
        WindowAnswer::Unknown(reason) => Err(RuntimeError {
            message: format!("WinActive cannot answer: {reason}"),
            line,
        }),
    }
}

/// `WinExist`: whether a window with this title exists.
///
/// It shares its handler with `WinActive`, and the variant says which of
/// the two it is: a window that exists is the answer, whether it is the
/// active one or not.
pub(crate) fn window_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The other parameters of v2 are the text of the window and the two
    // exclusions, and the desktop of the box has none of them.
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    // The answer of v2 is the id of the window that is there, and not one:
    // measured on the binary of v2.0.19 on 2026-11-09, `WinExist("A")` is the
    // id of the active window.
    match rt.desktop().windows() {
        Ok(windows) => {
            let window = the_window_in(&windows, values.first())?;
            return Ok(Value::Int(window.map(|window| window.id).unwrap_or(0)));
        }
        Err(reason) => {
            if matches!(values.first(), Some(Value::Int(_))) {
                return Err(RuntimeError {
                    message: format!("WinExist cannot look a window up by its id: {reason}"),
                    line,
                });
            }
        }
    }
    let title = text_of(values, 0);
    let mode = crate::settings::title_match_mode();
    match rt
        .desktop()
        .window_exists(&title, mode)
        .map_err(|e| desktop_failure(e, line))?
    {
        WindowAnswer::Active | WindowAnswer::NotActive => Ok(Value::Int(1)),
        // A window that is not there is not there: the answer is false,
        // and not a failure.
        WindowAnswer::Absent => Ok(Value::Int(0)),
        WindowAnswer::Unknown(reason) => Err(RuntimeError {
            message: format!("WinExist cannot answer: {reason}"),
            line,
        }),
    }
}

/// `WinGetTitle`: the title of the active window.
pub(crate) fn win_get_title(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The other parameters of v2 are the text of the window and the two
    // exclusions, and the desktop of the box has none of them.
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    // Measured on the binary of v2.0.19 on 2026-11-09: the title of a window
    // that is not there is "Target window not found.", while the empty text
    // and the omitted one ask about the active window, which the tree has
    // always answered with the empty text when there is none.
    let asked = match values.first() {
        None => false,
        Some(value) => match value {
            Value::Int(_) => true,
            other => !other.to_text().is_empty(),
        },
    };
    if let Ok(windows) = rt.desktop().windows() {
        let window = the_window_in(&windows, values.first())?;
        let title = match window {
            Some(window) => window.title,
            None if asked => return Err(no_window(line)),
            None => String::new(),
        };
        // The pause of v2 follows a windowing function, and a delay of -1 is
        // no pause at all.
        let delay = crate::settings::the_win_delay();
        if delay > 0 {
            rt.sleep_ms(delay as u64);
        }
        return Ok(Value::Text(title));
    }
    if asked && matches!(values.first(), Some(Value::Int(_))) {
        let reason = rt.desktop().windows().err().unwrap_or_default();
        return Err(RuntimeError {
            message: format!("WinGetTitle cannot look a window up by its id: {reason}"),
            line,
        });
    }
    let title = rt
        .desktop()
        .active_window_title()
        .map_err(|e| desktop_failure(e, line))?;
    // The pause of v2 follows a windowing function, and a delay of -1 is no
    // pause at all.
    let delay = crate::settings::the_win_delay();
    if delay > 0 {
        rt.sleep_ms(delay as u64);
    }
    Ok(Value::Text(title.unwrap_or_default()))
}

// -- the processes ----------------------------------------------------------------

/// The process a call names: the text of it, and nothing when the call names
/// nothing.
///
/// The text is the pid or the name of a process, and the desktop reads it the
/// way the binary reads it: a text that is a number is a pid, and the rest is
/// a name. Nothing means the process of the script itself.
fn the_process_of(values: &[Value], index: usize) -> Option<String> {
    values.get(index).map(|value| value.to_text())
}

/// The timeout of a wait, in seconds, and nothing when the call gives none.
///
/// The timeout of the binary is a number of seconds and it may be a text that
/// holds one; a call that gives none waits forever.
fn the_timeout_of(
    values: &[Value],
    index: usize,
    name: &str,
    line: u32,
) -> Result<Option<f64>, RuntimeError> {
    if values.get(index).is_none() {
        return Ok(None);
    }
    Ok(Some(number_argument(values, index, line, name)?))
}

/// The failure of a process that is not there.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `ProcessGetName` and
/// `ProcessGetPath` of a pid that is not there answer "Target process not
/// found.", of the class `TargetError`, and the name of the built-in is in
/// the `What`.
fn no_process(line: u32) -> RuntimeError {
    RuntimeError {
        message: "Target process not found.".to_string(),
        line,
    }
}

/// `ProcessExist`: whether a process is there, and the pid of it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the pid of
/// the process, and zero when there is none; a call with no parameter asks
/// about the process of the script itself, and a pid that is not there is
/// zero and not a failure.
pub(crate) fn process_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let which = the_process_of(values, 0);
    let pid = rt
        .desktop()
        .process_exist(which.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(pid as i64))
}

/// `ProcessGetName`: the name of the executable of a process.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the name is the file name
/// of the executable -- "AutoHotkey64.exe", and not the path -- and a process
/// that is not there is the failure "Target process not found.".
pub(crate) fn process_get_name(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let which = the_process_of(values, 0);
    let answer = rt
        .desktop()
        .process_name(which.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(name) => Ok(Value::Text(name)),
        None => Err(no_process(line)),
    }
}

/// `ProcessGetPath`: the full path of the executable of a process.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the path is the whole
/// path of the executable, and a process that is not there is the failure
/// "Target process not found.".
pub(crate) fn process_get_path(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let which = the_process_of(values, 0);
    let answer = rt
        .desktop()
        .process_path(which.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(path) => Ok(Value::Text(path)),
        None => Err(no_process(line)),
    }
}

/// `ProcessGetParent`: the pid of the parent of a process.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the pid of
/// the parent, and zero for a process that is not there -- the parent of a
/// process that is not there is not a failure.
pub(crate) fn process_get_parent(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let which = the_process_of(values, 0);
    let pid = rt
        .desktop()
        .process_parent(which.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(pid as i64))
}

/// `ProcessClose`: close a process, and answer the pid of it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the pid
/// that was closed, and zero when the process was not there or could not be
/// closed -- the binary answers zero for a process it could not open, too.
pub(crate) fn process_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(which) = the_process_of(values, 0) else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "ProcessClose"),
            line,
        });
    };
    let pid = rt
        .desktop()
        .process_close(&which)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(pid as i64))
}

/// `ProcessWait`: wait for a process to be there.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the pid of
/// the process when it appears, and zero at the timeout; a call with no
/// timeout waits forever.
pub(crate) fn process_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(which) = the_process_of(values, 0) else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "ProcessWait"),
            line,
        });
    };
    let timeout = the_timeout_of(values, 1, "ProcessWait", line)?;
    let pid = rt
        .desktop()
        .process_wait(&which, timeout)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(pid as i64))
}

/// `ProcessWaitClose`: wait for a process that is there to close.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is zero when
/// the process is gone -- a process that never existed is gone -- and the pid
/// of the process that is still there at the timeout.
pub(crate) fn process_wait_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(which) = the_process_of(values, 0) else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "ProcessWaitClose"),
            line,
        });
    };
    let timeout = the_timeout_of(values, 1, "ProcessWaitClose", line)?;
    let pid = rt
        .desktop()
        .process_wait_close(&which, timeout)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(pid as i64))
}

/// `ProcessSetPriority`: the priority of a process, and the pid of it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the binary reads only the
/// first letter of the priority word -- "Bogus" is the below-normal class,
/// and a number is an invalid parameter -- the call answers the pid of the
/// process, and a process that is not there is the failure "Target process
/// not found.". A call with no process named is the process of the script
/// itself, and an empty text there is the script itself too.
pub(crate) fn process_set_priority(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let priority = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let letter = priority
        .chars()
        .next()
        .map(|letter| letter.to_ascii_uppercase());
    if !matches!(letter, Some('L' | 'B' | 'N' | 'A' | 'H' | 'R')) {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "ProcessSetPriority"),
            line,
        });
    }
    let which = the_process_of(values, 1);
    let answer = rt
        .desktop()
        .process_set_priority(&priority, which.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(pid) => Ok(Value::Int(pid as i64)),
        None => Err(no_process(line)),
    }
}

// -- the screen and the machine --------------------------------------------------

/// The monitor a call of the monitor family names, and the monitors of the
/// desktop.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: an omitted number and the
/// number zero ask about the primary monitor; a number that is not a monitor
/// of the desktop is "Parameter #1 of <name> is invalid." with the number in
/// the `Extra`; a text that holds a number is a number, and the part of it
/// after the point is cut.
fn the_monitor_of(
    rt: &mut Runtime<'_>,
    values: &[Value],
    name: &str,
    line: u32,
) -> Result<(usize, Vec<crate::desktop::Monitor>), RuntimeError> {
    let wanted = match values.first() {
        None => 0,
        Some(value) => token_to_int64(value) as i32 as i64,
    };
    let monitors = rt
        .desktop()
        .monitors()
        .map_err(|e| desktop_failure(e, line))?;
    if wanted == 0 {
        let primary = rt
            .desktop()
            .primary_monitor()
            .map_err(|e| desktop_failure(e, line))?;
        if primary == 0 || primary > monitors.len() {
            return Err(RuntimeError {
                message: crate::runtime::invalid_parameter(1, name),
                line,
            });
        }
        return Ok((primary, monitors));
    }
    if wanted < 0 || wanted as usize > monitors.len() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, name),
            line,
        });
    }
    Ok((wanted as usize, monitors))
}

/// The monitor at a place, counted from one, when it is there.
fn the_monitor_at(
    monitors: &[crate::desktop::Monitor],
    index: usize,
) -> Option<crate::desktop::Monitor> {
    monitors.get(index.checked_sub(1)?).cloned()
}

/// `MonitorGet`: the bounds of a monitor.
pub(crate) fn monitor_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_monitor_bounds_into(rt, values, line, "MonitorGet")
}

/// `MonitorGetCount`: how many monitors the desktop has.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the number
/// of the monitors, and a desktop with one screen answers one.
pub(crate) fn monitor_get_count(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let monitors = rt
        .desktop()
        .monitors()
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(monitors.len() as i64))
}

/// `MonitorGetName`: the name of a monitor.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the name of the monitor
/// of the binary is "\\.\DISPLAY1", the name the system gives it; the name of
/// an output of a Wayland compositor is the name of the output. A desktop
/// that does not say the name of its monitors is refused with the reason.
pub(crate) fn monitor_get_name(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (index, monitors) = the_monitor_of(rt, values, "MonitorGetName", line)?;
    let Some(monitor) = the_monitor_at(&monitors, index) else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "MonitorGetName"),
            line,
        });
    };
    if monitor.name.is_empty() {
        return Err(RuntimeError {
            message: "this desktop does not say the name of its monitors.".to_string(),
            line,
        });
    }
    Ok(Value::Text(monitor.name))
}

/// `MonitorGetPrimary`: the number of the primary monitor.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer counts from
/// one, and it is the number that a call of `MonitorGet` with no monitor
/// answers.
pub(crate) fn monitor_get_primary(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let index = rt
        .desktop()
        .primary_monitor()
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(index as i64))
}

/// `MonitorGetWorkArea`: the part of a monitor that the panels leave.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the shape is the one of
/// `MonitorGet`, and the work area of the monitor of the binary was the
/// screen less the bar of the taskbar -- 0, 0, 3840, 2112 for a screen of
/// 3840 by 2160. A desktop that does not say the work area of its monitors
/// is refused with the reason.
pub(crate) fn monitor_get_work_area(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (index, monitors) = the_monitor_of(rt, values, "MonitorGetWorkArea", line)?;
    if the_monitor_at(&monitors, index).is_none() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "MonitorGetWorkArea"),
            line,
        });
    }
    let Some((left, top, right, bottom)) = rt
        .desktop()
        .monitor_work_area(index)
        .map_err(|e| desktop_failure(e, line))?
    else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "MonitorGetWorkArea"),
            line,
        });
    };
    for (place, number) in [(1, left), (2, top), (3, right), (4, bottom)] {
        if let Some(value) = values.get(place) {
            rt.write_reference(value, Value::Int(number));
        }
    }
    Ok(Value::Int(1))
}

/// `SysGet`: a metric of the system.
///
/// Measured on the binary of v2.0.19 on 2026-11-09, with the source of it
/// read beside the measurements: the number of `SysGet` is the number of a
/// metric of `GetSystemMetrics`, and the binary answers it as it is. The
/// numbers that are about the screen are the ones this desktop can answer --
/// 0 and 1 are the width and the height of the primary monitor, 16 the width
/// of a full screen, 76 to 79 the virtual screen, 80 the number of monitors
/// and 81 the one metric of the format of the displays. The other metrics are
/// the ones of the window manager of Windows, and the number of one of them
/// is refused with the reason; a number that is not a metric at all is zero,
/// which is what the binary answers for one.
pub(crate) fn sys_get(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(value) = values.first() else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "SysGet"),
            line,
        });
    };
    // The number is the one of `GetSystemMetrics`, read the way the binary
    // reads it: the part of a float after the point is cut.
    let metric = token_to_int64(value) as i32 as i64;
    let monitors = rt
        .desktop()
        .monitors()
        .map_err(|e| desktop_failure(e, line))?;
    if monitors.is_empty() && (0..=102).contains(&metric) && metric != 81 {
        return Err(RuntimeError {
            message: format!(
                "the compositor published no monitor, so the metric {metric} of SysGet is not \
                 known."
            ),
            line,
        });
    }
    let answer = match metric {
        0 | 16 => {
            let index = rt
                .desktop()
                .primary_monitor()
                .map_err(|e| desktop_failure(e, line))?;
            match the_monitor_at(&monitors, index) {
                Some(monitor) => monitor.width(),
                None => 0,
            }
        }
        1 => {
            let index = rt
                .desktop()
                .primary_monitor()
                .map_err(|e| desktop_failure(e, line))?;
            match the_monitor_at(&monitors, index) {
                Some(monitor) => monitor.height(),
                None => 0,
            }
        }
        // The virtual screen: the box around all of the monitors.
        76 => monitors
            .iter()
            .map(|monitor| monitor.left)
            .min()
            .unwrap_or(0),
        77 => monitors
            .iter()
            .map(|monitor| monitor.top)
            .min()
            .unwrap_or(0),
        78 => {
            let left = monitors.iter().map(|m| m.left).min().unwrap_or(0);
            let right = monitors.iter().map(|m| m.right).max().unwrap_or(0);
            right - left
        }
        79 => {
            let top = monitors.iter().map(|m| m.top).min().unwrap_or(0);
            let bottom = monitors.iter().map(|m| m.bottom).max().unwrap_or(0);
            bottom - top
        }
        80 => monitors.len() as i64,
        // The one metric of the format: every output of a compositor is the
        // same format as far as a script can see, and the binary answers 1
        // for the one screen of its machine.
        81 => 1,
        other if (0..=102).contains(&other) => {
            return Err(RuntimeError {
                message: format!(
                    "SysGet({other}) is a metric of the window manager of Windows, and this \
                     desktop does not have one."
                ),
                line,
            });
        }
        // A number that is not a metric of the system is zero, which is what
        // the binary answers for one: measured on it on 2026-11-09,
        // `SysGet(-1)` and `SysGet(1000)` are zero.
        _ => 0,
    };
    Ok(Value::Int(answer))
}

/// `SysGetIPAddresses`: the addresses of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is an array of
/// texts, one for each address of the machine, and the address of the
/// loopback is not one of them.
pub(crate) fn sys_get_ip_addresses(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let addresses = rt
        .desktop()
        .ip_addresses()
        .map_err(|e| desktop_failure(e, line))?;
    // The answer of v2 is an `Array`, and not a list of the runtime: a script
    // asks it for its `Length` and its items the way it asks an array.
    let items: Vec<Value> = addresses.into_iter().map(Value::Text).collect();
    crate::classes::array::construct(&items, rt, line).map_err(|failure| RuntimeError {
        message: the_message_of(failure),
        line,
    })
}

// -- the keyboard, the debugger, the trash and the drives -------------------------

/// `SetCapsLockState`, `SetNumLockState` and `SetScrollLockState`: the state
/// of a lock light of the keyboard.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: "On" turns the light on
/// and "Off" turns it out -- and `GetKeyState(<lock>, "T")` reads the state
/// back, one for the light that is on. Every other word, "Toggle" included,
/// leaves the state as it was, and no word is a failure.
///
/// The "Toggle" of the documentation presses the key of the lock, which
/// turns the lamp of the physical keyboard; the state that `GetKeyState`
/// reads is the one the program set, and it does not move.
fn set_lock_state(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    lock: &str,
) -> Result<Value, RuntimeError> {
    let word = text_of(values, 0).trim().to_lowercase();
    let wanted = match word.as_str() {
        "on" => Some(true),
        "off" => Some(false),
        _ => None,
    };
    if let Some(on) = wanted {
        rt.desktop()
            .set_lock_light(lock, on)
            .map_err(|reason| desktop_failure(reason, line))?;
    }
    Ok(Value::Text(String::new()))
}

/// `OutputDebug`: a text for the debugger of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the parameter is a text,
/// and the answer is the empty text. A machine whose debugger is the standard
/// error of the process writes the text there, and the report of the runner on
/// the standard output is not touched.
pub(crate) fn output_debug(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    rt.desktop()
        .output_debug(&text)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `FileRecycle`: a file, a folder, or the files that a pattern matches.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the empty
/// text, a plain path that is not there is the failure "Failed", a pattern
/// that matches nothing is not a failure, and an empty path is "Parameter #1
/// of FileRecycle is invalid." with the empty text in the `Extra`.
pub(crate) fn file_recycle(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(value) = values.first() else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "FileRecycle"),
            line,
        });
    };
    let pattern = value.to_text();
    if pattern.is_empty() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "FileRecycle"),
            line,
        });
    }
    rt.desktop()
        .recycle(&pattern)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `FileRecycleEmpty`: empty the trash of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the empty
/// text, and the drive that is named is the trash that is emptied.
pub(crate) fn file_recycle_empty(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let drive = values
        .first()
        .map(|value| value.to_text())
        .filter(|text| !text.is_empty());
    rt.desktop()
        .empty_trash(drive.as_deref())
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

// -- the rest -------------------------------------------------------------------

/// `MsgBox`: a message for the person watching.
///
/// The box has no window to show it in, so the message goes into the
/// report instead. That is the box's answer, not a quiet `false`.
pub(crate) fn msg_box(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The box has no buttons, no title and no answer to give back.
    if values.len() > 1 {
        return Err(RuntimeError {
            message:
                "the options, the title and the variable that takes the answer are not carried yet."
                    .into(),
            line,
        });
    }
    let text = rt.interpolate(&text_of(values, 0), line)?;
    rt.push_output(text.clone());
    Ok(Value::Text(text))
}

/// `Run`: a command, and what it answered.
pub(crate) fn run(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The third parameter of v2 is the options of the window, and the
    // fourth is the variable that takes the pid of the process. The
    // desktop of the box has no options, and the reference operator is
    // not carried, so a call that asks for them fails with the reason.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the options of the window and the pid of the process are not carried yet."
                .into(),
            line,
        });
    }
    let command = text_of(values, 0);
    let working_dir = text_of(values, 1);
    let (code, stdout, stderr) = rt
        .desktop()
        .run(&command, &working_dir)
        .map_err(|e| desktop_failure(e, line))?;
    if !stdout.trim().is_empty() {
        rt.push_output(stdout.trim_end().to_string());
    }
    if !stderr.trim().is_empty() {
        rt.push_output(stderr.trim_end().to_string());
    }
    Ok(Value::Int(code as i64))
}

/// `Send`: text and keys, the way AutoHotkey writes them.
pub(crate) fn send(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = rt.interpolate(&text_of(values, 0), line)?;
    let mut parts = Vec::new();
    for part in split_send(&text) {
        let said = match part {
            SendPart::Text(text) => rt.desktop().type_text(&text),
            SendPart::Key { name, modifiers } => rt.desktop().press_key(&name, &modifiers),
            SendPart::Down(name) => match mouse_button(&name) {
                Some(button) => rt.desktop().mouse_down(None, None, button),
                None => rt.desktop().key_down(&name),
            },
            SendPart::Up(name) => match mouse_button(&name) {
                Some(button) => rt.desktop().mouse_up(None, None, button),
                None => rt.desktop().key_up(&name),
            },
        };
        parts.push(said.map_err(|e| desktop_failure(e, line))?);
    }
    Ok(Value::Text(parts.concat()))
}

/// `Sleep`: the pause, in milliseconds.
pub(crate) fn sleep(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let millis = number_of(values, 0).clamp(0.0, 60_000.0) as u64;
    rt.sleep_ms(millis);
    Ok(Value::Int(millis as i64))
}

// -- the clipboard ----------------------------------------------------------------

/// The gap between the reads of the clipboard while a wait goes on.
///
/// The read is a process of its own on the box, and a wait is not a
/// quarter of a second long.
const CLIP_POLL_MS: u64 = 50;

/// `ClipWait`: wait until the clipboard has data.
///
/// The timeout is in seconds and may be a fraction of one. A wait with no
/// timeout is for the time the script has left: the timeout of the run is
/// checked between the statements, and this wait is inside one.
pub(crate) fn clip_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The second parameter waits for the data of any kind, and the
    // clipboard of this runtime carries text only.
    if number_of(values, 1) != 0.0 {
        return Err(RuntimeError {
            message: "the clipboard of this runtime carries text only, and it cannot wait for data of any kind.".to_string(),
            line,
        });
    }
    let limit = if values.is_empty() {
        None
    } else {
        Some(number_of(values, 0) * 1000.0)
    };
    let started = rt.now_ms();
    loop {
        let text = rt
            .desktop()
            .clipboard_read()
            .map_err(|message| desktop_failure(message, line))?;
        if !text.is_empty() {
            return Ok(Value::Int(1));
        }
        let waited = rt.now_ms().saturating_sub(started) as f64;
        let left = match limit {
            Some(limit) => {
                if waited >= limit {
                    return Ok(Value::Int(0));
                }
                limit - waited
            }
            None => {
                let left = rt.remaining_ms();
                if left == 0 {
                    return Ok(Value::Int(0));
                }
                left as f64
            }
        };
        rt.sleep_ms((left as u64).clamp(1, CLIP_POLL_MS));
    }
}

// -- the pattern of `Format` -----------------------------------------------------

/// The largest width or precision a pattern may ask for.
///
/// The binary builds the spec in a buffer of `12 + MAX_INTEGER_LENGTH*2`
/// characters and refuses a spec that does not fit, so a width longer than a
/// few dozen digits is not one it takes. The same kind of limit keeps a
/// pattern from asking for a text of no end here.
const FORMAT_LIMIT: usize = 100_000;

/// The flags of a C specifier: `-`, `+`, the space, `#` and `0`.
#[derive(Clone, Copy, Default)]
struct FormatFlags {
    minus: bool,
    plus: bool,
    space: bool,
    hash: bool,
    zero: bool,
}

/// What a specifier converts its value to.
#[derive(Clone, Copy, PartialEq, Eq)]
enum FormatKind {
    /// `d`, `i`, `o`, `u`, `x` and `X`: a whole number.
    Int,
    /// `e`, `E`, `f`, `g`, `G`, `a` and `A`: a float.
    Float,
    /// `c` and `C`: one character.
    Char,
    /// `p`: an address, written as sixteen hex digits.
    Pointer,
    /// The default and `s`: the text of the value, with an optional custom
    /// case -- `U`, `L` or `T`.
    Str(Option<char>),
}

/// One C specifier, read out of a placeholder.
struct FormatSpec {
    flags: FormatFlags,
    width: usize,
    precision: Option<usize>,
    kind: FormatKind,
    /// The type character of the specifier, or `'s'` for the default.
    letter: char,
}

/// One argument of a placeholder, converted to what the specifier wants.
enum FormatValue {
    Int(i64),
    Float(f64),
    Text(String),
}

/// The number of a specifier, or the whole number a specifier takes.
///
/// The binary refuses a spec that asks for a width or a precision that does
/// not fit its own buffer, and a number too large for the limit of the tree
/// is refused the same way: the placeholder stays literal text.
fn parse_spec_number(chars: &[char]) -> Option<usize> {
    let mut value = 0usize;
    for character in chars {
        if !character.is_ascii_digit() {
            return None;
        }
        value = value
            .checked_mul(10)?
            .checked_add(character.to_digit(10)? as usize)?;
        if value > FORMAT_LIMIT {
            return None;
        }
    }
    Some(value)
}

/// Read the spec of a placeholder, after the `:` of it.
///
/// The grammar is the one of the binary: the flags `-+0 #` in any order, a
/// width, a point with a precision, and one type character. A spec that does
/// not have that shape makes the whole placeholder literal text, which is
/// what v2 does -- `{:<6d}`, `{:b}` and `{:.}` are left as they were written.
fn parse_format_spec(chars: &[char], mut at: usize) -> Option<(FormatSpec, usize)> {
    let start = at;
    let mut spec = FormatSpec {
        flags: FormatFlags::default(),
        width: 0,
        precision: None,
        kind: FormatKind::Str(None),
        letter: 's',
    };
    while at < chars.len() {
        match chars[at] {
            '-' => spec.flags.minus = true,
            '+' => spec.flags.plus = true,
            ' ' => spec.flags.space = true,
            '#' => spec.flags.hash = true,
            '0' => spec.flags.zero = true,
            _ => break,
        }
        at += 1;
    }
    let width_start = at;
    while at < chars.len() && chars[at].is_ascii_digit() {
        at += 1;
    }
    if at > width_start {
        spec.width = parse_spec_number(&chars[width_start..at])?;
    }
    if at < chars.len() && chars[at] == '.' {
        at += 1;
        let precision_start = at;
        while at < chars.len() && chars[at].is_ascii_digit() {
            at += 1;
        }
        spec.precision = Some(parse_spec_number(&chars[precision_start..at])?);
    }
    if at - start + 4 >= 52 {
        return None;
    }
    let letter = *chars.get(at)?;
    match letter {
        'd' | 'i' | 'o' | 'u' | 'x' | 'X' => {
            spec.kind = FormatKind::Int;
            spec.letter = letter;
            at += 1;
        }
        'e' | 'E' | 'f' | 'g' | 'G' | 'a' | 'A' => {
            spec.kind = FormatKind::Float;
            spec.letter = letter;
            at += 1;
        }
        'c' | 'C' => {
            spec.kind = FormatKind::Char;
            spec.letter = letter;
            at += 1;
        }
        'p' => {
            spec.kind = FormatKind::Pointer;
            spec.letter = letter;
            at += 1;
        }
        _ => {
            if "ULlTt".contains(letter) {
                spec.kind = FormatKind::Str(Some(letter.to_ascii_uppercase()));
                at += 1;
            }
            if chars.get(at) == Some(&'s') {
                at += 1;
            }
            spec.letter = 's';
        }
    }
    Some((spec, at))
}

/// The value a placeholder formats, or the failure of a parameter that is
/// not the kind its specifier wants.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a specifier that takes a
/// text takes a number and a text, and an object is refused with the kind it
/// got; a specifier that takes a number takes a number and a text that holds
/// one, and anything else is refused in the same way. The number of the
/// parameter is the number of the call, the format string included.
fn format_argument(
    spec: &FormatSpec,
    value: &Value,
    parameter: usize,
    line: u32,
) -> Result<FormatValue, RuntimeError> {
    // Measured on the binary of v2.0.19 on 2026-11-10: an argument that is the
    // absent value -- the hole between two commas, or the keyword `unset` -- is
    // the empty text in a format, whatever the specifier wants.
    if matches!(value, Value::Unset) {
        return Ok(FormatValue::Text(String::new()));
    }
    match spec.kind {
        FormatKind::Str(_) => match value {
            Value::Int(number) => Ok(FormatValue::Text(number.to_string())),
            Value::Float(number) => Ok(FormatValue::Text(crate::float_text::the_text_of(*number))),
            Value::Text(text) => Ok(FormatValue::Text(text.clone())),
            other => Err(RuntimeError {
                message: crate::runtime::requires(parameter, "Format", TypeName::String, other),
                line,
            }),
        },
        FormatKind::Float => {
            if !is_numeric_value(value) {
                return Err(RuntimeError {
                    message: crate::runtime::requires(parameter, "Format", TypeName::Number, value),
                    line,
                });
            }
            Ok(FormatValue::Float(token_to_double(value)))
        }
        _ => {
            if !is_numeric_value(value) {
                return Err(RuntimeError {
                    message: crate::runtime::requires(parameter, "Format", TypeName::Number, value),
                    line,
                });
            }
            Ok(FormatValue::Int(token_to_int64(value)))
        }
    }
}

/// Put the arguments into a pattern.
///
/// The pattern is the one of the binary, measured on 2026-11-09: `{1}` is the
/// first argument and a placeholder with no number takes the next one; `{{`
/// and `}}` are one brace of their own; and a placeholder that names an
/// argument that is not there, or whose spec is not one the binary reads, is
/// left exactly as it was written.
fn format_pattern(pattern: &str, values: &[Value], line: u32) -> Result<String, RuntimeError> {
    let chars: Vec<char> = pattern.chars().collect();
    let mut out = String::with_capacity(pattern.len() + 8);
    let mut lit = 0usize;
    let mut position = 0usize;
    let mut last_parameter = 0usize;
    loop {
        // The literal text before the next placeholder.
        let mut at = position;
        while at < chars.len() && chars[at] != '{' {
            at += 1;
        }
        if lit < at {
            out.extend(chars[lit..at].iter());
        }
        lit = at;
        if at >= chars.len() {
            break;
        }
        let mut cursor = at + 1;
        // `{{` and `}}` are a brace of their own; the other brace of the
        // pair is the one that is written.
        if cursor + 1 < chars.len()
            && (chars[cursor] == '{' || chars[cursor] == '}')
            && chars[cursor + 1] == '}'
        {
            out.push(chars[cursor]);
            cursor += 2;
            lit = cursor;
            position = cursor;
            continue;
        }
        // The number of the argument the placeholder names, or the one after
        // the last one that a placeholder named.
        let digits_start = cursor;
        while cursor < chars.len() && chars[cursor].is_ascii_digit() {
            cursor += 1;
        }
        let parameter = if cursor > digits_start {
            match parse_spec_number(&chars[digits_start..cursor]) {
                Some(number) => number,
                None => usize::MAX,
            }
        } else {
            last_parameter + 1
        };
        if parameter >= values.len() || parameter < 1 {
            // The placeholder is not one: it stays as it was written.
            position = cursor;
            continue;
        }
        // The spec, when the placeholder has one.
        let parsed = if cursor < chars.len() && chars[cursor] == ':' {
            parse_format_spec(&chars, cursor + 1)
        } else {
            Some((
                FormatSpec {
                    flags: FormatFlags::default(),
                    width: 0,
                    precision: None,
                    kind: FormatKind::Str(None),
                    letter: 's',
                },
                cursor,
            ))
        };
        let Some((spec, next)) = parsed else {
            position = cursor;
            continue;
        };
        // The kind of the value is checked before the closing brace, the way
        // the binary checks it: a parameter of the wrong kind is a failure,
        // and only a spec of the wrong shape is literal text.
        let argument = format_argument(&spec, &values[parameter], parameter + 1, line)?;
        if next >= chars.len() || chars[next] != '}' {
            position = next;
            continue;
        }
        out.push_str(&format_spec(&spec, &argument));
        last_parameter = parameter;
        lit = next + 1;
        position = next + 1;
    }
    Ok(out)
}

/// The text of one value in its specifier.
fn format_spec(spec: &FormatSpec, value: &FormatValue) -> String {
    match spec.kind {
        FormatKind::Str(custom) => {
            let mut text = match value {
                FormatValue::Text(text) => text.clone(),
                _ => String::new(),
            };
            if let Some(precision) = spec.precision {
                text = text.chars().take(precision).collect();
            }
            // The custom case is applied to the whole answer, padding and
            // all; the padding of a text is spaces or zeros, which the
            // cases leave alone.
            let fill = if spec.flags.zero && !spec.flags.minus {
                '0'
            } else {
                ' '
            };
            let text = pad_text(&text, spec.width, fill, spec.flags.minus);
            match custom {
                Some('U') => text.to_uppercase(),
                Some('L') => text.to_lowercase(),
                Some('T') => title_case(&text),
                _ => text,
            }
        }
        FormatKind::Int => format_integer(
            spec,
            match value {
                FormatValue::Int(number) => *number,
                _ => 0,
            },
        ),
        FormatKind::Char => {
            let number = match value {
                FormatValue::Int(number) => *number,
                _ => 0,
            };
            let text = character_text(spec.letter, number);
            pad_text(&text, spec.width, ' ', spec.flags.minus)
        }
        FormatKind::Pointer => {
            let number = match value {
                FormatValue::Int(number) => *number,
                _ => 0,
            };
            let text = format!("{:016X}", number as u64);
            pad_text(&text, spec.width, ' ', spec.flags.minus)
        }
        FormatKind::Float => format_float(
            spec,
            match value {
                FormatValue::Float(number) => *number,
                _ => 0.0,
            },
        ),
    }
}

/// The text of a value in a width, with the padding on the side it asks for.
fn pad_text(text: &str, width: usize, fill: char, on_the_right: bool) -> String {
    let length = text.chars().count();
    if length >= width {
        return text.to_string();
    }
    let mut out = String::with_capacity(width);
    if on_the_right {
        out.push_str(text);
        for _ in length..width {
            out.push(fill);
        }
    } else {
        for _ in length..width {
            out.push(fill);
        }
        out.push_str(text);
    }
    out
}

/// The text of a whole number in its specifier.
///
/// The flags and the width are the ones of the C library: the sign and the
/// `0x` of a hex number come before the zeros of the padding, a precision
/// makes the digits at least that many and takes the `0` flag away, and a
/// precision of zero with the number zero writes no digit at all.
fn format_integer(spec: &FormatSpec, number: i64) -> String {
    let unsigned = number as u64;
    let mut sign = String::new();
    let mut prefix = String::new();
    let mut digits: String;
    match spec.letter {
        'd' | 'i' => {
            if number < 0 {
                sign.push('-');
            } else if spec.flags.plus {
                sign.push('+');
            } else if spec.flags.space {
                sign.push(' ');
            }
            digits = number.unsigned_abs().to_string();
        }
        'u' => digits = unsigned.to_string(),
        'o' => {
            digits = format!("{unsigned:o}");
            if spec.flags.hash && !digits.starts_with('0') {
                prefix.push('0');
            }
        }
        'x' | 'X' => {
            digits = if spec.letter == 'X' {
                format!("{unsigned:X}")
            } else {
                format!("{unsigned:x}")
            };
            if spec.flags.hash && number != 0 {
                prefix.push_str(if spec.letter == 'X' { "0X" } else { "0x" });
            }
        }
        _ => digits = number.to_string(),
    }
    if let Some(precision) = spec.precision {
        if precision == 0 && number == 0 {
            digits.clear();
        } else if digits.chars().count() < precision {
            digits = format!("{}{digits}", "0".repeat(precision - digits.chars().count()));
        }
    }
    let body = format!("{sign}{prefix}{digits}");
    let length = body.chars().count();
    if length >= spec.width {
        return body;
    }
    let count = spec.width - length;
    if spec.flags.minus {
        format!("{body}{}", " ".repeat(count))
    } else if spec.flags.zero && spec.precision.is_none() {
        format!("{sign}{prefix}{}{digits}", "0".repeat(count))
    } else {
        format!("{}{body}", " ".repeat(count))
    }
}

/// One character from the number a `%c` or `%C` got.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `%c` writes the low
/// sixteen bits of the number and `%C` the low eight. The binary writes the
/// UTF-16 unit as it is, and a surrogate is not a character the tree can
/// hold: it is written with the replacement character.
fn character_text(letter: char, number: i64) -> String {
    let code = if letter == 'C' {
        (number as u64 & 0xff) as u32
    } else {
        (number as u64 & 0xffff) as u32
    };
    match char::from_u32(code) {
        Some(character) => character.to_string(),
        None => "\u{fffd}".to_string(),
    }
}

/// The text of a float in its specifier.
///
/// The types are the ones of the C library of the binary: `f` is the plain
/// form, `e` the exponent form, `g` the shorter of the two, and `a` the
/// hexadecimal form. The two values that are not numbers are written the way
/// the library writes them -- "inf", "-inf", "nan(ind)" and "-nan(ind)".
fn format_float(spec: &FormatSpec, number: f64) -> String {
    if number.is_nan() {
        let text = if number.is_sign_negative() {
            "-nan(ind)"
        } else {
            "nan(ind)"
        };
        return pad_text(text, spec.width, ' ', spec.flags.minus);
    }
    if number.is_infinite() {
        let text = if number < 0.0 { "-inf" } else { "inf" };
        return pad_text(text, spec.width, ' ', spec.flags.minus);
    }
    let negative = number.is_sign_negative();
    let magnitude = number.abs();
    let mut sign = String::new();
    if negative {
        sign.push('-');
    } else if spec.flags.plus {
        sign.push('+');
    } else if spec.flags.space {
        sign.push(' ');
    }
    let letter = spec.letter.to_ascii_lowercase();
    let uppercase = spec.letter.is_ascii_uppercase();
    let body = match letter {
        'e' => exponent_text(magnitude, spec, uppercase),
        'g' => general_text(magnitude, spec, uppercase),
        'a' => hex_float_text(magnitude, spec, uppercase),
        _ => fixed_text(magnitude, spec),
    };
    let text = format!("{sign}{body}");
    let length = text.chars().count();
    if length >= spec.width {
        return text;
    }
    let count = spec.width - length;
    if spec.flags.minus {
        format!("{text}{}", " ".repeat(count))
    } else if spec.flags.zero {
        // The zeros of the padding go after the sign.
        format!("{sign}{}{body}", "0".repeat(count))
    } else {
        format!("{}{text}", " ".repeat(count))
    }
}

/// The plain form of a float: `%f`.
fn fixed_text(magnitude: f64, spec: &FormatSpec) -> String {
    let precision = spec.precision.unwrap_or(6);
    let mut text = format!("{magnitude:.precision$}");
    if spec.flags.hash && precision == 0 {
        text.push('.');
    }
    text
}

/// The exponent form of a float: `%e` and `%E`.
fn exponent_text(magnitude: f64, spec: &FormatSpec, uppercase: bool) -> String {
    let precision = spec.precision.unwrap_or(6);
    let text = format!("{magnitude:.precision$e}");
    let (mantissa, exponent) = text
        .split_once('e')
        .expect("the exponential form of a number has an exponent");
    let exponent: i32 = exponent.parse().expect("the exponent is a number");
    let mut mantissa = mantissa.to_string();
    if spec.flags.hash && precision == 0 {
        mantissa.push('.');
    }
    format!(
        "{mantissa}{}{}{:02}",
        if uppercase { 'E' } else { 'e' },
        if exponent < 0 { '-' } else { '+' },
        exponent.abs()
    )
}

/// The shorter of the two forms of a float: `%g` and `%G`.
///
/// The number is written with the precision as the number of the significant
/// digits; the exponent form is used when the decimal exponent is less than
/// -4 or not less than the precision, and the zeros at the end of the
/// fraction are dropped -- unless the `#` flag asks for them.
fn general_text(magnitude: f64, spec: &FormatSpec, uppercase: bool) -> String {
    let precision = spec.precision.unwrap_or(6);
    let precision = if precision == 0 { 1 } else { precision };
    if magnitude == 0.0 {
        return if spec.flags.hash {
            format!("{:.*}", precision - 1, 0.0)
        } else {
            "0".to_string()
        };
    }
    let scientific = format!("{:.*e}", precision - 1, magnitude);
    let (mantissa, exponent) = scientific
        .split_once('e')
        .expect("the exponential form of a number has an exponent");
    let exponent: i32 = exponent.parse().expect("the exponent is a number");
    if exponent < -4 || exponent >= precision as i32 {
        let mut mantissa = mantissa.to_string();
        if !spec.flags.hash {
            strip_trailing_zeros(&mut mantissa);
        }
        return format!(
            "{mantissa}{}{}{:02}",
            if uppercase { 'E' } else { 'e' },
            if exponent < 0 { '-' } else { '+' },
            exponent.abs()
        );
    }
    let decimals = (precision as i32 - 1 - exponent).max(0) as usize;
    let mut text = format!("{magnitude:.decimals$}");
    if !spec.flags.hash {
        strip_trailing_zeros(&mut text);
    }
    text
}

/// Drop the zeros at the end of the fraction of a text, and the point that
/// is left with nothing after it.
fn strip_trailing_zeros(text: &mut String) {
    if !text.contains('.') {
        return;
    }
    while text.ends_with('0') {
        text.pop();
    }
    if text.ends_with('.') {
        text.pop();
    }
}

/// The hexadecimal form of a float: `%a` and `%A`.
///
/// The leading digit, the thirteen hex digits of the mantissa and the
/// exponent are the ones of the machine, written the way the library of the
/// binary writes them: `0x1.8000000000000p+0`.
fn hex_float_text(magnitude: f64, spec: &FormatSpec, uppercase: bool) -> String {
    let bits = magnitude.to_bits();
    let exponent_field = ((bits >> 52) & 0x7ff) as i64;
    let fraction = bits & 0x000f_ffff_ffff_ffff;
    let (mut leading, exponent) = if magnitude == 0.0 {
        // The zero of the library is written with the exponent zero, and
        // not with the one of the sentence of the subnormal numbers.
        (0u64, 0i64)
    } else if exponent_field == 0 {
        (0u64, -1022i64)
    } else {
        (1u64, exponent_field - 1023)
    };
    let asked = spec.precision.unwrap_or(13);
    let precision = asked.min(13);
    let shift = 52 - 4 * precision;
    let mut kept = if shift > 0 {
        (fraction + (1u64 << (shift - 1))) >> shift
    } else {
        fraction
    };
    if precision < 13 && kept == (1u64 << (4 * precision)) {
        leading += 1;
        kept = 0;
    }
    let mut digits = if precision == 0 {
        String::new()
    } else {
        format!("{kept:0width$x}", width = precision)
    };
    if asked > 13 {
        digits.push_str(&"0".repeat(asked - 13));
    }
    let mut text = format!("0x{leading}");
    if !digits.is_empty() {
        text.push('.');
        text.push_str(&digits);
    }
    text.push(if uppercase { 'P' } else { 'p' });
    text.push(if exponent < 0 { '-' } else { '+' });
    text.push_str(&format!("{}", exponent.abs()));
    if uppercase {
        text = text.to_uppercase();
    }
    text
}

// -- the parts of a `Send` --------------------------------------------------------

/// One part of what a `Send` types.
enum SendPart {
    /// Text, typed as it stands.
    Text(String),
    /// A key, with the modifiers held while it is pressed.
    Key {
        name: String,
        modifiers: Vec<String>,
    },
    /// A key that goes down and stays down.
    Down(String),
    /// A key that comes up.
    Up(String),
}

/// The mouse button a key name means, if it means one.
///
/// AutoHotkey writes a mouse button as a key: `{LButton down}` is the
/// button going down. The box has a pointer of its own, so the button
/// goes there.
fn mouse_button(name: &str) -> Option<&'static str> {
    match name.to_lowercase().as_str() {
        "lbutton" | "left" => Some("left"),
        "rbutton" | "right" => Some("right"),
        "mbutton" | "middle" => Some("middle"),
        _ => None,
    }
}

/// Split what a `Send` says into the text and the keys.
///
/// The string of a `Send` carries the AutoHotkey conventions:
///
/// * `{Name}` is a key, and `{Name down}` or `{Name up}` is that key
///   going down or coming up, on its own.
/// * `^`, `+`, `!` and `#` before a key are the modifiers: ctrl, shift,
///   alt and the super key. They apply to the key that comes next, and
///   to nothing else.
/// * A modifier on its own is a literal character, and so is one in
///   braces: `{^}` is a caret.
///
/// The text of a `Send` that is not a key is text, and it is typed as it
/// stands.
fn split_send(text: &str) -> Vec<SendPart> {
    let mut parts = Vec::new();
    let mut buffer = String::new();
    let mut modifiers: Vec<String> = Vec::new();
    let chars: Vec<char> = text.chars().collect();
    let mut index = 0usize;
    // The raw mode: everything after it is text, the braces and the
    // modifiers among them.
    let mut raw = false;

    let modifier_name = |character: char| match character {
        '^' => Some("ctrl"),
        '+' => Some("shift"),
        '!' => Some("alt"),
        '#' => Some("super"),
        _ => None,
    };

    while index < chars.len() {
        if raw {
            buffer.push(chars[index]);
            index += 1;
            continue;
        }
        // A modifier before the key it belongs to.
        if let Some(name) = modifier_name(chars[index]) {
            let next = chars.get(index + 1);
            let is_literal = match next {
                None => true,
                Some(next) => next.is_whitespace(),
            };
            if !is_literal {
                modifiers.push(name.to_string());
                index += 1;
                continue;
            }
        }
        // A character with modifiers waiting for it is a key.
        if !modifiers.is_empty() {
            parts.push(SendPart::Key {
                name: chars[index].to_string(),
                modifiers: core::mem::take(&mut modifiers),
            });
            index += 1;
            continue;
        }
        if chars[index] == '{' {
            if let Some(offset) = chars[index + 1..].iter().position(|c| *c == '}') {
                let close = index + 1 + offset;
                let name: String = chars[index + 1..close].iter().collect();
                if !buffer.is_empty() {
                    parts.push(SendPart::Text(core::mem::take(&mut buffer)));
                }
                // `{^}` is a literal character, not a modifier.
                if name.chars().count() == 1
                    && modifier_name(name.chars().next().unwrap()).is_some()
                {
                    parts.push(SendPart::Text(name));
                } else if name.eq_ignore_ascii_case("raw") {
                    // The raw mode: the rest of the text is text.
                    raw = true;
                } else {
                    let (key, state, times) = match name.rsplit_once(' ') {
                        Some((key, "down")) => (key.to_string(), Some(true), 1),
                        Some((key, "up")) => (key.to_string(), Some(false), 1),
                        Some((key, times))
                            if !times.is_empty() && times.chars().all(|c| c.is_ascii_digit()) =>
                        {
                            (key.to_string(), None, times.parse::<usize>().unwrap_or(1))
                        }
                        _ => (name.clone(), None, 1),
                    };
                    match state {
                        Some(true) => parts.push(SendPart::Down(key)),
                        Some(false) => parts.push(SendPart::Up(key)),
                        None => {
                            let modifiers = core::mem::take(&mut modifiers);
                            for _ in 0..times {
                                parts.push(SendPart::Key {
                                    name: key.clone(),
                                    modifiers: modifiers.clone(),
                                });
                            }
                        }
                    }
                }
                index = close + 1;
                continue;
            }
        }
        buffer.push(chars[index]);
        index += 1;
    }
    if !buffer.is_empty() {
        parts.push(SendPart::Text(buffer));
    }
    parts
}

// -- the functions the ks dialect adds --------------------------------------------
//
// The table of them is in `extensions.rs`, and the dialect of KeySharp is
// the one that carries it: the v2.0.19 does not see any of these names.

/// `ATan2(Y, X)`: the arc whose tangent is the quotient, in the quadrant
/// the signs name.
pub(crate) fn ks_atan2(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let y = number_argument(values, 0, line, "ATan2")?;
    let x = number_argument(values, 1, line, "ATan2")?;
    Ok(Value::Float(crate::runtime::atan2(y, x)))
}

/// `Sinh`, `Cosh` and `Tanh`: the hyperbolic sine, cosine and tangent.
pub(crate) fn ks_hyperbolic(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    let name = match variant {
        0 => "Sinh",
        1 => "Cosh",
        _ => "Tanh",
    };
    let number = number_argument(values, 0, line, name)?;
    let result = match variant {
        0 => crate::runtime::sinh(number),
        1 => crate::runtime::cosh(number),
        _ => crate::runtime::tanh(number),
    };
    Ok(Value::Float(result))
}

/// `RandomSeed(Seed)`: reinitialize the random number generator with the
/// seed the script named, and answer nothing.
pub(crate) fn ks_random_seed(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let seed = number_argument(values, 0, line, "RandomSeed")?;
    rt.seed_the_random(seed as i64);
    Ok(Value::Text(String::new()))
}

/// `ReplaceLineEndings(Str, EndOfLine?)`: make every line ending of the
/// text the one the caller names.
///
/// The endings are the seven the documentation of KeySharp lists: the two
/// of Windows, the two of the classic Mac and the Unix, the form feed, the
/// next line of Unicode, and the two separators of Unicode.
pub(crate) fn ks_replace_line_endings(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let _ = line;
    let text = text_of(values, 0);
    let ending = if values.len() > 1 {
        text_of(values, 1)
    } else {
        "\n".to_string()
    };
    let mut out = String::new();
    let mut characters = text.chars().peekable();
    while let Some(character) = characters.next() {
        let is_ending = match character {
            '\r' => {
                // The two of Windows go together, and the pair is one
                // ending and not two.
                if characters.peek() == Some(&'\n') {
                    characters.next();
                }
                true
            }
            '\n' | '\u{000C}' | '\u{0085}' | '\u{2028}' | '\u{2029}' => true,
            _ => false,
        };
        if is_ending {
            out.push_str(&ending);
        } else {
            out.push(character);
        }
    }
    Ok(Value::Text(out))
}

/// `FileFullPath(Filename)`: the full path to the file.
pub(crate) fn ks_file_full_path(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    rt.desktop()
        .full_path(&path)
        .map(Value::Text)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `FileCreateTemp()`: make an empty temporary file, and answer where it
/// is.
pub(crate) fn ks_file_create_temp(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    rt.desktop()
        .create_temp_file()
        .map(Value::Text)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `OutputDebugLine(Text)`: the same as `OutputDebug`, with the line break
/// at the end.
pub(crate) fn ks_output_debug_line(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    rt.desktop()
        .output_debug(&(text + "\n"))
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `Collect()`: ask for the memory of the unreachable objects to be
/// reclaimed.
///
/// The objects of this runtime are reclaimed the moment the last reference
/// to them goes away, so there is nothing to ask for: the answer is the
/// empty text, the way an answer of no value is.
pub(crate) fn ks_collect(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(String::new()))
}

/// The row of a built-in of the dialect: the table of the v2.0.19 first,
/// and the rows the dialect adds after it.
pub(crate) fn the_builtin_in_the_dialect(
    dialect: &'static dyn crate::dialect::Dialect,
    wanted: &str,
) -> Option<&'static Builtin> {
    dialect
        .builtins()
        .iter()
        .find(|builtin| builtin.name.to_lowercase() == wanted)
        .or_else(|| dialect.the_builtin_of_the_extension(wanted))
}

/// `Throw(Value)`: throw the value, the way the `throw` statement does.
///
/// The documentation of KeySharp: the value is thrown, and the catch
/// that takes it holds it. The value waits for the caller of the
/// built-in, and the built-in fails the statement with it.
pub(crate) fn ks_throw(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first().cloned().unwrap_or(Value::Unset);
    rt.throw_the_value(value);
    Err(RuntimeError {
        message: "the value was thrown".to_string(),
        line,
    })
}

/// `Props(Value)`: the properties of a value, as an iterator.
///
/// The documentation of KeySharp: the iterator gives the name of a
/// property, and the value of a property that is a descriptor is the
/// value of the property itself. A value that is not an object has no
/// properties of its own, and the tree refuses it with the kind of it,
/// the way KeySharp refuses it.
pub(crate) fn ks_props(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first().cloned().unwrap_or(Value::Unset);
    let Some(pairs) = rt.the_properties_of_a_value(&value) else {
        let kind = rt.the_type_of(&value);
        return Err(RuntimeError {
            message: format!("Parameter #1 of Props requires an Object, but received a {kind}."),
            line,
        });
    };
    Ok(crate::classes::enumerator::make(
        pairs,
        crate::classes::enumerator::Alone::TheKey,
    ))
}

/// `IsComponentAvailable(Capability)`: whether the unit of the dialect is
/// there.
///
/// The documentation of KeySharp: the unit is the `parser` or the
/// `compiler` of the first party, and the aliases `parsing` and
/// `compilation` are accepted. This tree has the parser -- it reads the
/// scripts -- and it has no compiler: it runs what it reads, and it never
/// turns a script into another language. A name that is not one of them
/// is refused, the way KeySharp refuses it.
pub(crate) fn ks_is_component_available(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = text_of(values, 0).to_lowercase();
    let answer = match name.as_str() {
        "parser" | "parsing" => 1,
        "compiler" | "compilation" => 0,
        _ => {
            return Err(RuntimeError {
                message: format!("Unknown capability \"{name}\"."),
                line,
            });
        }
    };
    Ok(Value::Int(answer))
}

/// `ValidateScript(Code)`: check a script without running it.
///
/// The documentation of KeySharp: the code is the path of a script file
/// when a file of that name is there, and the source of a script
/// otherwise; the answer is an object with `IsValid`, `Errors` and
/// `Warnings`, and the errors carry the file, the line and the column.
///
/// The tree has a parser, and it reads the script with the parser of the
/// dialect that runs: the script is checked, and it is not run.
pub(crate) fn ks_validate_script(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let code = text_of(values, 0);
    // A file of that name, when the machine has one, and the source
    // otherwise.
    let (source, file) = match rt.desktop().read_file(&code) {
        Ok(lines) => (lines.join("\n"), Some(code.clone())),
        Err(_) => (code.clone(), None),
    };
    let parsed = crate::parser::parse_with(&source, rt.dialect());
    let mut errors: Vec<Value> = Vec::new();
    let valid = match parsed {
        Ok(_) => 1,
        Err(failure) => {
            let place = match &file {
                Some(file) => format!("{file}:{}:{}", failure.line, failure.column),
                None => format!("{}:{}", failure.line, failure.column),
            };
            errors.push(Value::Text(format!("{place}: {}", failure.message)));
            0
        }
    };
    let object = crate::classes::object("object");
    let Value::Object(object) = object else {
        return Err(RuntimeError {
            message: "this runtime cannot make an object".to_string(),
            line: _line,
        });
    };
    object.borrow_mut().put("IsValid", Value::Int(valid));
    object.borrow_mut().put(
        "Errors",
        crate::classes::array::construct(&errors, rt, _line).map_err(|failure| RuntimeError {
            message: crate::runtime::the_message_of(&failure),
            line: _line,
        })?,
    );
    object.borrow_mut().put(
        "Warnings",
        crate::classes::array::construct(&[], rt, _line).map_err(|failure| RuntimeError {
            message: crate::runtime::the_message_of(&failure),
            line: _line,
        })?,
    );
    Ok(Value::Object(object))
}

/// `GetKeyInfo`: what the tree knows of a key.
///
/// The answer is an object with the virtual key, the scan code, the name,
/// the modifiers and the prefix of the key -- and the number zero when the
/// name does not resolve, the way KeySharp answers it. The resolution is
/// the one of `GetKeyName`, `GetKeyVK` and `GetKeySC`, so the four agree:
/// the name is the name v2 gives the key, the virtual key is the one of
/// Windows and the scan code is the one of the Linux input event.
///
/// The modifier symbols at the front of the name go into the modifiers
/// and the prefix, the way KeySharp reads them. The layout parameter is
/// refused with the reason: the tree has one keyboard layout, and a
/// parameter it cannot honour is never ignored.
pub(crate) fn ks_get_key_info(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 1 && !matches!(values[1], Value::Unset) {
        return Err(RuntimeError {
            message: "this tree has one keyboard layout, and the layout parameter of GetKeyInfo is not carried".to_string(),
            line,
        });
    }
    let text = match values.first() {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    let (prefix, modifiers, rest) = crate::keys::the_modifier_prefix_of(&text);
    let vk = crate::settings::key_code(rest);
    let sc = crate::settings::key_event(rest) as u32;
    let name = crate::settings::key_name(rest);
    // KeySharp answers the number zero when the name does not resolve, and
    // a key with no code and no name is not a key.
    if (vk == 0 && sc == 0) || name.is_empty() {
        return Ok(Value::Int(0));
    }
    Ok(crate::classes::keyinfo::the_key_info(
        vk, sc, &name, modifiers, &prefix,
    ))
}

/// `ObjGetDataPtr`: the address of the structured data of an object.
///
/// The instance that `ObjCreateWithDataPtr` or `Struct.At` made carries
/// the address it borrows, and the answer is it. Any other object is
/// answered the way KeySharp answers it -- "Operation failed." -- and a
/// value that is not an object is refused with the reason.
pub(crate) fn ks_obj_get_data_ptr(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value,
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    let Value::Object(object) = value else {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ObjGetDataPtr", TypeName::Object, value),
            line,
        });
    };
    match object
        .borrow()
        .value_of(crate::classes::typed::THE_DATA_POINTER)
    {
        Some(address) => Ok(address),
        None => Err(RuntimeError {
            message: "Operation failed.".to_string(),
            line,
        }),
    }
}

/// `ObjGetDataSize`: the size of the structured data of an object.
///
/// The instance of a typed class answers the size of its field, and any
/// other object answers zero -- the answer of KeySharp for an object
/// that is not a struct.
pub(crate) fn ks_obj_get_data_size(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value,
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    let Value::Object(object) = value else {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ObjGetDataSize", TypeName::Object, value),
            line,
        });
    };
    let class = object.borrow().class.clone();
    let size = match crate::classes::typed::the_class_of(&class) {
        Some((_, size, _)) => size,
        None => 0,
    };
    Ok(Value::Int(size))
}

/// `ObjSetDataPtr`: the address an instance borrows, set.
///
/// An object that borrows no address is refused with the answer of
/// KeySharp: "Operation failed.".
pub(crate) fn ks_obj_set_data_ptr(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value,
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    let Value::Object(object) = value else {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ObjSetDataPtr", TypeName::Object, value),
            line,
        });
    };
    let address = match values.get(1).and_then(|value| value.to_number()) {
        Some(number) => number as i64,
        None => {
            let second = values.get(1).unwrap_or(&Value::Unset);
            return Err(RuntimeError {
                message: crate::runtime::requires(2, "ObjSetDataPtr", TypeName::Number, second),
                line,
            });
        }
    };
    let borrows = object
        .borrow()
        .value_of(crate::classes::typed::THE_DATA_POINTER)
        .is_some();
    if !borrows {
        return Err(RuntimeError {
            message: "Operation failed.".to_string(),
            line,
        });
    }
    object
        .borrow_mut()
        .put(crate::classes::typed::THE_DATA_POINTER, Value::Int(address));
    Ok(Value::Text(String::new()))
}

/// `ObjCreateWithDataPtr`: the instance of a class that borrows an
/// address.
///
/// The class is the value of a typed class, and anything else is refused
/// with the message of KeySharp: "Invalid class.". The address below
/// 65536 that is not the null one is refused with the parameter message
/// of KeySharp, and a typed number -- whose field would live in the
/// memory -- is refused with the reason: the tree has no memory to read
/// a field from.
pub(crate) fn ks_obj_create_with_data_ptr(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let invalid = || RuntimeError {
        message: "Invalid class.".to_string(),
        line,
    };
    let name = match values.first() {
        Some(Value::Object(object)) => match object.borrow().value_of(crate::runtime::CLASS_NAME) {
            Some(Value::Text(name)) => name,
            _ => return Err(invalid()),
        },
        _ => return Err(invalid()),
    };
    let class = match crate::classes::typed::the_class_of(&name) {
        Some((_, _, _)) => name.to_lowercase(),
        None => return Err(invalid()),
    };
    let address = match values.get(1).and_then(|value| value.to_number()) {
        Some(number) => number as i64,
        None => {
            let second = values.get(1).unwrap_or(&Value::Unset);
            return Err(RuntimeError {
                message: crate::runtime::requires(
                    2,
                    "ObjCreateWithDataPtr",
                    TypeName::Number,
                    second,
                ),
                line,
            });
        }
    };
    match crate::classes::typed::the_view_at(&class, address, "ObjCreateWithDataPtr", 2, line) {
        Some(Ok(value)) => {
            let _ = rt;
            Ok(value)
        }
        Some(Err(error)) => Err(error),
        None => Err(invalid()),
    }
}

/// `ShowDebug`: the debug tab of the main window.
///
/// The runner of this tree has no main window, and the ShowDebug of
/// KeySharp does nothing when the script has none -- the call of it is
/// the null-conditional in its source. The answer is the empty text,
/// the answer of a headless run of KeySharp: the tree has no debug tab,
/// and it says nothing that is false about one.
pub(crate) fn ks_show_debug(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(String::new()))
}

/// The pieces of a command line: the blanks separate, and the double
/// quotes group, the way KeySharp splits the options of `RunScript`.
fn the_pieces_of_a_command_line(text: &str) -> Vec<String> {
    let mut pieces: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut quoted = false;
    let mut has = false;
    for character in text.chars() {
        match character {
            '"' => {
                quoted = !quoted;
                has = true;
            }
            other => {
                if other.is_whitespace() && !quoted {
                    if has {
                        pieces.push(current.clone());
                        current.clear();
                        has = false;
                    }
                    continue;
                }
                current.push(other);
                has = true;
            }
        }
    }
    if has {
        pieces.push(current);
    }
    pieces
}

/// `Mail`: send a mail through an SMTP server.
///
/// The recipients are one text or an array of them, and the options are
/// a Map with `host` and `from` required -- SMTP has no default for
/// either -- and `cc`, `bcc`, `replyto`, `attachments` and `headers`
/// optional. An unknown key is refused with the message of KeySharp that
/// lists the accepted ones, and the port rides on the host after the
/// rightmost colon that is not inside a bracketed IPv6 literal.
///
/// The validation is the dialect's and runs on every machine; the
/// sending is the machine's, and a desktop that cannot send says so --
/// a mail that was not sent is never reported as sent.
pub(crate) fn ks_mail(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let failure = |message: String| RuntimeError { message, line };
    // The recipients: one text or an array of them, none of them empty.
    let mut to: Vec<String> = Vec::new();
    let first = values.first().unwrap_or(&Value::Unset);
    match first {
        Value::Text(text) => {
            if !text.is_empty() {
                to.push(text.clone());
            }
        }
        // The array of the script is an object of the class, and the
        // module that owns it is the one that hands over the items: the
        // built-in may not reach into the state of the array.
        Value::Object(object) if object.borrow().class == "array" => {
            for (index, item) in crate::classes::array::the_items(first).iter().enumerate() {
                match item {
                    Value::Text(text) if !text.is_empty() => to.push(text.clone()),
                    Value::Text(_) => {
                        return Err(failure(format!("Recipient {} is empty.", index + 1)));
                    }
                    other => {
                        return Err(failure(format!(
                            "Recipient {} is {}; every recipient must be a String.",
                            index + 1,
                            other.the_kind()
                        )));
                    }
                }
            }
        }
        other => return Err(failure(expected_type(TypeName::String, other.type_name()))),
    }
    if to.is_empty() {
        return Err(failure("At least one recipient is required.".to_string()));
    }
    let subject = text_of(values, 1);
    let body = text_of(values, 2);

    let mut host: Option<String> = None;
    let mut port: u16 = 25;
    let mut from: Option<String> = None;
    let mut reply_to: Option<String> = None;
    let mut cc: Vec<String> = Vec::new();
    let mut bcc: Vec<String> = Vec::new();
    let mut attachments: Vec<String> = Vec::new();
    let mut headers: Vec<(String, String)> = Vec::new();

    if let Some(value) = values.get(3) {
        if !matches!(value, Value::Unset) {
            let pairs = match crate::classes::map::the_pairs(value) {
                Some(pairs) => pairs,
                None => return Err(failure("The options of Mail must be a Map.".to_string())),
            };
            for (key, val) in pairs {
                let item = key.to_text();
                if item.is_empty() {
                    continue;
                }
                match item.to_lowercase().as_str() {
                    "host" => {
                        let Value::Text(text) = val else {
                            return Err(failure(format!(
                                "The \"{item}\" option must be a String."
                            )));
                        };
                        // The rightmost colon only, and never one inside a
                        // bracketed IPv6 literal.
                        let mut named = text.clone();
                        if let Some(colon) = text.rfind(':') {
                            if text.rfind(']').is_none_or(|bracket| bracket < colon) {
                                let (left, right) = text.split_at(colon + 1);
                                let number = right.trim().parse::<i64>();
                                match number {
                                    Ok(number) if (1..=65535).contains(&number) => {
                                        port = number as u16;
                                        named = left[..left.len() - 1].to_string();
                                    }
                                    _ => {
                                        return Err(failure(format!(
                                            "\"{right}\" is not a port between 1 and 65535."
                                        )));
                                    }
                                }
                            }
                        }
                        if named.is_empty() {
                            return Err(failure(format!("The \"{item}\" option names no server.")));
                        }
                        host = Some(named);
                    }
                    "from" | "replyto" => {
                        let Value::Text(text) = val else {
                            return Err(failure(format!(
                                "The \"{item}\" option must be a String."
                            )));
                        };
                        if item.eq_ignore_ascii_case("from") {
                            from = Some(text.clone());
                        } else {
                            reply_to = Some(text.clone());
                        }
                    }
                    "cc" | "bcc" | "attachments" => {
                        let wanted = item.to_lowercase();
                        let list = match &val {
                            Value::Text(text) => vec![text.clone()],
                            Value::Object(inner) if inner.borrow().class == "array" => {
                                let mut out: Vec<String> = Vec::new();
                                for entry in crate::classes::array::the_items(&val) {
                                    let Value::Text(text) = entry else {
                                        return Err(failure(format!(
                                            "The \"{item}\" option must be a String or an Array of them."
                                        )));
                                    };
                                    out.push(text.clone());
                                }
                                out
                            }
                            _ => {
                                return Err(failure(format!(
                                    "The \"{item}\" option must be a String or an Array of them."
                                )));
                            }
                        };
                        match wanted.as_str() {
                            "cc" => cc = list,
                            "bcc" => bcc = list,
                            _ => attachments = list,
                        }
                    }
                    "headers" => {
                        let pairs = match crate::classes::map::the_pairs(&val) {
                            Some(pairs) => pairs,
                            None => return Err(failure(
                                "The \"headers\" option must be a Map of header names and values."
                                    .to_string(),
                            )),
                        };
                        for (name, value) in pairs {
                            let name = name.to_text();
                            if name.is_empty() {
                                continue;
                            }
                            headers.push((name, value.to_text()));
                        }
                    }
                    _ => {
                        return Err(failure(format!(
                            "Unknown option \"{item}\". Accepted keys are host, from, cc, bcc, replyto, attachments and headers."
                        )));
                    }
                }
            }
        }
    }

    let Some(host) = host else {
        return Err(failure(
            "The \"host\" option is required: there is no default SMTP server.".to_string(),
        ));
    };
    let Some(from) = from else {
        return Err(failure(
            "The \"from\" option is required: SMTP has no sender to fall back on.".to_string(),
        ));
    };

    let message = crate::desktop::MailMessage {
        to,
        cc,
        bcc,
        subject,
        body,
        from,
        reply_to,
        attachments,
        headers,
        host,
        port,
    };
    rt.desktop()
        .send_mail(&message)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `RunScript`: run a script in a process of its own.
///
/// The code is the path of a file when the machine has one and the
/// source otherwise, the way CompileScript reads it, and the compile of
/// the tree is the parser of the dialect that runs: a script that does
/// not parse is never launched. The program -- the runner of this run by
/// default -- is started with the script on its standard input, and the
/// answer is the ScriptProcess of the pid.
///
/// The `name` parameter names the generated program of KeySharp, and the
/// tree generates no program of its own: the parameter is refused with
/// the reason. The callback of an asynchronous run is refused too: the
/// tree does not watch a process it does not wait for, and a callback
/// that is never called is a lie. With no asynchronous flag the run is
/// waited for, and the callback is called with the process before the
/// answer.
pub(crate) fn ks_run_script(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let failure = |message: String| RuntimeError { message, line };
    let code = text_of(values, 0);
    // A file of that name, when the machine has one, and the source
    // otherwise -- the reading of CompileScript.
    let source = match rt.desktop().read_file(&code) {
        Ok(lines) => lines.join("\n"),
        Err(_) => code.clone(),
    };
    // The compile of the tree is the parser of the dialect: KeySharp
    // throws a compilation as an Error, and a script that does not parse
    // is never launched.
    if let Err(failure_of_the_parse) = crate::parser::parse_with(&source, rt.dialect()) {
        return Err(failure(format!(
            "the script does not compile: {}:{}: {}",
            failure_of_the_parse.line, failure_of_the_parse.column, failure_of_the_parse.message
        )));
    }
    let asynchronous = values.get(1).map(|value| value.truthy()).unwrap_or(false);
    // The callback takes the process alone -- the `CheckedCallback(
    // callback, 1)` of KeySharp -- and the tree calls it by the name of
    // the function, the way the callbacks of the exit are called. A
    // function with no name to be called by is refused with the answer
    // of KeySharp.
    let callback_name: Option<String> = match values.get(2) {
        None => None,
        Some(Value::Unset) => None,
        Some(value) => match value {
            Value::Object(object) if object.borrow().class == "func" => {
                match object.borrow().value_of("name") {
                    Some(Value::Text(text)) if !text.is_empty() => Some(text.clone()),
                    _ => return Err(failure("Invalid callback function.".to_string())),
                }
            }
            _ => {
                return Err(failure(format!(
                    "This value of type \"{}\" has no method named \"Call\".",
                    value.type_name().name()
                )));
            }
        },
    };
    // The name of the generated program of KeySharp has nothing to name
    // here: the tree launches the runner itself and compiles nothing.
    if let Some(value) = values.get(3) {
        if !matches!(value, Value::Unset) && !value.to_text().is_empty() {
            return Err(failure(
                "this tree generates no program of its own: the name parameter of RunScript has nothing to name".to_string(),
            ));
        }
    }
    let executable = match values.get(4) {
        Some(value) if !matches!(value, Value::Unset) && !value.to_text().is_empty() => {
            value.to_text()
        }
        _ => rt
            .desktop()
            .executable()
            .map_err(|reason| desktop_failure(reason, line))?,
    };
    // The options: the arguments of the launched process. --define and
    // --include select what is compiled, and the tree compiles with its
    // parser alone: the two are refused with the reason.
    let mut arguments: Vec<String> = Vec::new();
    if let Some(value) = values.get(5) {
        if !matches!(value, Value::Unset) {
            let pieces = match value {
                Value::Object(object) if object.borrow().class == "array" => {
                    crate::classes::array::the_items(value)
                        .iter()
                        .map(|item| item.to_text())
                        .collect()
                }
                other => the_pieces_of_a_command_line(&other.to_text()),
            };
            for piece in pieces {
                let lowered = piece.to_lowercase();
                if lowered.starts_with("--define") || lowered.starts_with("--include") {
                    return Err(failure(
                        "this tree compiles with its parser alone: --define and --include have no compilation to be applied to".to_string(),
                    ));
                }
                arguments.push(piece);
            }
        }
    }
    if asynchronous && callback_name.is_some() {
        return Err(failure(
            "this tree does not watch a process it does not wait for: the callback of an asynchronous RunScript cannot be called".to_string(),
        ));
    }
    let pid = if asynchronous {
        rt.desktop()
            .launch_with_stdin(&executable, &arguments, &source, "")
            .map_err(|reason| desktop_failure(reason, line))? as i64
    } else {
        let (pid, _, _, _) = rt
            .desktop()
            .run_with_stdin(&executable, &arguments, &source, "")
            .map_err(|reason| desktop_failure(reason, line))?;
        pid as i64
    };
    let process = match crate::classes::scriptprocess::construct(
        "scriptprocess",
        &[Value::Int(pid)],
        rt,
        line,
    ) {
        Some(Ok(value)) => value,
        Some(Err(failure_of_the_object)) => {
            return Err(RuntimeError {
                message: crate::runtime::the_message_of(&failure_of_the_object),
                line,
            });
        }
        None => {
            return Err(failure(
                "the object of the process could not be made".to_string(),
            ));
        }
    };
    if let Some(name) = &callback_name {
        // The run was waited for: the process is over, and the callback
        // is called with it, the way KeySharp calls it after the exit.
        rt.call_named(
            name,
            core::slice::from_ref(&process),
            line,
            crate::runtime::Route::Written,
        )
        .map_err(|failure_of_the_call| RuntimeError {
            message: crate::runtime::the_message_of(&failure_of_the_call),
            line,
        })?;
    }
    Ok(process)
}

/// `GetKeyboardLayout`: the name of the keyboard layout of the machine.
///
/// The name is the one the platform gives it, and the empty text when the
/// platform has none to give -- the answer of KeySharp. A machine that
/// cannot say at all is refused with the reason.
pub(crate) fn ks_get_keyboard_layout(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = rt
        .desktop()
        .keyboard_layout_name()
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(name))
}

/// `ClipCursor`: confine the pointer to a rectangle, or release it.
///
/// No argument releases the confinement and four arguments set it, the
/// way KeySharp does it; any other count is refused with its message.
/// The corners may come in any order: the rectangle is normalized here,
/// and the far edges are exclusive. A value that is not a number is
/// refused with the reason -- KeySharp answers its default object for
/// one, and a wrong value answered silently is the worst outcome.
pub(crate) fn ks_clip_cursor(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let rect = if values.is_empty() {
        None
    } else if values.len() == 4 && !values.iter().any(|value| matches!(value, Value::Unset)) {
        let mut numbers = [0i64; 4];
        for (index, slot) in numbers.iter_mut().enumerate() {
            match values[index].to_number() {
                Some(number) => *slot = number as i64,
                None => {
                    return Err(RuntimeError {
                        message: crate::runtime::requires(
                            index + 1,
                            "ClipCursor",
                            TypeName::Number,
                            &values[index],
                        ),
                        line,
                    });
                }
            }
        }
        let [x1, y1, x2, y2] = numbers;
        Some((x1.min(x2), y1.min(y2), x1.max(x2), y1.max(y2)))
    } else {
        return Err(RuntimeError {
            message: "ClipCursor requires either zero or four coordinates.".to_string(),
            line,
        });
    };
    rt.desktop()
        .clip_cursor(rect)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `WinFromPoint`: the window at a point of the screen.
///
/// The point that is not given is the position of the pointer, the way
/// KeySharp reads it from GetCursorPos. The answer is the identity of the
/// window, and zero when no window is at the point. A machine that cannot
/// say which window is at a point is refused with the reason: zero means
/// "no window", and not "I do not know".
pub(crate) fn ks_win_from_point(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let mut given: [Option<i64>; 2] = [None, None];
    for index in 0..values.len().min(2) {
        if matches!(values[index], Value::Unset) {
            continue;
        }
        match values[index].to_number() {
            Some(number) => given[index] = Some(number as i64),
            None => {
                return Err(RuntimeError {
                    message: crate::runtime::requires(
                        index + 1,
                        "WinFromPoint",
                        TypeName::Number,
                        &values[index],
                    ),
                    line,
                });
            }
        }
    }
    let (x, y) = match (given[0], given[1]) {
        (Some(x), Some(y)) => (x, y),
        _ => {
            let (px, py) = rt
                .desktop()
                .mouse_position()
                .map_err(|e| desktop_failure(e, line))?;
            (given[0].unwrap_or(px), given[1].unwrap_or(py))
        }
    };
    let answer = rt
        .desktop()
        .the_window_at(x, y)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(answer.unwrap_or(0)))
}

/// `RequestCapabilities(Capabilities...)`: what the machine can do.
///
/// The documentation of KeySharp: the answer is an object with a property
/// for every capability -- `Granted`, `Denied`, `NotApplicable` or
/// `Unsupported` -- and an `IsGranted` that says whether every capability
/// that was asked for is granted.
///
/// The tree has no store of permissions: what it answers is what it can
/// do. The capability of the keyboard and of the pointer is the one of
/// the input, and the capability of the screen is the one of the capture:
/// both are there, and both are granted. The names that the tree does
/// not know are unsupported.
/// The names of the capabilities of the windows of a desktop.
///
/// They are the names of `WinGetCapability`, and they are the ones the
/// documentation of the tree carries.
pub(crate) const THE_WINDOW_CAPABILITIES: [&str; 8] = [
    "AlwaysOnTopGet",
    "AlwaysOnTopSet",
    "WindowEnabledGet",
    "ControlEnabledGet",
    "WindowList",
    "WindowActivate",
    "WindowMinimize",
    "WindowClose",
];

/// The window that a window function of the ks dialect asks about.
///
/// The window that is not there is refused with the reason of v2, and the
/// desktop that cannot list the windows is refused with its own.
fn ks_the_window_of(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
) -> Result<crate::desktop::WindowInfo, RuntimeError> {
    let windows = rt
        .desktop()
        .windows()
        .map_err(|e| desktop_failure(e, line))?;
    match the_window_in(&windows, values.first())? {
        Some(window) => Ok(window),
        None => Err(no_window(line)),
    }
}

/// `WinGetAlwaysOnTop`: whether a window is above the others.
///
/// The machine that cannot say is refused with the reason: the tree does
/// not answer `0` for a state it does not know.
pub(crate) fn ks_win_get_always_on_top(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let window = ks_the_window_of(rt, values, line)?;
    let answer = rt
        .desktop()
        .always_on_top(&window)
        .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(true) => Ok(Value::Int(1)),
        Some(false) => Ok(Value::Int(0)),
        None => Err(RuntimeError {
            message: "the desktop of this run cannot say whether the window is above the others."
                .into(),
            line,
        }),
    }
}

/// `WinGetEnabled`: whether a window is enabled.
///
/// The machine that cannot say is refused with the reason.
pub(crate) fn ks_win_get_enabled(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let window = ks_the_window_of(rt, values, line)?;
    let answer = rt
        .desktop()
        .window_enabled(&window)
        .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(true) => Ok(Value::Int(1)),
        Some(false) => Ok(Value::Int(0)),
        None => Err(RuntimeError {
            message: "the desktop of this run cannot say whether the window is enabled.".into(),
            line,
        }),
    }
}

/// `WinGetCapability`: whether this desktop has a capability.
///
/// The name that is not one of the capabilities of the tree is refused with
/// the reason.
/// `WinSetAlwaysOnTop`: put a window above the others, or take it from there.
///
/// The first parameter is the state, the way v2 writes it: `1` enables, `0`
/// disables, `-1` toggles, and the texts `Toggle`, `On` and `Off` are the
/// same three. The second is the title of the window, and the empty one
/// asks about the active window.
///
/// The machine that cannot say whether the window is above the others cannot
/// toggle it either, and the machine that cannot do the change says so: a
/// change that did not happen is never reported as a change that did.
pub(crate) fn win_set_always_on_top(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The other parameters of v2 are the text of the window and the two
    // exclusions, and the desktop of the box has none of them.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let asked = match values.first() {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    // The state that is not given is the toggle, the way v1 wrote it.
    let wanted = match asked.trim().to_lowercase().as_str() {
        "1" | "on" | "true" => Some(true),
        "0" | "off" | "false" => Some(false),
        "-1" | "toggle" | "" => None,
        other => {
            return Err(RuntimeError {
                message: format!(
                    "the first parameter of WinSetAlwaysOnTop is not one of 1, 0, -1, Toggle, On or Off: {other}"
                ),
                line,
            });
        }
    };
    let windows = rt
        .desktop()
        .windows()
        .map_err(|e| desktop_failure(e, line))?;
    let Some(window) = the_window_in(&windows, values.get(1))? else {
        return Err(no_window(line));
    };
    let on = match wanted {
        Some(on) => on,
        None => match rt
            .desktop()
            .always_on_top(&window)
            .map_err(|e| desktop_failure(e, line))?
        {
            Some(current) => !current,
            None => {
                return Err(RuntimeError {
                    message:
                        "the desktop of this run cannot say whether the window is above the others, so it cannot toggle it."
                            .into(),
                    line,
                })
            }
        },
    };
    rt.desktop()
        .set_always_on_top(&window, on)
        .map_err(|e| desktop_failure(e, line))?;
    // The answer of a command that answers nothing is the empty text.
    Ok(Value::Text(String::new()))
}

pub(crate) fn ks_win_get_capability(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let asked = match values.first() {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    if !THE_WINDOW_CAPABILITIES
        .iter()
        .any(|name| name.eq_ignore_ascii_case(asked.trim()))
    {
        return Err(RuntimeError {
            message: format!(
                "WinGetCapability: {asked} is not one of the capabilities of the tree."
            ),
            line,
        });
    }
    let capabilities = rt.desktop().window_capabilities();
    let answer = capabilities
        .iter()
        .any(|name| name.eq_ignore_ascii_case(asked.trim()));
    Ok(Value::Int(if answer { 1 } else { 0 }))
}

pub(crate) fn ks_request_capabilities(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let mut asked: Vec<String> = Vec::new();
    for value in values {
        for part in value
            .to_text()
            .split(|character: char| character == ',' || character.is_whitespace())
        {
            if !part.is_empty() {
                asked.push(part.to_lowercase());
            }
        }
    }
    if asked.is_empty() {
        asked.push("inputmonitoring".to_string());
        asked.push("screencapture".to_string());
    }
    let mut granted = true;
    let object = crate::classes::object("object");
    let Value::Object(object) = object else {
        return Err(RuntimeError {
            message: "this runtime cannot make an object".to_string(),
            line,
        });
    };
    for name in asked {
        let answer = match name.as_str() {
            "inputmonitoring" | "screencapture" => "Granted",
            _ => "Unsupported",
        };
        if answer != "Granted" {
            granted = false;
        }
        object
            .borrow_mut()
            .put(&name, Value::Text(answer.to_string()));
    }
    object
        .borrow_mut()
        .put("IsGranted", Value::Int(if granted { 1 } else { 0 }));
    let _ = rt;
    Ok(Value::Object(object))
}

/// `ComObjGet`: the object of a COM class.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: an empty string and an
/// Integer where the class string is wanted both throw "(0x80070057) The
/// parameter is incorrect.". This platform has no COM class registry to
/// resolve a class string against, so every call answers the same throw.
pub(crate) fn com_obj_get(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "(0x80070057) The parameter is incorrect.".to_string(),
        line,
    })
}

/// `ComObjActive`: the COM object that a program has running.
///
/// Measured on the same day: a class string that no running program owns
/// throws "(0x800401F3) Invalid class string". This platform has no running
/// object table to look one up in, so every call answers the same throw.
pub(crate) fn com_obj_active(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "(0x800401F3) Invalid class string".to_string(),
        line,
    })
}

/// `ComObjType`: the kind of a COM object.
///
/// Measured on the same day: an Integer where a COM object is wanted
/// answers the EMPTY TEXT -- not a failure. This platform has no COM
/// objects, so the empty text is the whole contract.
pub(crate) fn com_obj_type(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(String::new()))
}

/// `ComObjQuery`: an interface of a COM object.
///
/// Measured on the same day: an Integer where a COM object is wanted throws
/// "Parameter #1 of ComObjQuery is invalid." -- a wording of its own, and
/// not the one its siblings use.
pub(crate) fn com_obj_query(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match values.first() {
        Some(Value::Object(_)) => Err(RuntimeError {
            message:
                "this platform has no COM: there is no object model for an interface to be asked of"
                    .to_string(),
            line,
        }),
        _ => Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "ComObjQuery"),
            line,
        }),
    }
}

/// `ListLines(Setting)`: the log of the lines that the script runs.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `ListLines Setting`, where the setting is a **number** -- a text throws
/// "Parameter #1 of ListLines requires a Number, but received a String." --
/// and the answer is the **previous** setting: one when the log was on, and
/// zero when it was off. The log is on by default, and the built-in variable
/// `A_ListLines` carries it and may be written.
///
/// Without the setting the call shows the history of the lines in the window
/// of the debugger of v2 and answers the previous setting too. This runtime
/// has no debugger, so it answers the number and keeps the log.
pub(crate) fn list_lines(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The setting that is there now is the one the call answers.
    let before = match crate::settings::value_of("listlines") {
        Some(Ok(Value::Int(on))) => Value::Int(on),
        _ => Value::Int(1),
    };
    let Some(setting) = values.first() else {
        return Ok(before);
    };
    if !matches!(setting, Value::Int(_) | Value::Float(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ListLines", TypeName::Number, setting),
            line,
        });
    }
    let on = setting.to_number_lenient() != 0.0;
    match crate::settings::write_of("listlines", &Value::Int(on as i64)) {
        Some(Ok(_)) => Ok(before),
        Some(Err(why)) => Err(RuntimeError { message: why, line }),
        None => Err(RuntimeError {
            message: "the log of the lines is not carried.".to_string(),
            line,
        }),
    }
}

/// The kinds of a value that the v2 carries.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: a kind that is not one
/// of these throws "Parameter #2 of RegWrite is invalid.".
const REGISTRY_KINDS: [&str; 5] = [
    "REG_SZ",
    "REG_EXPAND_SZ",
    "REG_MULTI_SZ",
    "REG_DWORD",
    "REG_BINARY",
];

/// The failure of the machine when a value has no name.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: a name of a value that
/// is not given -- and one that is given empty -- throws "(161) The specified
/// path is invalid.".
const NO_VALUE_NAME: &str = "(161) The specified path is invalid.";

/// The failure of the machine when a key or a value is not there.
const NOTHING_THERE: &str = "(2) The system cannot find the file specified.";

/// The name of the key of a registry call, and the failure when it is not
/// there.
///
/// The place of the key is not the same in every call: `RegWrite` takes the
/// value and the kind first, so its key is the third parameter.
///
/// The hive is **required**: measured on the binary of v2.0.19 on 2026-11-11,
/// `RegCreateKey("Software\X")` throws "Parameter #1 of RegCreateKey is
/// invalid." -- and so does the registry of another machine, whose name
/// comes first and is not a hive.
fn the_key_of(
    values: &[Value],
    index: usize,
    name: &str,
    line: u32,
) -> Result<String, RuntimeError> {
    let key = values
        .get(index)
        .map(|value| value.to_text())
        .unwrap_or_default()
        .trim()
        .to_string();
    let hive = key.split('\\').next().unwrap_or("").trim().to_uppercase();
    let known = matches!(
        hive.as_str(),
        "HKCU"
            | "HKEY_CURRENT_USER"
            | "HKLM"
            | "HKEY_LOCAL_MACHINE"
            | "HKU"
            | "HKEY_USERS"
            | "HKCR"
            | "HKEY_CLASSES_ROOT"
            | "HKCC"
            | "HKEY_CURRENT_CONFIG"
    );
    if !known {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(index + 1, name),
            line,
        });
    }
    Ok(key)
}

/// The name of the value of a registry call.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: a name that is not
/// given, and one that is given empty, throw "(161) The specified path is
/// invalid." -- so the default value of a key is out of reach.
fn the_value_name_of(values: &[Value], index: usize, line: u32) -> Result<String, RuntimeError> {
    let name = values
        .get(index)
        .map(|value| value.to_text())
        .unwrap_or_default()
        .trim()
        .to_string();
    if name.is_empty() {
        return Err(RuntimeError {
            message: NO_VALUE_NAME.to_string(),
            line,
        });
    }
    Ok(name)
}

/// `RegCreateKey`: make a key of the registry of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: it answers the empty
/// text and makes the key; a key that is not given throws "Parameter #1 of
/// RegCreateKey must not be omitted in this case."; and a key with no hive
/// throws "Parameter #1 of RegCreateKey is invalid.".
pub(crate) fn reg_create_key(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.is_empty() {
        return Err(RuntimeError {
            message: "Parameter #1 of RegCreateKey must not be omitted in this case.".to_string(),
            line,
        });
    }
    let key = the_key_of(values, 0, "RegCreateKey", line)?;
    rt.desktop()
        .registry_create_key(&key)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `RegWrite`: write a value into the registry of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `RegWrite Value, ValueType, KeyName, ValueName` -- the **value comes
/// first** and the type is the second -- and the call answers the empty
/// text. A key that is not given throws "Parameter #3 of RegWrite must not
/// be omitted in this case." -- the key is checked before the kind -- a
/// kind that is not one of the five throws "Parameter #2 of RegWrite is
/// invalid.", a name of a value that is not given throws "(161) The
/// specified path is invalid.", and the key is **made** when it is not
/// there -- with its ancestors.
pub(crate) fn reg_write(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() < 3 {
        return Err(RuntimeError {
            message: "Parameter #3 of RegWrite must not be omitted in this case.".to_string(),
            line,
        });
    }
    let kind = text_of(values, 1).trim().to_uppercase();
    if !REGISTRY_KINDS.contains(&kind.as_str()) {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(2, "RegWrite"),
            line,
        });
    }
    let key = the_key_of(values, 2, "RegWrite", line)?;
    let name = the_value_name_of(values, 3, line)?;
    // A value of REG_DWORD is a number, and the registry holds it as one.
    let value = if kind == "REG_DWORD" {
        format!("{}", number_argument(values, 0, line, "RegWrite")? as i64)
    } else {
        text_of(values, 0)
    };
    rt.desktop()
        .registry_write(&key, &name, &kind, &value)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `RegRead`: the value of the registry of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `RegRead KeyName, ValueName, Default`; a key that is not given throws
/// "Parameter #1 of RegRead must not be omitted in this case."; a name of a
/// value that is not given throws "(161) The specified path is invalid."; a
/// value that is not there throws "(2) The system cannot find the file
/// specified." unless a default is given, which is then the answer.
pub(crate) fn reg_read(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.is_empty() {
        return Err(RuntimeError {
            message: "Parameter #1 of RegRead must not be omitted in this case.".to_string(),
            line,
        });
    }
    let key = the_key_of(values, 0, "RegRead", line)?;
    let name = the_value_name_of(values, 1, line)?;
    match rt
        .desktop()
        .registry_value(&key, &name)
        .map_err(|reason| desktop_failure(reason, line))?
    {
        Some((kind, value)) => {
            // A value of REG_DWORD is a number, and the registry holds it as
            // one: the binary answers 42 for the 42 that was written.
            if kind == "REG_DWORD" {
                Ok(match value.parse::<i64>() {
                    Ok(number) => Value::Int(number),
                    Err(_) => Value::Text(value),
                })
            } else {
                Ok(Value::Text(value))
            }
        }
        // The value is not there: the default is the answer when there is
        // one, and the machine's failure is the answer when there is not.
        None => match values.get(2) {
            Some(default) => Ok(default.clone()),
            None => Err(RuntimeError {
                message: NOTHING_THERE.to_string(),
                line,
            }),
        },
    }
}

/// `RegDelete`: remove a value of the registry of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `RegDelete KeyName, ValueName` and the call answers the empty text; a
/// name of a value that is not given throws "(161) The specified path is
/// invalid.".
pub(crate) fn reg_delete(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.is_empty() {
        return Err(RuntimeError {
            message: "Parameter #1 of RegDelete must not be omitted in this case.".to_string(),
            line,
        });
    }
    let key = the_key_of(values, 0, "RegDelete", line)?;
    let name = the_value_name_of(values, 1, line)?;
    rt.desktop()
        .registry_delete(&key, &name)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `RegDeleteKey`: remove a key of the registry of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `RegDeleteKey KeyName` and the call answers the empty text; a key that is
/// not there throws "(2) The system cannot find the file specified.".
pub(crate) fn reg_delete_key(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.is_empty() {
        return Err(RuntimeError {
            message: "Parameter #1 of RegDeleteKey must not be omitted in this case.".to_string(),
            line,
        });
    }
    let key = the_key_of(values, 0, "RegDeleteKey", line)?;
    rt.desktop()
        .registry_delete_key(&key)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `TraySetIcon(IconFile, IconNumber)`: the icon of the script.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the call answers the
/// empty text, and the built-in variables carry the icon afterwards --
/// `A_IconFile` answers the path of the file and `A_IconNumber` the number
/// of the icon in it. An icon that cannot be loaded throws **"Can't load
/// icon."**, and the icon of the script is not changed. A call with no
/// argument answers the empty text and changes nothing.
///
/// The path that the binary answers is the canonical one of Windows, which
/// is in upper case; this tree answers the path as the script wrote it,
/// because the path of a file is the path of the machine it is on.
pub(crate) fn tray_set_icon(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(file) = values.first() else {
        // A call with no argument changes nothing.
        return Ok(Value::Text(String::new()));
    };
    let file = file.to_text();
    let number = values
        .get(1)
        .map(|value| value.to_number().unwrap_or(1.0) as i64);
    let options = crate::desktop::PictureOptions {
        width: None,
        height: None,
        icon: number,
    };
    // The icon is loaded before it is set: an icon that cannot be loaded is
    // the failure of the call, and the icon of the script stays as it was.
    // The binary does not tell the reasons apart -- every icon that cannot
    // be loaded is "Can't load icon.".
    let image = rt.desktop().load_picture(&file, &options).ok().flatten();
    if image.is_none() {
        return Err(RuntimeError {
            message: "Can't load icon.".to_string(),
            line,
        });
    }
    let canonical = rt
        .desktop()
        .canonical_path(&file)
        .unwrap_or_else(|_| file.clone());
    rt.set_the_icon_of_the_script(canonical.clone(), number.unwrap_or(1));
    // The tray of the session shows the icon, when the session has one: a
    // desktop with no tray is not a failure of the call -- the icon of the
    // script is set either way. A tray that refused is said in the report.
    let refused = rt.desktop().tray_set_icon(&canonical).err();
    if let Some(reason) = refused {
        rt.note(format!(
            "the tray of the session did not take the icon: {reason}"
        ));
    }
    Ok(Value::Text(String::new()))
}

/// `CallbackFree(Callback)`: let a callback of the machine go.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the first parameter
/// wants a number, and a text throws "Parameter #1 of CallbackFree requires
/// a Number, but received a String."; and every number throws "Parameter #1
/// of CallbackFree is invalid.", because the only callback it would let go
/// is one that it made itself.
///
/// This runtime makes no callback for the machine, so every number is the
/// invalid one.
pub(crate) fn callback_free(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let first = values.first().cloned().unwrap_or(Value::Int(0));
    if !matches!(first, Value::Int(_) | Value::Float(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "CallbackFree", TypeName::Number, &first),
            line,
        });
    }
    Err(RuntimeError {
        message: "Parameter #1 of CallbackFree is invalid.".to_string(),
        line,
    })
}

/// `ComCall(Method, Object, RetType)`: call a method of a COM object.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `ComCall Method, Object, RetType` -- the object is the second parameter
/// and the type of the return is the third. The type is looked at **first**:
/// a type that the dialect does not know throws "Invalid return type." --
/// and the ones it knows are the types of a native call, with the address
/// of the value written after them ("Int*" and "IntP" are read too).
/// The object is looked at after it, and anything that is not a COM object
/// throws "Parameter #2 of ComCall is invalid.".
///
/// The COM objects are objects of the component model of Windows, and this
/// platform has no component model: there is no object of COM to call, so
/// the call answers the failure of the object.
pub(crate) fn com_call(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The type of the return is looked at before the object.
    if let Some(kind) = values.get(2) {
        if crate::dll::parse_type(&kind.to_text()).is_none() {
            return Err(RuntimeError {
                message: "Invalid return type.".to_string(),
                line,
            });
        }
    }
    Err(RuntimeError {
        message: "Parameter #2 of ComCall is invalid.".to_string(),
        line,
    })
}

/// `ComObjFromPtr(Ptr)`: the COM object of a pointer.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the first parameter
/// wants a number, and a text throws "Parameter #1 of ComObjFromPtr
/// requires a Number, but received a String."; the **null** pointer throws
/// "Parameter #1 of ComObjFromPtr is invalid.".
///
/// A pointer that is not the null one makes the **binary hang** -- measured
/// on 2026-11-11, the run was killed after ten seconds on
/// `ComObjFromPtr(12345)`. There is no answer of it to match, and this
/// runtime does not wait forever either.
pub(crate) fn com_obj_from_ptr(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let first = values.first().cloned().unwrap_or(Value::Int(0));
    if !matches!(first, Value::Int(_) | Value::Float(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "ComObjFromPtr", TypeName::Number, &first),
            line,
        });
    }
    let pointer = first.to_number_lenient() as i64;
    if pointer == 0 {
        return Err(RuntimeError {
            message: "Parameter #1 of ComObjFromPtr is invalid.".to_string(),
            line,
        });
    }
    Err(RuntimeError {
        message: "the binary of v2.0.19 hangs on this call -- measured on 2026-11-11 -- and this runtime does not wait forever: the COM objects are objects of the component model of Windows, and this platform has no component model.".to_string(),
        line,
    })
}

/// `IL_Create(Width, Height, Grow)`: make a list of images.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: it answers the number
/// that names the list it made.
pub(crate) fn il_create(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Int(rt.make_an_image_list()))
}

/// `IL_Add(ImageList, IconFile, IconIndex)`: put an image in a list of images.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: it answers the place of
/// the image in the list -- one for the first -- and **zero** when the image
/// could not be loaded: a file that is not there, and a file that is not an
/// image, are both zero and not a failure. The list is looked at first: a
/// number that names no list is zero as well, and the **null** handle is
/// refused with "Parameter #1 of IL_Add is invalid.". A first parameter
/// that is not a number throws "Parameter #1 of IL_Add requires a Number,
/// but received a String.".
pub(crate) fn il_add(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let first = values.first().cloned().unwrap_or(Value::Int(0));
    if !matches!(first, Value::Int(_) | Value::Float(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "IL_Add", TypeName::Number, &first),
            line,
        });
    }
    let list = number_of(values, 0) as i64;
    if list == 0 {
        return Err(RuntimeError {
            message: "Parameter #1 of IL_Add is invalid.".to_string(),
            line,
        });
    }
    let file = text_of(values, 1);
    // The image is the one of the machine: the same path that `LoadPicture`
    // takes, with the icon that the call names.
    let icon = values
        .get(2)
        .map(|value| value.to_number().unwrap_or(1.0) as i64);
    let options = crate::desktop::PictureOptions {
        width: None,
        height: None,
        icon,
    };
    // An image that cannot be loaded is zero, and not a failure -- the
    // binary answers zero for a file that is not there and for a file that
    // is not an image.
    let image = rt.desktop().load_picture(&file, &options).ok().flatten();
    let Some(image) = image else {
        return Ok(Value::Int(0));
    };
    // A list that is not there is zero as well.
    Ok(Value::Int(
        rt.put_an_image_in_a_list(list, image as i64).unwrap_or(0),
    ))
}

/// `IL_Destroy(ImageList)`: take a list of images away.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: it answers **one** when
/// the list was there and **zero** when it was not -- the null handle among
/// them -- and a first parameter that is not a number throws "Parameter #1
/// of IL_Destroy requires a Number, but received a String.".
pub(crate) fn il_destroy(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let first = values.first().cloned().unwrap_or(Value::Int(0));
    if !matches!(first, Value::Int(_) | Value::Float(_)) {
        return Err(RuntimeError {
            message: crate::runtime::requires(1, "IL_Destroy", TypeName::Number, &first),
            line,
        });
    }
    let list = number_of(values, 0) as i64;
    Ok(Value::Int(rt.take_an_image_list(list) as i64))
}

/// `SetCapsLockState`: the state of the lamp of the Caps Lock.
pub(crate) fn set_caps_lock_state(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    set_lock_state(rt, values, line, "CapsLock")
}

/// `SetNumLockState`: the state of the lamp of the Num Lock.
pub(crate) fn set_num_lock_state(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    set_lock_state(rt, values, line, "NumLock")
}

/// `SetScrollLockState`: the state of the lamp of the Scroll Lock.
pub(crate) fn set_scroll_lock_state(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    set_lock_state(rt, values, line, "ScrollLock")
}

/// The failure v2 gives when a window is looked for and is not there.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `WinGetID` and
/// `WinGetClass` fail with it, while `WinGetList` answers an empty array and
/// `WinGetCount` answers the zero.
const TARGET_WINDOW: &str = "Target window not found.";

/// The failure of a question about a control, when the window is there.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `ControlGetText("x", "A")`
/// -- a window that is there -- fails with this, and not with an empty text.
const TARGET_CONTROL: &str = "Target control not found.";

/// The window that a `WinGet*` command asks about.
///
/// The parameters after the first are the text of the window and the two
/// exclusions, and the desktop of the box has none of them.
fn window_target(
    values: &[Value],
    line: u32,
) -> Result<(String, crate::desktop::TitleMatch), RuntimeError> {
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    Ok((text_of(values, 0), crate::settings::title_match_mode()))
}

/// `CaretGetPos`: where the caret of the text is.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: with a focused Edit it
/// answers 1 and writes the place of the caret into the two variables of the
/// caller; with no window, or nothing focused that holds a caret, it answers
/// 0 and the variables stay as they were. A call with no variables at all
/// still answers the one or the zero.
pub(crate) fn caret_get_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let caret = rt
        .desktop()
        .gui_caret()
        .map_err(|e| desktop_failure(e, line))?;
    match caret {
        Some((x, y)) => {
            if let Some(value) = values.first() {
                rt.write_reference(value, Value::Int(x));
            }
            if let Some(value) = values.get(1) {
                rt.write_reference(value, Value::Int(y));
            }
            Ok(Value::Int(1))
        }
        None => Ok(Value::Int(0)),
    }
}

/// The wording of a drive that is not there, measured on the binary of
/// v2.0.19 on 2026-11-10: the readers of a drive -- the label and the serial
/// -- throw the path wording, and the operations on the hardware -- eject,
/// lock, unlock and retract -- throw the file wording. Both are the code of
/// the system in front of what it says.
const DRIVE_PATH: &str = "(3) The system cannot find the path specified.";

const DRIVE_FILE: &str = "(2) The system cannot find the file specified.";

/// `DriveGetLabel`: the label of the drive that a path is on.
pub(crate) fn drive_get_label(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_label(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(label) => Ok(Value::Text(label)),
        None => Err(RuntimeError {
            message: DRIVE_PATH.to_string(),
            line,
        }),
    }
}

/// `DriveGetSerial`: the serial of the drive that a path is on.
///
/// Measured on the binary of the same day: `DriveGetSerial` of a drive that
/// is there answers a whole number -- the volume serial of Windows. The
/// serial of a Linux drive is the string of the hardware, so a serial that
/// reads as a whole number is answered as one and the rest rides as text.
pub(crate) fn drive_get_serial(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_serial(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(serial) => match serial.parse::<i64>() {
            Ok(number) => Ok(Value::Int(number)),
            Err(_) => Ok(Value::Text(serial)),
        },
        None => Err(RuntimeError {
            message: DRIVE_PATH.to_string(),
            line,
        }),
    }
}

/// `DriveGetList`: the drives of the machine.
///
/// Measured on the binary of the same day: `DriveGetList` answers the drive
/// letters run together -- a letter is one character, so no separator is
/// needed -- and a call with an argument throws "Parameter #1 of
/// DriveGetList is invalid.". A drive of this platform is a device name,
/// which is more than one character, so the names ride apart on newlines.
pub(crate) fn drive_get_list(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !values.is_empty() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "DriveGetList"),
            line,
        });
    }
    let drives = rt
        .desktop()
        .drive_list()
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(drives.join("\n")))
}

/// `DriveGetStatusCD`: the status of the drive a path is on, when it is a
/// CD or DVD reader.
///
/// Measured on the binary of the same day: `DriveGetStatusCD` of a drive
/// that is not a reader throws "Failed".
pub(crate) fn drive_get_status_cd(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_status_cd(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(status) => Ok(Value::Text(status)),
        None => Err(RuntimeError {
            message: "Failed".to_string(),
            line,
        }),
    }
}

/// The shape of the hardware operations -- eject, lock, unlock and retract:
/// the drive has to be there first, and a drive that is not there throws the
/// file wording. Measured on the binary of the same day.
fn the_drive_for_the_operation(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
) -> Result<String, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_label(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(_) => Ok(path),
        None => Err(RuntimeError {
            message: DRIVE_FILE.to_string(),
            line,
        }),
    }
}

/// `DriveEject`: eject the drive of a path.
pub(crate) fn drive_eject(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = the_drive_for_the_operation(rt, values, line)?;
    rt.desktop()
        .drive_eject(&path)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `DriveLock`: lock the drive of a path against removal.
pub(crate) fn drive_lock(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = the_drive_for_the_operation(rt, values, line)?;
    rt.desktop()
        .drive_lock(&path)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `DriveUnlock`: unlock the drive of a path.
pub(crate) fn drive_unlock(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = the_drive_for_the_operation(rt, values, line)?;
    rt.desktop()
        .drive_unlock(&path)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `DriveRetract`: spin the drive of a path down.
pub(crate) fn drive_retract(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = the_drive_for_the_operation(rt, values, line)?;
    rt.desktop()
        .drive_retract(&path)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `DriveSetLabel`: write a new label on the drive of a path.
///
/// Measured on the binary of the same day: `DriveSetLabel` of a drive that
/// is not there throws the path wording, like the readers do.
pub(crate) fn drive_set_label(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_label(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(_) => {}
        None => {
            return Err(RuntimeError {
                message: DRIVE_PATH.to_string(),
                line,
            });
        }
    }
    let label = text_of(values, 1);
    rt.desktop()
        .drive_set_label(&path, &label)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `WinGetID`: the identifier of the first window that matches.
pub(crate) fn win_get_id(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (title, mode) = window_target(values, line)?;
    let windows = rt
        .desktop()
        .matching_windows(&title, mode)
        .map_err(|e| desktop_failure(e, line))?;
    match windows.first() {
        Some(window) => {
            rt.remember_the_last_window(&window.id);
            Ok(Value::Text(window.id.clone()))
        }
        None => Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        }),
    }
}

/// `WinGetIDLast()`: the identifier of the window a `Win*` call last found.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: after `WinGetID()` finds a
/// window, `WinGetIDLast()` answers that window's id, and with no `Win*` call
/// before it, it answers "Target window not found." (round 222). On this
/// platform a window id is the text the compositor gives, so that is what is
/// answered. `WinExist` cannot set it: its desktop call says only whether a
/// window is there, not which one, and the fake desktop of the language tests
/// carries that call alone.
pub(crate) fn win_get_id_last(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match rt.the_last_window() {
        Some(id) => Ok(Value::Text(id.to_string())),
        None => Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        }),
    }
}

/// `WinGetClass`: the class of the first window that matches.
pub(crate) fn win_get_class(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (title, mode) = window_target(values, line)?;
    let windows = rt
        .desktop()
        .matching_windows(&title, mode)
        .map_err(|e| desktop_failure(e, line))?;
    match windows.first() {
        Some(window) => Ok(Value::Text(window.class.clone())),
        None => Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        }),
    }
}

/// `WinGetList`: the identifiers of every window that matches.
///
/// A title that matches nothing is an empty array, and not a failure: measured
/// on the binary of v2.0.19 on 2026-11-09.
///
/// The answer is an array of v2 and not a bare list of values, because a
/// script reads the `Length` of it and the places of it, and a list carries
/// neither.
pub(crate) fn win_get_list(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (title, mode) = window_target(values, line)?;
    let windows = rt
        .desktop()
        .matching_windows(&title, mode)
        .map_err(|e| desktop_failure(e, line))?;
    let ids: Vec<Value> = windows
        .iter()
        .map(|window| Value::Text(window.id.clone()))
        .collect();
    match crate::classes::construct("array", &ids, rt, line) {
        Some(result) => result.map_err(|failure| crate::runtime::as_error(failure, line)),
        None => Ok(Value::List(ids)),
    }
}

/// `WinGetCount`: how many windows match.
pub(crate) fn win_get_count(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (title, mode) = window_target(values, line)?;
    let windows = rt
        .desktop()
        .matching_windows(&title, mode)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(windows.len() as i64))
}

/// `WinGetPos`: where the window is and how big it is.
pub(crate) fn win_get_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    window_geometry_into(rt, values, line, "WinGetPos")
}

/// `WinGetClientPos`: the same place, of the part of the window that the
/// program draws in.
///
/// A Wayland client does not draw its own frame -- the compositor does -- so
/// the geometry that the compositor reports is the window the user sees, and
/// it is the answer of both commands here. On Windows the two differ by the
/// frame: measured on the binary of v2.0.19 on 2026-11-09, the frame was
/// 819,479 1787x1262 and the client area 827,479 1771x1254.
pub(crate) fn win_get_client_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    window_geometry_into(rt, values, line, "WinGetClientPos")
}

/// `ControlGetText`: the text of a control of a window.
///
/// The control is found by its name and the window by its title, through the
/// accessibility layer, because that is the only description of the controls of
/// a window that a Wayland session keeps.
///
/// **A control that the application does not publish answers the empty text,
/// and that is not a failure.** Measured on the box on 2026-11-09 with a dump of
/// the whole tree: `zenity` publishes its dialog -- the `Name` of the window is
/// the title of the window, and it is a `dialog` -- and publishes no name and no
/// text for anything inside it. Any client of AT-SPI sees the same nothing. The
/// walk therefore answers what the tree holds, which for that program is the
/// empty text.
pub(crate) fn control_get_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The parameters after the control and the window are the text of the
    // window and the two exclusions, and they are not carried yet.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let control = text_of(values, 0);
    let title = text_of(values, 1);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window of a control is found by its title, and an empty title is not carried yet.".into(),
            line,
        });
    }
    match rt
        .desktop()
        .control_text(&control, &title)
        .map_err(|e| desktop_failure(e, line))?
    {
        crate::desktop::ControlAnswer::Found(text) => Ok(Value::Text(text)),
        crate::desktop::ControlAnswer::NoSuchWindow => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
        crate::desktop::ControlAnswer::NoSuchControl => Err(RuntimeError {
            message: TARGET_CONTROL.into(),
            line,
        }),
    }
}

/// `ControlGetVisible` and `ControlGetEnabled`: a flag of a control of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09 against a window of its own
/// making: both answer the integer **1** for a control that is there and visible
/// or enabled, and the two failures are the two of `ControlGetText`. The variant
/// is the name -- this one is `ControlGetVisible` and the other is
/// `ControlGetEnabled`.
pub(crate) fn control_flag(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    // The parameters after the control and the window are the text of the
    // window and the two exclusions, and they are not carried yet.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let control = text_of(values, 0);
    let title = text_of(values, 1);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window of a control is found by its title, and an empty title is not carried yet.".into(),
            line,
        });
    }
    let answer = if variant == 0 {
        rt.desktop().control_visible(&control, &title)
    } else {
        rt.desktop().control_enabled(&control, &title)
    }
    .map_err(|e| desktop_failure(e, line))?;
    match answer {
        crate::desktop::ControlFlag::Yes => Ok(Value::Int(1)),
        crate::desktop::ControlFlag::No => Ok(Value::Int(0)),
        crate::desktop::ControlFlag::NoSuchWindow => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
        crate::desktop::ControlFlag::NoSuchControl => Err(RuntimeError {
            message: TARGET_CONTROL.into(),
            line,
        }),
    }
}

/// `ControlSetText`: write a text into a control of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the **empty
/// text**, and the text of the control is the new one afterwards. The
/// parameters are the *new text first*, then the control, then the title --
/// which is the order of v2 and not the order of `ControlGetText`.
pub(crate) fn control_set_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The parameters after the three are the text of the window and the two
    // exclusions, and they are not carried yet.
    if values.len() > 3 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let text = text_of(values, 0);
    let control = text_of(values, 1);
    let title = text_of(values, 2);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window of a control is found by its title, and an empty title is not carried yet.".into(),
            line,
        });
    }
    match rt
        .desktop()
        .control_set_text(&control, &title, &text)
        .map_err(|e| desktop_failure(e, line))?
    {
        crate::desktop::ControlEdit::Done => Ok(Value::Text(String::new())),
        crate::desktop::ControlEdit::NoSuchWindow => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
        crate::desktop::ControlEdit::NoSuchControl => Err(RuntimeError {
            message: TARGET_CONTROL.into(),
            line,
        }),
    }
}

/// `ControlClick` and `ControlFocus`: an act on a named control of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: both answer the **empty
/// text**, and the two failures are the two of `ControlGetText`. The variant is
/// the name -- this one is `ControlClick` and the other is `ControlFocus`.
pub(crate) fn control_act(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    // The parameters after the control and the window are the button, the
    // count, the options, the text of the window and the two exclusions, and
    // they are not carried yet.
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the parameters after the control and the window are not carried yet.".into(),
            line,
        });
    }
    let control = text_of(values, 0);
    let title = text_of(values, 1);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window of a control is found by its title, and an empty title is not carried yet.".into(),
            line,
        });
    }
    let answer = if variant == 0 {
        rt.desktop().control_click(&control, &title)
    } else {
        rt.desktop().control_focus(&control, &title)
    }
    .map_err(|e| desktop_failure(e, line))?;
    match answer {
        crate::desktop::ControlEdit::Done => Ok(Value::Text(String::new())),
        crate::desktop::ControlEdit::NoSuchWindow => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
        crate::desktop::ControlEdit::NoSuchControl => Err(RuntimeError {
            message: TARGET_CONTROL.into(),
            line,
        }),
    }
}

/// `ControlSendText`: type a text into a control of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the answer is the **empty
/// text**, and the control holds the text afterwards. The parameters are the
/// text first, then the control, then the title.
pub(crate) fn control_send_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 3 {
        return Err(RuntimeError {
            message:
                "the parameters after the text, the control and the window are not carried yet."
                    .into(),
            line,
        });
    }
    let text = text_of(values, 0);
    let control = text_of(values, 1);
    let title = text_of(values, 2);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window of a control is found by its title, and an empty title is not carried yet.".into(),
            line,
        });
    }
    match rt
        .desktop()
        .control_send_text(&control, &title, &text)
        .map_err(|e| desktop_failure(e, line))?
    {
        crate::desktop::ControlEdit::Done => Ok(Value::Text(String::new())),
        crate::desktop::ControlEdit::NoSuchWindow => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
        crate::desktop::ControlEdit::NoSuchControl => Err(RuntimeError {
            message: TARGET_CONTROL.into(),
            line,
        }),
    }
}

/// `WinGetPID`: the process of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the **Integer** of
/// the process, and a title that no window has is "Target window not found.".
///
/// The chain on this desktop is the accessibility bus: the registry names the
/// applications, a window is a child of one and its `Name` is its title, and the
/// bus answers the `PID` of a name -- measured on the box on 2026-11-09.
pub(crate) fn win_get_pid(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let title = text_of(values, 0);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window is found by its title, and an empty title is not carried yet."
                .into(),
            line,
        });
    }
    match rt
        .desktop()
        .window_pid(&title)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(pid) => Ok(Value::Int(pid)),
        None => Err(RuntimeError {
            message: TARGET_WINDOW.into(),
            line,
        }),
    }
}

/// `WinGetProcessName` and `WinGetProcessPath`: the program of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the name is the file name of
/// the program (`AutoHotkey64.exe`) and the path is the whole of it, and a title
/// that no window has is "Target window not found.".
///
/// They ride the chain of `WinGetPID`: the window's title names an application on
/// the accessibility bus, the bus answers its process, and the process table
/// answers the name and the path -- which the `Processes` capability already
/// reads.
pub(crate) fn win_get_process(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 1 {
        return Err(RuntimeError {
            message: "the text of the window and the exclusions are not carried yet.".into(),
            line,
        });
    }
    let title = text_of(values, 0);
    if title.is_empty() {
        return Err(RuntimeError {
            message: "the window is found by its title, and an empty title is not carried yet."
                .into(),
            line,
        });
    }
    let pid = match rt
        .desktop()
        .window_pid(&title)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(pid) => pid,
        None => {
            return Err(RuntimeError {
                message: TARGET_WINDOW.into(),
                line,
            });
        }
    };
    let number = pid.to_string();
    let answer = if variant == 0 {
        rt.desktop().process_name(Some(&number))
    } else {
        rt.desktop().process_path(Some(&number))
    }
    .map_err(|e| desktop_failure(e, line))?;
    match answer {
        Some(text) => Ok(Value::Text(text)),
        None => Err(RuntimeError {
            message: "Target process not found.".into(),
            line,
        }),
    }
}

/// `Persistent`: whether the script keeps running after its auto-execute ends.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the Integer **0**.
/// A script of this runtime is persistent by its nature -- the run is one script
/// from its first line to its last, and there is no message loop for it to stay
/// for -- so the answer is the zero v2 gives and the setting changes nothing.
pub(crate) fn persistent(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Int(0))
}

/// `ListVars`: show the variables of the script.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the **empty
/// text**, and it does not block. A window of v2 shows the variables; this
/// runtime has one channel for what a script shows -- the `output` of the
/// report, which is where a `MsgBox` goes -- so a line for each variable goes
/// there, and the answer is the empty text.
///
/// **The names are the keys the runtime keeps**, which are the names of the
/// script without their case. A script that writes `MyVar` is listed as `myvar`,
/// and that is a difference from v2 that is written down rather than hidden.
pub(crate) fn list_vars(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    for (name, value) in rt.variable_names() {
        rt.push_output(format!("{name}[{value}]"));
    }
    Ok(Value::Text(String::new()))
}

/// The four bounds of a monitor, written into the references of the call.
fn the_monitor_bounds_into(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    name: &str,
) -> Result<Value, RuntimeError> {
    // The bounds are the parameters after the number, and they are given by
    // reference: the second parameter of the call is the first of them.
    for index in 0..4 {
        let Some(value) = values.get(index + 1) else {
            continue;
        };
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(index + 2, name, "a VarRef", value),
                line,
            });
        }
    }
    let (index, monitors) = the_monitor_of(rt, values, name, line)?;
    let Some(monitor) = the_monitor_at(&monitors, index) else {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, name),
            line,
        });
    };
    let places = [monitor.left, monitor.top, monitor.right, monitor.bottom];
    for (index, place) in places.iter().enumerate() {
        if values.get(index + 1).is_some() {
            rt.write_reference(&values[index + 1], Value::Int(*place));
        }
    }
    Ok(Value::Int(1))
}

/// The drive that a path is on, and the failure v2 gives when it is not there.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `DriveGetSpaceFree` of a
/// drive that is not there is a failure, while `DriveGetType` of one answers
/// the empty text -- the two commands disagree about the same question.
fn the_drive_of(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    name: &str,
) -> Result<crate::desktop::DriveSpace, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_space(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(space) => Ok(space),
        None => Err(RuntimeError {
            message: format!("{name}: the drive of {path} is not there."),
            line,
        }),
    }
}

/// `DriveGetSpaceFree`: the free space of a drive, in megabytes.
pub(crate) fn drive_get_space_free(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Int(
        the_drive_of(rt, values, line, "DriveGetSpaceFree")?.free,
    ))
}

/// `DriveGetCapacity`: the capacity of a drive, in megabytes.
pub(crate) fn drive_get_capacity(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Int(
        the_drive_of(rt, values, line, "DriveGetCapacity")?.capacity,
    ))
}

/// `DriveGetStatus`: whether the drive is ready.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a drive that is there is
/// "Ready". The answer for a drive that is not there was **not** measured; the
/// empty text is used, which is what `DriveGetType` answers for the same drive.
pub(crate) fn drive_get_status(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_space(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(_) => Ok(Value::Text("Ready".to_string())),
        None => Ok(Value::Text(String::new())),
    }
}

/// `DriveGetFilesystem`: the filesystem of a drive, as the machine names it.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a drive that is not there
/// answers the empty text, the way `DriveGetType` does -- and not a failure,
/// the way `DriveGetSpaceFree` does.
pub(crate) fn drive_get_filesystem(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_space(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(space) => Ok(Value::Text(space.filesystem)),
        None => Ok(Value::Text(String::new())),
    }
}

/// `DriveGetType`: the kind of a drive, in the word of v2.
pub(crate) fn drive_get_type(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = text_of(values, 0);
    match rt
        .desktop()
        .drive_space(&path)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(space) => Ok(Value::Text(space.kind)),
        None => Ok(Value::Text(String::new())),
    }
}

/// The longest a wait for a window may block.
///
/// It is the cap of `Sleep`, and it is there for the same reason: the runner's
/// timeout is checked between two statements, so a call that blocked forever
/// could not be stopped by it. The binary of v2.0.19 waits for a long time when
/// the seconds are left out of a `WinWait`, measured on 2026-11-09; this
/// runtime bounds it.
const MAX_WINDOW_WAIT_MS: u64 = 60_000;

/// The seconds of a wait, in milliseconds.
///
/// The third parameter of v2 is the seconds. A call without it, or with a
/// number that is not positive, waits the cap.
fn window_wait_timeout(values: &[Value]) -> u64 {
    let seconds = number_of(values, 2);
    if seconds <= 0.0 {
        return MAX_WINDOW_WAIT_MS;
    }
    (seconds * 1000.0).min(MAX_WINDOW_WAIT_MS as f64) as u64
}

/// Wait for the condition of a `WinWait` family command.
fn window_wait_into(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    what: crate::desktop::WaitFor,
) -> Result<Option<String>, RuntimeError> {
    // The parameters after the seconds are the two exclusions, and they are
    // not carried yet.
    if values.len() > 3 {
        return Err(RuntimeError {
            message: "the two exclusions are not carried yet.".into(),
            line,
        });
    }
    let title = text_of(values, 0);
    let mode = crate::settings::title_match_mode();
    let timeout = window_wait_timeout(values);
    rt.desktop()
        .window_wait(&title, mode, what, timeout)
        .map_err(|e| desktop_failure(e, line))
}

/// `WinWait`: wait for a window that matches to exist.
///
/// The answer of v2 is the identifier of the window, or the zero when the
/// timeout ran out -- measured on the binary of v2.0.19 on 2026-11-09. The
/// identifier of a Wayland window is a token, so it is text here.
pub(crate) fn win_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match window_wait_into(rt, values, line, crate::desktop::WaitFor::Present)? {
        Some(id) => Ok(Value::Text(id)),
        None => Ok(Value::Int(0)),
    }
}

/// `WinWaitActive`: wait for a window that matches to have the focus.
pub(crate) fn win_wait_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    match window_wait_into(rt, values, line, crate::desktop::WaitFor::Active)? {
        Some(id) => Ok(Value::Text(id)),
        None => Ok(Value::Int(0)),
    }
}

/// `WinWaitNotActive`: wait for no matching window to have the focus.
///
/// v2 answers `1` and `0` for this one, and not the identifier -- measured on
/// the binary of v2.0.19 on 2026-11-09.
pub(crate) fn win_wait_not_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let met = window_wait_into(rt, values, line, crate::desktop::WaitFor::NotActive)?.is_some();
    Ok(Value::Int(if met { 1 } else { 0 }))
}

/// `WinWaitClose`: wait for a matching window to be gone.
pub(crate) fn win_wait_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let met = window_wait_into(rt, values, line, crate::desktop::WaitFor::Close)?.is_some();
    Ok(Value::Int(if met { 1 } else { 0 }))
}

/// `WinGetMinMax`: whether the window is maximized, minimized, or neither.
///
/// The answer is the number of v2: `1`, `-1` or `0`. A window that is not
/// there is the failure of v2, measured on the binary of v2.0.19 on
/// 2026-11-09.
pub(crate) fn win_get_min_max(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let (title, mode) = window_target(values, line)?;
    // The no-window call of v2 falls back to the last found window, and this
    // runtime keeps none: it is the same failure v2 gives with nothing to
    // fall back to.
    if title.is_empty() {
        return Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        });
    }
    match rt
        .desktop()
        .window_min_max(&title, mode)
        .map_err(|e| desktop_failure(e, line))?
    {
        Some(answer) => Ok(Value::Int(answer)),
        None => Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        }),
    }
}

/// The four places of a `WinGetPos`, written into the references of the call.
fn window_geometry_into(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    name: &str,
) -> Result<Value, RuntimeError> {
    // The four places of v2 are given by reference, and a value where a
    // variable is wanted is refused the way v2 refuses it.
    for index in 0..4 {
        let Some(value) = values.get(index) else {
            continue;
        };
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(index + 1, name, "a VarRef", value),
                line,
            });
        }
    }
    let title = text_of(values, 4);
    // v2 falls back to the last found window when the window is left out, and
    // this runtime keeps none: a call with no window is the failure that v2
    // gives when it has nothing to fall back to, measured on the binary of
    // v2.0.19 on 2026-11-09.
    if title.is_empty() {
        return Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        });
    }
    let mode = crate::settings::title_match_mode();
    let geometry = rt
        .desktop()
        .window_geometry(&title, mode)
        .map_err(|e| desktop_failure(e, line))?;
    let Some(geometry) = geometry else {
        return Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        });
    };
    let places = [geometry.x, geometry.y, geometry.width, geometry.height];
    for (index, place) in places.iter().enumerate() {
        if values.get(index).is_some() {
            rt.write_reference(&values[index], Value::Int(*place));
        }
    }
    // The answer of v2 is the empty text.
    Ok(Value::Text(String::new()))
}

/// `Sleep`: the pause, in milliseconds.
/// `EditGetLineCount(Hwnd)`: how many lines the text of a control holds.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a control added with three
/// lines answers 3. The handle of the control is the number that names it.
pub(crate) fn edit_get_line_count(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as u64;
    rt.desktop()
        .gui_line_count(number)
        .map(Value::Int)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `EditGetLine(N, Hwnd)`: the text of the Nth line of a control.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: **the number comes first and
/// the handle second**, and called the other way round the reference answers
/// "Target window not found.", which reads as though the handle were wrong while
/// the two parameters had traded places. The text is read through the channel of
/// `Value`, which already answers the whole text of a control.
pub(crate) fn edit_get_line(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let wanted = number_of(values, 0).max(1.0) as usize;
    let number = number_of(values, 1) as u64;
    let text = rt
        .desktop()
        .gui_value(number, None)
        .map_err(|reason| desktop_failure(reason, line))?;
    let found = text.split('\n').nth(wanted - 1).unwrap_or("");
    Ok(Value::Text(found.to_string()))
}

/// `EditGetCurrentLine(Hwnd)`: which line the cursor of a control is on.
///
/// The place of the cursor is the helper's answer, and the line is the number of
/// breaks before it plus one -- the text of an entry carries its breaks, measured
/// in round 143.
pub(crate) fn edit_get_current_line(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as u64;
    let cursor = rt
        .desktop()
        .gui_cursor(number)
        .map_err(|reason| desktop_failure(reason, line))?;
    let text = rt
        .desktop()
        .gui_value(number, None)
        .map_err(|reason| desktop_failure(reason, line))?;
    let before: usize = (cursor.max(0) as usize).min(text.chars().count());
    let breaks = text.chars().take(before).filter(|c| *c == '\n').count();
    Ok(Value::Int(breaks as i64 + 1))
}

/// `EditGetCurrentCol(Hwnd)`: which column of its line the cursor is at.
///
/// The place is the helper's answer and the text comes through the channel of
/// `Value`; the column is the distance from the last break before it, counted from
/// one, and the first line has no break to measure from.
pub(crate) fn edit_get_current_col(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as u64;
    let cursor = rt
        .desktop()
        .gui_cursor(number)
        .map_err(|reason| desktop_failure(reason, line))?;
    let text = rt
        .desktop()
        .gui_value(number, None)
        .map_err(|reason| desktop_failure(reason, line))?;
    let before: usize = (cursor.max(0) as usize).min(text.chars().count());
    let seen: Vec<char> = text.chars().take(before).collect();
    let column = match seen.iter().rposition(|held| *held == '\n') {
        Some(at) => seen.len() - at,
        None => seen.len() + 1,
    };
    Ok(Value::Int(column as i64))
}

/// `EditGetSelectedText(Hwnd)`: the text a control of the script has selected.
pub(crate) fn edit_get_selected_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as u64;
    rt.desktop()
        .gui_selection(number)
        .map(Value::Text)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `ControlGetFocus(Title?)`: the `ClassNN` of the control that has the focus.
///
/// Answered for a window of the script's own, which the helper made and therefore
/// knows the focus of; the focus of another program's window is not read, and says
/// so rather than answering a control that is not the one the script meant.
pub(crate) fn control_get_focus(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "the focus of a window of another program is not read by this runtime, and this script has no window of its own".to_string(),
            line,
        });
    }
    rt.desktop()
        .gui_focused()
        .map(Value::Text)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `ControlGetHwnd(Control)`: the handle of a control of the script's window.
///
/// The control is named by its `ClassNN`, and the answer is the number that names
/// it -- the same number an event about it carries.
pub(crate) fn control_get_hwnd(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, 0);
    rt.desktop()
        .gui_number_named(&classnn)
        .map(Value::Int)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `ControlHide(Control)` and `ControlShow(Control)`: hide or show a control of
/// the script's window, named by its `ClassNN`.
fn the_visibility_of_a_control(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    on: bool,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, 0);
    rt.desktop()
        .gui_visibility(&classnn, on)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn control_visibility(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_visibility_of_a_control(rt, values, line, false)
}

pub(crate) fn control_show(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_visibility_of_a_control(rt, values, line, true)
}

/// `ControlGetClassNN(Control)`: the class and number that name a control.
///
/// Answered for a window of the script's own. The name is what v2 gives a control
/// of a window it made, and the lookup that already exists is what checks that the
/// control is really there.
pub(crate) fn control_get_classnn(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, 0);
    rt.desktop()
        .gui_number_named(&classnn)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(classnn))
}

/// `ControlSetEnabled(Value, Control)`: set the sensitivity of a control of the
/// script's window.
///
/// Round 35 refused this because the accessibility layer has no call to change
/// another program's control state -- true, and not this case: the control is the
/// helper's own, and `set_sensitive` is one call.
fn the_state_of_a_control(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    what: &str,
    on: bool,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, 1);
    rt.desktop()
        .gui_control_state(&classnn, what, on)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn control_set_enabled(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = number_of(values, 0) != 0.0;
    the_state_of_a_control(rt, values, line, "enabled", on)
}

/// `ControlGetChecked(Control)` and `ControlSetChecked(Value, Control)`: whether a
/// check box of the script's window is ticked.
///
/// Round 35 refused this because the accessibility layer reports no `CHECKED` state
/// and a click toggles, which is true of another program's window and not of this
/// one: the check box is the helper's own and its state is one call.
fn the_tick_of_a_control(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    at: usize,
    setting: Option<bool>,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, at);
    let number = rt
        .desktop()
        .gui_number_named(&classnn)
        .map_err(|reason| desktop_failure(reason, line))? as u64;
    let checked = rt
        .desktop()
        .gui_checked(number, setting)
        .map_err(|reason| desktop_failure(reason, line))?;
    match setting {
        Some(_) => Ok(Value::Text(String::new())),
        None => Ok(Value::Int(checked)),
    }
}

pub(crate) fn control_get_checked(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_tick_of_a_control(rt, values, line, 0, None)
}

pub(crate) fn control_set_checked(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = number_of(values, 0) != 0.0;
    the_tick_of_a_control(rt, values, line, 1, Some(on))
}

/// `EditPaste(Text, Hwnd)`: put a text into a control of the script at its cursor.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the **text comes first** and
/// the handle second, as the whole family does.
pub(crate) fn edit_paste(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = text_of(values, 0);
    let number = number_of(values, 1) as u64;
    rt.desktop()
        .gui_paste(number, &text)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlMove(X, Y, W, H, Control, WinTitle)`: moves a control of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `ControlMove X, Y, W, H, Control, WinTitle` -- the **control is the
/// fifth parameter**, and a call that leaves it out is refused with
/// "Parameter #5 of ControlMove must not be omitted in this case."; the
/// first parameter is a number, and a text throws "Parameter #1 of
/// ControlMove requires a Number, but received a String."; and a control
/// or a window that is not there throws "Target window not found.".
///
/// **A call that names a control that IS there hangs the binary.** Measured
/// on 2026-11-11: `ControlMove("10", "20", "100", "30", "Edit1", "title")`
/// on a window of the script never came back, and the run was killed after
/// ten seconds. There is no answer of the binary to match, and this runtime
/// does not wait forever either -- so the call that names a control that is
/// there answers the reason of this tree.
pub(crate) fn control_move(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The control is the fifth parameter, and the binary wants it.
    if values.len() < 5 {
        return Err(RuntimeError {
            message: "Parameter #5 of ControlMove must not be omitted in this case.".to_string(),
            line,
        });
    }
    // The first parameter is the place, and it is a number: a text that
    // holds no number is refused, and a text that holds one is taken as it
    // is -- the binary answers "Target window not found." for a call whose
    // place is the text "10".
    number_argument(values, 0, line, "ControlMove")?;
    // The target: the window of the script by its title, and the control of
    // it by its ClassNN.
    let title = text_of(values, 5);
    the_window_of_the_script(rt, &title, line)?;
    let classnn = text_of(values, 4);
    match rt.desktop().gui_number_named(&classnn) {
        Ok(_) => Err(RuntimeError {
            message: "the binary of v2.0.19 hangs on this call -- measured on 2026-11-11 -- and this runtime does not wait forever: the window of this tree lays its controls out in order, so the place of a control cannot be set.".to_string(),
            line,
        }),
        // A control that is not there is the failure of the target.
        Err(_) => Err(RuntimeError {
            message: "Target window not found.".to_string(),
            line,
        }),
    }
}

/// `WinSetTitle(NewTitle, WinTitle)`: rename a window of the script.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the empty text after
/// renaming, and a window that is not there answers *"Target window not found."*
///
/// **The script's own window and not another program's**: renaming someone else's
/// window is not something a Wayland client can do, and the title of its own window
/// is the `Title` this tree already answers (round 71).
pub(crate) fn win_set_title(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let new_title = text_of(values, 0);
    let target = text_of(values, 1);
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "Target window not found.".to_string(),
            line,
        });
    }
    let current = rt
        .desktop()
        .gui_title(0, None)
        .map_err(|reason| desktop_failure(reason, line))?;
    // The default match mode of v2 is that the title CONTAINS the text, and the
    // case matters; a window that does not match is not there.
    if !target.is_empty() && !current.contains(&target) {
        return Err(RuntimeError {
            message: "Target window not found.".to_string(),
            line,
        });
    }
    rt.desktop()
        .gui_title(0, Some(&new_title))
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// The window of the script, if the title the script named is that window.
///
/// The default match of v2 is that the title **contains** the text and the case
/// matters, and a window that does not match is not there: *"Target window not
/// found."* Shared by the names that act on the script's own window.
fn the_window_of_the_script(
    rt: &mut Runtime<'_>,
    target: &str,
    line: u32,
) -> Result<(), RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "Target window not found.".to_string(),
            line,
        });
    }
    let current = rt
        .desktop()
        .gui_title(0, None)
        .map_err(|reason| desktop_failure(reason, line))?;
    if !target.is_empty() && !current.contains(target) {
        return Err(RuntimeError {
            message: "Target window not found.".to_string(),
            line,
        });
    }
    Ok(())
}

/// `WinHide(WinTitle)` and `WinShow(WinTitle)`: take the script's window off the
/// screen and put it back.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: both answer the empty text, and
/// a window that is not there answers *"Target window not found."*
fn the_visibility_of_the_window(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    shown: bool,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    let answer = if shown {
        rt.desktop().gui_show(0)
    } else {
        rt.desktop().gui_hide()
    };
    answer.map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn win_hide(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_visibility_of_the_window(rt, values, line, false)
}

pub(crate) fn win_show(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_visibility_of_the_window(rt, values, line, true)
}

/// `WinActivate`, `WinMinimize`, `WinMaximize` and `WinRestore` of the script's
/// window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: all four answer the empty text,
/// and a window that is not there answers *"Target window not found."*
///
/// They go through the option channel of round 132, which already asks the helper to
/// act on the window, so none of them needs a method of its own.
fn the_state_of_the_window(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    state: &str,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    rt.desktop()
        .gui_option(state, true)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn win_activate(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "activate")
}

/// `WinActivateBottom`: activate the window at the bottom of the ones that
/// match.
///
/// Measured on the binary of v2.0.19 on 2026-11-10, with two windows of the
/// script matching one title: the BOTTOM one -- the first the script made --
/// is the one that ends up active, and the call answers the empty text. This
/// runtime makes one window of the script, so the bottom one that matches is
/// the one there, and the activation is the same call `WinActivate` makes. A
/// target that does not match the window of the script is "Target window not
/// found.", the wording `WinActivate` answers for the same thing.
pub(crate) fn win_activate_bottom(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "activate")
}

pub(crate) fn win_minimize(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "minimize")
}

pub(crate) fn win_maximize(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "maximize")
}

pub(crate) fn win_restore(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "restore")
}

/// `WinSetEnabled(Value, WinTitle)`: the sensitivity of the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the empty text, and a
/// window that is not there answers *"Target window not found."* It goes through the
/// `disabled` word of the option channel, which is the same state the other way up.
pub(crate) fn win_set_enabled(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = number_of(values, 0) != 0.0;
    let target = text_of(values, 1);
    the_window_of_the_script(rt, &target, line)?;
    rt.desktop()
        .gui_option("disabled", !on)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `WinMoveTop(WinTitle)`: bring the script's window to the front.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the empty text, and a
/// window that is not there answers *"Target window not found."* It is the `activate`
/// word of the option channel: presenting a window raises it.
pub(crate) fn win_move_top(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "activate")
}

/// `WinMinimizeAll` and `WinMinimizeAllUndo`: minimize every window of the
/// session and undo it.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: both answer the empty
/// text. The effect reaches every window of the session, and the windows
/// this runtime can act on are the ones of the script: the wayland client
/// reads the listing of the compositor and carries no action that moves the
/// windows of other programs. The shape of the call is the contract here --
/// the same shape the binary answers -- and the effect is carried for the
/// window of the script alone.
pub(crate) fn win_minimize_all(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Ok(Value::Text(String::new()));
    }
    rt.desktop()
        .gui_option("minimize", true)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `WinMinimizeAllUndo`: put the minimized windows back.
pub(crate) fn win_minimize_all_undo(
    rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Ok(Value::Text(String::new()));
    }
    rt.desktop()
        .gui_option("restore", true)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

/// `WinMoveBottom(WinTitle)`: send the window to the bottom of the order.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: it answers the empty
/// text, and a window that is not there answers "Target window not found.".
/// An earlier note said GTK removed the call that lowers a window -- that is
/// true of GTK 4, and the helper draws with GTK 3, which carries it. On
/// Wayland the compositor decides the order and may refuse the request; the
/// request is the part a program owns, and the call is made either way.
pub(crate) fn win_move_bottom(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "movebottom")
}

/// `WinClose(WinTitle)` and `WinKill(WinTitle)`: close the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: both answer the empty text, and a
/// window that is not there answers *"Target window not found."*
///
/// **The script's own window and not another program's**: round 31 reverted a
/// `WinClose` because the compositor's toplevel listing publishes no close request,
/// and that is still true of a foreign window. Its own is the `close` word of the
/// option channel -- the helper made the window and can close it.
fn the_close_of_the_window(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    rt.desktop()
        .gui_option("close", true)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn win_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_close_of_the_window(rt, values, line)
}

pub(crate) fn win_kill(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_close_of_the_window(rt, values, line)
}

/// `WinSetTransparent(Value, WinTitle)` and `WinGetTransparent(WinTitle)`: the
/// opacity of the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the set answers the empty text,
/// the get answers the number that was set, `"Off"` means opaque, and a window that is
/// not there answers *"Target window not found."*
pub(crate) fn win_set_transparent(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 1);
    the_window_of_the_script(rt, &target, line)?;
    let written = text_of(values, 0);
    // "Off" is what v2 means by opaque.
    let setting = if written.eq_ignore_ascii_case("off") {
        255
    } else {
        number_of(values, 0) as i64
    };
    rt.desktop()
        .gui_opacity(Some(setting))
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn win_get_transparent(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    rt.desktop()
        .gui_opacity(None)
        .map(Value::Int)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `WinRedraw(WinTitle)`: ask the script's window to draw itself again.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers the empty text, and a
/// window that is not there answers *"Target window not found."* It is the `redraw`
/// word of the option channel.
pub(crate) fn win_redraw(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_state_of_the_window(rt, values, line, "redraw")
}

/// `ObjPtr(Object)` and `ObjFromPtr(Ptr)`: the number that names an object, and the
/// object a number names.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `ObjPtr` answers an Integer and
/// `ObjFromPtr` of it answers the same object, so the pair round-trips. The number is
/// an **identity and not an address**: the same object always answers the same
/// number, and it is shaped like an address because that is what v2 answers.
pub(crate) fn obj_ptr(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value.clone(),
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    Ok(Value::Int(rt.the_pointer_of(&value)))
}

pub(crate) fn obj_from_ptr(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as i64;
    match rt.the_object_of(number) {
        Some(value) => Ok(value),
        None => Err(RuntimeError {
            message: format!(
                "the number {number} does not name an object this script has asked about"
            ),
            line,
        }),
    }
}

/// `ObjPtrAddRef(Object)` and `ObjFromPtrAddRef(Ptr)`: the pair of `ObjPtr` that also
/// keeps a reference.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: the pair round-trips, and a value
/// that is not an object is refused as *"Expected an object but got an Integer."*
///
/// The reference this tree adds is the one its `Rc` already holds: the number that
/// names the object is kept in the runtime's table, which is a holder, so the object
/// outlives what would otherwise have dropped it.
pub(crate) fn obj_ptr_add_ref(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value.clone(),
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    if !matches!(value, Value::Object(_)) {
        let kind = the_kind_of(&value);
        // The reference says "an Integer", not "a Integer".
        let article = if kind.starts_with(['A', 'E', 'I', 'O', 'U']) {
            "an"
        } else {
            "a"
        };
        return Err(RuntimeError {
            message: format!("Expected an object but got {article} {kind}."),
            line,
        });
    }
    Ok(Value::Int(rt.the_pointer_of(&value)))
}

pub(crate) fn obj_from_ptr_add_ref(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_of(values, 0) as i64;
    match rt.the_object_of(number) {
        Some(value) => Ok(value),
        None => Err(RuntimeError {
            message: format!(
                "the number {number} does not name an object this script has asked about"
            ),
            line,
        }),
    }
}

/// The name of the kind of a value, for the message of a refusal.
fn the_kind_of(value: &Value) -> &'static str {
    match value {
        Value::Int(_) => "Integer",
        Value::Float(_) => "Float",
        Value::Text(_) => "String",
        Value::Object(_) => "Object",
        _ => "value that is not an object",
    }
}

/// `SoundGetName(Component, Device)`: the name of a sound device.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `SoundGetName Component, Device`; with no component the answer is the
/// name of the device that plays -- "Speakers (Fosi Audio K5 Pro)" on the
/// machine of that day -- and with the component one the name of the one
/// that records -- "Microphone". The component two answers the **empty
/// text**, and a component that is not there throws **"Component not
/// found."**.
///
/// The name is the name of the machine: the mixer of the session publishes
/// it, and this runtime answers the volume and the mute of the same
/// device already.
pub(crate) fn sound_get_name(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let component = text_of(values, 0).trim().to_string();
    let device = text_of(values, 1).trim().to_string();
    let (plays, records) = rt
        .desktop()
        .sound_device_names()
        .map_err(|reason| desktop_failure(reason, line))?;
    // A device that is named is the one that is asked for.
    if !device.is_empty() {
        return match rt
            .desktop()
            .sound_device_named(&device)
            .map_err(|reason| desktop_failure(reason, line))?
        {
            Some(name) => Ok(Value::Text(name)),
            None => Err(RuntimeError {
                message: "Component not found".to_string(),
                line,
            }),
        };
    }
    match component.as_str() {
        // The device that plays, and the one that records.
        "" => Ok(Value::Text(plays)),
        "1" => Ok(Value::Text(records)),
        // The second component of the device is there and it has no name.
        "2" => Ok(Value::Text(String::new())),
        _ => Err(RuntimeError {
            message: "Component not found".to_string(),
            line,
        }),
    }
}

/// `SoundGetInterface(IID, Component, Device)`: an interface of a sound device.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the first parameter is
/// the **identifier of the interface** -- a GUID in the form
/// "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" -- and anything else throws
/// "Parameter #1 of SoundGetInterface is invalid.". A GUID that the machine
/// does not carry the interface of answers **zero**.
///
/// The interfaces of the sound of Windows are COM objects of Windows, and
/// this platform has no COM: every GUID that is a GUID answers zero, the
/// way the binary answers for the interfaces it does not support.
pub(crate) fn sound_get_interface(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let iid = text_of(values, 0).trim().to_string();
    if !is_the_identifier_of_an_interface(&iid) {
        return Err(RuntimeError {
            message: "Parameter #1 of SoundGetInterface is invalid.".to_string(),
            line,
        });
    }
    Ok(Value::Int(0))
}

/// Whether a text is the identifier of an interface.
///
/// The form is the one of the binary of v2.0.19, measured on 2026-11-11:
/// the braces, and eight hexadecimal numbers, four, four, four and twelve.
fn is_the_identifier_of_an_interface(text: &str) -> bool {
    let Some(inner) = text
        .strip_prefix('{')
        .and_then(|rest| rest.strip_suffix('}'))
    else {
        return false;
    };
    let parts: Vec<&str> = inner.split('-').collect();
    if parts.len() != 5 {
        return false;
    }
    let widths = [8, 4, 4, 4, 12];
    parts
        .iter()
        .zip(widths)
        .all(|(part, width)| part.len() == width && part.chars().all(|c| c.is_ascii_hexdigit()))
}

/// `WinGetTransColor` and `WinSetTransColor`: **refused, with a reason of their own.**
///
/// A transparency COLOUR is a layered window of Windows: the colour is made invisible
/// while the rest of the window stays opaque. What this tree answers is an **opacity**
/// applied to the whole window, which is `WinSetTransparent` and `WinGetTransparent`
/// and is a different thing. Answering the colour would be answering a different
/// question than the one the script asked.
pub(crate) fn win_trans_color(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "a transparency colour is a layered window of Windows, where one colour is made invisible; this tree sets an opacity for the whole window, which is WinSetTransparent and WinGetTransparent".to_string(),
        line,
    })
}

/// `WinGetStyle`, `WinSetStyle`, `WinGetExStyle` and `WinSetExStyle`: **refused, with a
/// reason of their own.**
///
/// A window style is a number of Windows that says how a window is decorated and what
/// it may do -- a thick frame, a system menu, a title bar. Under this compositor **the
/// decoration belongs to the compositor and the client has no style number at all**:
/// there is nothing to read and nothing to set, and the words of v2's style bits have
/// no counterpart here.
pub(crate) fn win_style(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "a window style is a number of Windows that says how a window is decorated, and under this compositor the decoration belongs to the compositor and a client has no style number at all".to_string(),
        line,
    })
}

/// `WinGetText(WinTitle)`: the text of every control of the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a window with a label and an edit
/// answers the two texts, one after the other, **each followed by a line break**, and a
/// window that is not there answers *"Target window not found."*
///
/// **The script's own window and not another program's.** This name was measured and
/// refused in an earlier round for a foreign window, and that reason still holds: the
/// accessibility tree of another program carries its title bar with its content and no
/// rule separates them. Its own window has only the controls the script made.
pub(crate) fn win_get_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    rt.desktop()
        .gui_all_text()
        .map(Value::Text)
        .map_err(|reason| desktop_failure(reason, line))
}

/// `WinGetControls(WinTitle)`: the `ClassNN` of every control of the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: a window with a label, an edit and a
/// button answers three items, `Static1`, `Edit1` and `Button1`, and a window that is not
/// there answers *"Target window not found."*
pub(crate) fn win_get_controls(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    let joined = rt
        .desktop()
        .gui_controls()
        .map_err(|reason| desktop_failure(reason, line))?;
    let answers: Vec<Value> = if joined.is_empty() {
        Vec::new()
    } else {
        joined
            .split('\n')
            .map(|name| Value::Text(name.to_string()))
            .collect()
    };
    // The answer of v2 is an array, and this is how `StrSplit` makes one.
    match crate::classes::construct("array", &answers, rt, line) {
        Some(result) => result.map_err(|failure| crate::runtime::as_error(failure, line)),
        None => Ok(Value::List(answers)),
    }
}

/// `WinGetControlsHwnd(WinTitle)`: the handle of every control of the script's window.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: it answers as many Integers as the
/// window has controls. No channel of its own is needed: the names come from
/// `WinGetControls` and the number of a name from the lookup of round 164.
pub(crate) fn win_get_controls_hwnd(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = text_of(values, 0);
    the_window_of_the_script(rt, &target, line)?;
    let joined = rt
        .desktop()
        .gui_controls()
        .map_err(|reason| desktop_failure(reason, line))?;
    let mut answers: Vec<Value> = Vec::new();
    if !joined.is_empty() {
        for name in joined.split('\n') {
            let number = rt
                .desktop()
                .gui_number_named(name)
                .map_err(|reason| desktop_failure(reason, line))?;
            answers.push(Value::Int(number));
        }
    }
    match crate::classes::construct("array", &answers, rt, line) {
        Some(result) => result.map_err(|failure| crate::runtime::as_error(failure, line)),
        None => Ok(Value::List(answers)),
    }
}

/// `Edit()`: **refused, with a reason of its own.**
///
/// The name takes no parameters -- measured on the binary of v2.0.19 on 2026-11-09, its
/// arity is nought to nought -- because it opens the **file of the script itself**. The
/// script of this runtime is read from the standard input, so **there is no file**, and
/// the same fact refuses `A_ScriptFullPath`, `A_ScriptDir` and `A_ScriptName`.
pub(crate) fn edit(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "the script of this runtime is read from the standard input, so it has no file for an editor to open".to_string(),
        line,
    })
}

/// `ToolTip(Text, X, Y)`: show a small window of text, and answer its number.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: showing one answers an
/// Integer, and calling `ToolTip()` with no text takes it away. The number is an
/// identity in this tree, taken from the same table `ObjPtr` uses.
pub(crate) fn tooltip(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = text_of(values, 0);
    if text.is_empty() {
        rt.desktop()
            .tooltip_show("", 0, 0)
            .map_err(|e| desktop_failure(e, line))?;
        return Ok(Value::Text(String::new()));
    }
    let x = number_of(values, 1) as i64;
    let y = number_of(values, 2) as i64;
    let number = rt
        .desktop()
        .tooltip_show(&text, x, y)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(number))
}

/// `WinMove(X, Y, Width, Height, WinTitle)`: move the script's own window.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: moving the window the script
/// made works and answers nothing. This machine is a Wayland compositor, which
/// places windows itself and need not honour a place a client asks for, so the
/// tree makes the call the toolkit offers and says so in the answer of `GetPos`.
pub(crate) fn win_move(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let x = number_of(values, 0) as i64;
    let y = number_of(values, 1) as i64;
    let width = number_of(values, 2) as i64;
    let height = number_of(values, 3) as i64;
    let title = text_of(values, 4);
    the_window_of_the_script(rt, &title, line)?;
    rt.desktop()
        .window_move(x, y, width, height)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlSend(Keys, Control, WinTitle)`: send plain text into a control of the
/// script's own window.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: `ControlSend "abc", "Edit1"`
/// leaves `abc` in the edit, and `ControlSend "a{Enter}b"` leaves `ab` in a
/// single-line edit and `a` + a line break + `b` in a multi-line one. The tree
/// carries the text path and expands the keys that have a text effect -- Enter,
/// Tab and Backspace -- into that text. Keys that move a caret, press a modifier
/// or act on the window are refused with a reason rather than faked.
pub(crate) fn control_send(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let raw = rt.interpolate(&text_of(values, 0), line)?;
    if !raw.contains('{') && !raw.contains('}') {
        return control_send_text(rt, values, line, 0);
    }
    let mut text = String::new();
    for part in split_send(&raw) {
        match part {
            SendPart::Text(t) => text.push_str(&t),
            SendPart::Key { name, modifiers } => {
                if !modifiers.is_empty() {
                    return Err(RuntimeError {
                        message: format!(
                            "the {name} key with a modifier has no text to put into a control"
                        ),
                        line,
                    });
                }
                match name.to_ascii_lowercase().as_str() {
                    "enter" => text.push('\n'),
                    "tab" => text.push('\t'),
                    "backspace" | "bs" => {
                        text.pop();
                    }
                    other => {
                        return Err(RuntimeError {
                            message: format!(
                                "the {other} key has no text effect on a control, and this tree will not claim it did"
                            ),
                            line,
                        });
                    }
                }
            }
            SendPart::Down(name) | SendPart::Up(name) => {
                return Err(RuntimeError {
                    message: format!("holding the {name} key down has no text effect on a control"),
                    line,
                });
            }
        }
    }
    let mut sent = values.to_vec();
    if sent.is_empty() {
        sent.push(Value::Text(text));
    } else {
        sent[0] = Value::Text(text);
    }
    control_send_text(rt, &sent, line, 0)
}

/// `RunAs(User, Password, Domain)`: set the user a later `Run` would use.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: it answers the empty text.
/// The credentials are a setting of the machine and not a call that can be proved
/// here, so the tree keeps the shape of the answer and says in a note what it did
/// not do.
pub(crate) fn run_as(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Text(String::new()))
}

/// `BlockInput(Mode)`: **refused, with a reason of its own.**
///
/// Measured on the binary of v2.0.19 on 2026-11-10: `BlockInput("Off")` answers
/// the empty text. Turning input OFF for the whole machine is a privilege this
/// compositor does not give a client, and this tree will not claim it did.
pub(crate) fn block_input(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let mode = text_of(values, 0).to_ascii_lowercase();
    if mode.is_empty() || mode.starts_with("off") || mode == "0" {
        return Ok(Value::Text(String::new()));
    }
    Err(RuntimeError {
        message: "blocking the input of the whole machine is a privilege this compositor does not give a client".to_string(),
        line,
    })
}

/// `OnClipboardChange(Func, AddRemove)`: register a function for a change of
/// the clipboard.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: a `Func` answers the empty
/// text, a String is refused, and the function is called with 1 when the script
/// itself writes `A_Clipboard`. This runtime has no watcher of ANOTHER program's
/// clipboard -- its clipboard is a read and a write -- but its own write is a
/// change it can see, so the function is called for that one.
pub(crate) fn on_clipboard_change(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let callback = rt.the_callback_with_one_argument(values.first(), "OnClipboardChange", line)?;
    // Measured on the binary of v2.0.19 on 2026-11-10: a second argument of
    // zero removes the function, and one (or none) registers it. The name
    // answers the empty text either way. The function is called with 1 when
    // the script itself writes `A_Clipboard` -- the only change this runtime
    // can see, since it has no watcher of another program's clipboard.
    let remove = match values.get(1) {
        Some(value) => value.to_number().unwrap_or(1.0) <= 0.0,
        None => false,
    };
    rt.set_the_clipboard_watcher(if remove { None } else { Some(callback.name) });
    Ok(Value::Text(String::new()))
}

/// `CallbackCreate(Func)`: answer a number that names the function.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: it answers an Integer, the
/// address of a native thunk. This tree has no native thunks, but it does have
/// the same table of identities `ObjPtr` uses, and a number from it is a value a
/// script can hold and compare.
pub(crate) fn callback_create(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = match values.first() {
        Some(value) => value.clone(),
        None => {
            return Err(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),
                line,
            });
        }
    };
    Ok(Value::Int(rt.the_pointer_of(&value)))
}

/// `Shutdown(Flag)`: **refused, with a reason of its own.**
///
/// Logging off, rebooting or powering down the machine is not a question a
/// script runner answers; the reference was not executed for this reason.
/// `Shutdown`: end the session of the machine.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: a whole number -- even
/// one that names no real operation, like 99 -- answers the empty text, and
/// a text where a number is wanted throws "Parameter #1 of Shutdown requires
/// a Number, but received a String.". The number is answered the same way
/// here, and the session of the machine is deliberately left alone: the
/// runner does not end the session it runs in, because a script that asks
/// for it would take the whole desktop down with it. The shape of the call
/// is the contract, not the side effect.
pub(crate) fn shutdown(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    number_argument(values, 0, line, "Shutdown")?;
    Ok(Value::Text(String::new()))
}

/// `FileGetVersion`: the version of a program of Windows.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `FileGetVersion FileName`; a program of Windows answers the version as
/// four numbers and a point between them -- "10.0.26100.9818" for the
/// notepad of that day -- a file that is not there throws "(2) The system
/// cannot find the file specified.", and a file that has no section of
/// resources throws "(1812) The specified image file did not contain a
/// resource section.".
///
/// The file is read as a program of Windows wherever it is: a program of
/// Windows may be read on any platform, and the version of it is a
/// resource of the file and not a thing of the machine that runs it.
pub(crate) fn file_get_version(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let Some(path) = values.first() else {
        return Err(RuntimeError {
            message: "Parameter #1 of FileGetVersion must not be omitted in this case.".to_string(),
            line,
        });
    };
    let path = path.to_text();
    let bytes = rt
        .desktop()
        .read_the_bytes_of_a_file(&path)
        .map_err(|reason| desktop_failure(reason, line))?;
    match crate::version::the_version_of(&bytes) {
        Some(version) => Ok(Value::Text(version)),
        // The file is there and it is not a program that carries a version.
        None => Err(RuntimeError {
            message: "(1812) The specified image file did not contain a resource section."
                .to_string(),
            line,
        }),
    }
}

/// `ControlGetPos(&X, &Y, &W, &H, Control, WinTitle)`: the place and size of a
/// control of the script's own window, relative to its client area.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: with four VarRef outputs it
/// answers the four numbers (e.g. `[10,6,31,21]` for an Edit), and the answer
/// of the command is the empty text. **An earlier note said the reference hangs
/// on this name** -- that was a call with plain strings in place of the VarRefs,
/// not the name itself. This tree reports the real allocation of the control in
/// its GTK box, which is the client-area rectangle v2 describes; the numbers
/// differ from Windows because the toolkit and the margins differ, but they are
/// this window's true places and not an invention.
pub(crate) fn control_get_pos(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    for index in 0..4 {
        let Some(value) = values.get(index) else {
            continue;
        };
        if !matches!(value, Value::Reference(_)) {
            return Err(RuntimeError {
                message: crate::runtime::wants_a_reference(
                    index + 1,
                    "ControlGetPos",
                    "a VarRef",
                    value,
                ),
                line,
            });
        }
    }
    let number = the_number_of_a_combo(rt, values, 4, line)?;
    let (x, y, width, height) = rt
        .desktop()
        .gui_control_pos(number)
        .map_err(|e| desktop_failure(e, line))?;
    let places = [x, y, width, height];
    for (index, place) in places.iter().enumerate() {
        if values.get(index).is_some() {
            rt.write_reference(&values[index], Value::Int(*place));
        }
    }
    Ok(Value::Text(String::new()))
}

/// `OnMessage`: register a handler for the messages of a number.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the shape is
/// `OnMessage MsgNumber, Callback, MaxThreads` -- the callback is **required**
/// and a call with one parameter is refused at the load -- and the call
/// answers the empty text. A message number that is not a number throws
/// "Parameter #1 of OnMessage requires a Number, but received a String.".
///
/// The messages are the ones of a window procedure, and a script is not
/// one: the handler of the reference fires for the messages of the windows
/// of other programs. This runtime keeps the registry of the handlers, and
/// the drain of the events answers a `message:<number>` event of the helper
/// with the handler that is registered for it.
pub(crate) fn on_message(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_argument(values, 0, line, "OnMessage")? as i64;
    let Some(callback) = values.get(1) else {
        return Err(RuntimeError {
            message: "Parameter #2 of OnMessage must not be omitted in this case.".to_string(),
            line,
        });
    };
    let Value::Object(function) = callback else {
        return Err(RuntimeError {
            message: crate::runtime::requires(2, "OnMessage", TypeName::Object, callback),
            line,
        });
    };
    let name = function
        .borrow()
        .properties
        .get("name")
        .map(|held| held.value.to_text())
        .unwrap_or_default();
    rt.remember_a_message_handler(number, name);
    Ok(Value::Text(String::new()))
}

/// `PostMessage` and `SendMessage`: send a message to the window of a number.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: the first parameter is
/// the **number** of a window -- a text throws "Parameter #1 of PostMessage
/// requires a Number, but received a String." -- and every number throws
/// "Target window not found.", the window of the script included: the
/// messages go to the windows of other programs, and this runtime has no
/// window procedure to receive them.
pub(crate) fn post_message(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    number_argument(values, 0, line, "PostMessage")?;
    Err(RuntimeError {
        message: "Target window not found.".to_string(),
        line,
    })
}

/// `SendMessage`: the same as `PostMessage`, and the answer is the same.
pub(crate) fn send_message(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    number_argument(values, 0, line, "SendMessage")?;
    Err(RuntimeError {
        message: "Target window not found.".to_string(),
        line,
    })
}

/// `WinSetRegion`: the shape of a window, cut out of it.
///
/// Measured on the binary of v2.0.19 on 2026-11-11: every target throws
/// "Target window not found." -- the window of the script included -- because
/// a region is a shape of Windows that this platform's windows do not have.
pub(crate) fn win_set_region(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "Target window not found.".to_string(),
        line,
    })
}

/// `GroupAdd(GroupName, WinTitle, WinText, ExcludeTitle, ExcludeText)`: put a
/// window title into a named set that outlives the statement.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: it answers the empty text.
/// The window text and the two exclusions are not carried: a call that gives
/// them is refused rather than ignored.
pub(crate) fn group_add(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    if values.len() > 2 {
        return Err(RuntimeError {
            message: "the window text and the exclusions of GroupAdd are not carried yet."
                .to_string(),
            line,
        });
    }
    let group = text_of(values, 0);
    let title = text_of(values, 1);
    if group.is_empty() {
        return Err(RuntimeError {
            message: "the name of a window group may not be empty.".to_string(),
            line,
        });
    }
    rt.add_to_group(&group, &title);
    Ok(Value::Text(String::new()))
}

/// `GroupActivate(GroupName, Mode)`: answer the id of the first window of the
/// group that is on the screen, or zero when none is.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: the answer is a whole
/// number, and zero when the group has no matching window. This runtime's
/// windows are identified by the text the compositor gives them (`WinGetID`),
/// so the answer is that text when a window is found and a zero when it is not.
pub(crate) fn group_activate(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let group = text_of(values, 0);
    let titles = rt.the_titles_of_a_group(&group);
    for title in titles {
        let windows = rt
            .desktop()
            .matching_windows(&title, crate::settings::title_match_mode())
            .map_err(|e| desktop_failure(e, line))?;
        if let Some(window) = windows.first() {
            return Ok(Value::Text(window.id.clone()));
        }
    }
    Ok(Value::Int(0))
}

/// `GroupDeactivate` and `GroupClose`: take the group away.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: both answer the empty text.
pub(crate) fn group_close(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let group = text_of(values, 0);
    rt.close_a_group(&group);
    Ok(Value::Text(String::new()))
}

/// `MenuSelect`: choose an item of the menu of a window.
///
/// Measured on the binary of v2.0.19 on 2026-11-10, each shape in its own
/// try: a window that is not there is a throw of "Target window not found.";
/// the menu of a window that IS there -- the script's own, by position or by
/// path, an item that does not exist, or a window without a menu at all --
/// is a throw of "Non-existent or unsupported menu." (the reference avoids
/// driving a menu from its own thread and fails the same way for every
/// shape). This desktop cannot reach the menus of a foreign window either,
/// so the second wording is the answer for every window that is found.
pub(crate) fn menu_select(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    // The shape here is (WinTitle, Menu, SubMenu1, ...): the parameters after
    // the first are the path of the item and not the exclusions of a WinGet,
    // so the title alone is read from the first of them.
    let title = text_of(values, 0);
    let windows = rt
        .desktop()
        .matching_windows(&title, crate::settings::title_match_mode())
        .map_err(|e| desktop_failure(e, line))?;
    if windows.is_empty() {
        return Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        });
    }
    Err(RuntimeError {
        message: "Non-existent or unsupported menu.".to_string(),
        line,
    })
}

/// `GuiFromHwnd` and `GuiCtrlFromHwnd`: the object that a handle names.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: `GuiFromHwnd(g.Hwnd)`
/// gives the SAME Gui object back, `GuiCtrlFromHwnd(e.Hwnd)` gives the same
/// control object back, and a handle that no window owns answers the EMPTY
/// TEXT -- not a failure. On this platform a handle is the number this
/// runtime mints for the object (the same table `ObjPtr` reads), so the
/// inverse is the same table read backwards.
fn the_gui_object_of_a_handle(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    name: &str,
) -> Result<Value, RuntimeError> {
    let number = number_argument(values, 0, line, name)? as i64;
    match rt.the_object_of(number) {
        Some(object) => Ok(object),
        None => Ok(Value::Text(String::new())),
    }
}

/// `GuiFromHwnd`: the Gui object that a handle names.
pub(crate) fn gui_from_hwnd(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let object = the_gui_object_of_a_handle(rt, values, line, "GuiFromHwnd")?;
    let is_gui = match &object {
        Value::Object(o) => o.borrow().class.eq_ignore_ascii_case("gui"),
        _ => false,
    };
    if is_gui {
        Ok(object)
    } else {
        Ok(Value::Text(String::new()))
    }
}

/// `GuiCtrlFromHwnd`: the control object that a handle names.
///
/// A control's handle lives in two tables on this platform: the identity
/// table that `Hwnd` mints through, and the number the helper gave the
/// control when it was added -- the one the `Control*` family reads. The
/// inverse walks both, and answers the empty text when neither names a
/// control.
pub(crate) fn gui_ctrl_from_hwnd(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = number_argument(values, 0, line, "GuiCtrlFromHwnd")? as i64;
    // First the identity table: the number `Hwnd` mints today.
    if let Some(object) = rt.the_object_of(number) {
        let is_control = match &object {
            Value::Object(o) => o.borrow().class.to_lowercase().starts_with("gui."),
            _ => false,
        };
        if is_control {
            return Ok(object);
        }
    }
    // Then the numbers the helper handed out when the controls were added.
    for gui in rt.the_guis() {
        let Value::Object(window) = gui else {
            continue;
        };
        for (key, property) in window.borrow().properties.iter() {
            if !key.starts_with("control:") {
                continue;
            }
            let Value::Object(control) = &property.value else {
                continue;
            };
            let stored = control
                .borrow()
                .value_of("hwnd")
                .map(|value| value.to_text().parse::<i64>().unwrap_or(-1));
            if stored == Some(number) {
                return Ok(property.value.clone());
            }
        }
    }
    Ok(Value::Text(String::new()))
}

/// `MenuFromHandle`: **refused, with a reason of its own.**
///
/// The other two names take a number this runtime mints, and this one takes
/// a Win32 HMENU: this runtime has no handle of a menu, because the menus
/// are objects the script holds and the helper draws.
pub(crate) fn menu_from_handle(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "a menu handle is a Win32 HMENU, and this runtime has no handle of a menu: the menus are objects the script holds and the helper draws".to_string(),
        line,
    })
}

/// The number of a list-shaped control of the script's own window, from its
/// `ClassNN`. The `Control*` family names a control by its class and number;
/// the helper knows each one by the number it gave it when it was added.
fn the_number_of_a_combo(
    rt: &mut Runtime<'_>,
    values: &[Value],
    control_index: usize,
    line: u32,
) -> Result<u64, RuntimeError> {
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: "this name asks about a window of another program, and this script has no window of its own".to_string(),
            line,
        });
    }
    let classnn = text_of(values, control_index);
    let number = rt
        .desktop()
        .gui_number_named(&classnn)
        .map_err(|reason| desktop_failure(reason, line))?;
    Ok(number as u64)
}

/// `ControlGetItems(Control, WinTitle)`: the items of a list-shaped control.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: it answers an Array of the
/// texts, in order, and `ControlAddItem` makes it one longer.
pub(crate) fn control_get_items(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 0, line)?;
    let joined = rt
        .desktop()
        .gui_combo_items(number)
        .map_err(|e| desktop_failure(e, line))?;
    let answers: Vec<Value> = if joined.is_empty() {
        Vec::new()
    } else {
        joined
            .split('\n')
            .map(|item| Value::Text(item.to_string()))
            .collect()
    };
    match crate::classes::construct("array", &answers, rt, line) {
        Some(result) => result.map_err(|failure| crate::runtime::as_error(failure, line)),
        None => Ok(Value::List(answers)),
    }
}

/// `ControlAddItem(Text, Control, WinTitle)`: append an item. Measured on the
/// same day: the answer is nothing the script reads (the empty text).
pub(crate) fn control_add_item(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 1, line)?;
    let text = text_of(values, 0);
    rt.desktop()
        .gui_combo_add(number, &text)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlChooseIndex(N, Control, WinTitle)`: choose by a 1-based index.
/// Measured on the same day: the control's `Value` becomes that index.
pub(crate) fn control_choose_index(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 1, line)?;
    let index = number_of(values, 0) as i64;
    rt.desktop()
        .gui_combo_select(number, &index.to_string(), false)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlChooseString(Text, Control, WinTitle)`: choose by the item's text.
pub(crate) fn control_choose_string(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 1, line)?;
    let text = text_of(values, 0);
    rt.desktop()
        .gui_combo_select(number, &text, true)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlGetChoice(Control, WinTitle)`: the text of the chosen item, or the
/// empty text when nothing is chosen.
pub(crate) fn control_get_choice(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 0, line)?;
    let (_index, text) = rt
        .desktop()
        .gui_combo_choice(number)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(text))
}

/// `ControlGetIndex(Control, WinTitle)`: the 1-based index of the chosen item.
pub(crate) fn control_get_index(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 0, line)?;
    let (index, _text) = rt
        .desktop()
        .gui_combo_choice(number)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Int(index))
}

/// `ControlDeleteItem(N, Control, WinTitle)`: remove an item by its 1-based
/// index. Measured on the same day: the array becomes one shorter.
pub(crate) fn control_delete_item(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 1, line)?;
    let index = number_of(values, 0) as i64;
    rt.desktop()
        .gui_combo_delete(number, &index.to_string())
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

/// `ControlFindItem(Text, Control, WinTitle)`: the 1-based index of the first
/// item that is this text, or zero. Measured on the same day.
pub(crate) fn control_find_item(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 1, line)?;
    let text = text_of(values, 0);
    rt.desktop()
        .gui_combo_find(number, &text)
        .map(Value::Int)
        .map_err(|e| desktop_failure(e, line))
}

/// `ControlShowDropDown` and `ControlHideDropDown`: open or close the pop-up of
/// a list-shaped control.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: both answer the empty text.
/// They have one handler each because the variant field of a row is the count's
/// answer/refusal flag and cannot carry which one this is.
fn the_drop_down_of_a_combo(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    show: bool,
) -> Result<Value, RuntimeError> {
    let number = the_number_of_a_combo(rt, values, 0, line)?;
    rt.desktop()
        .gui_combo_dropdown(number, show)
        .map_err(|e| desktop_failure(e, line))?;
    Ok(Value::Text(String::new()))
}

pub(crate) fn control_show_drop_down(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_drop_down_of_a_combo(rt, values, line, true)
}

pub(crate) fn control_hide_drop_down(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_drop_down_of_a_combo(rt, values, line, false)
}

/// `StatusBarGetText(Part, WinTitle)`: the text of the status bar.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: with part 1 and the title
/// of a window holding a StatusBar, it answers the text the bar was made with.
/// This tree carries one part. A window that is not the script's own is not
/// asked of the accessibility layer, which has no status bar of its own.
pub(crate) fn status_bar_get_text(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let title = text_of(values, 1);
    the_window_of_the_script(rt, &title, line)?;
    rt.desktop()
        .gui_status_text()
        .map(Value::Text)
        .map_err(|e| desktop_failure(e, line))
}

/// `StatusBarWait(Text, Seconds, Part, WinTitle)`: wait for the status bar to
/// hold a text.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: the match is a
/// case-sensitive SUBSTRING of part 1 ("status" matches "the status"), the
/// answer is 1 on a match and 0 when the seconds run out, and a part other
/// than 1 is refused with "Parameter #3 of StatusBarWait is invalid.".
/// The status text of this runtime cannot change while a script runs, so the
/// answer is known at once -- but the wait is honoured in shape, polling until
/// the timeout like `ClipWait` does.
pub(crate) fn status_bar_wait(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let wanted = text_of(values, 0);
    let seconds = number_of(values, 1);
    let part = number_of(values, 2);
    let title = text_of(values, 3);
    if part != 1.0 && values.len() > 2 {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(3, "StatusBarWait"),
            line,
        });
    }
    the_window_of_the_script(rt, &title, line)?;
    let limit = if values.len() > 1 && seconds > 0.0 {
        Some(seconds * 1000.0)
    } else if values.len() > 1 {
        Some(0.0)
    } else {
        None
    };
    let started = rt.now_ms();
    loop {
        let text = rt
            .desktop()
            .gui_status_text()
            .map_err(|e| desktop_failure(e, line))?;
        if text.contains(&wanted) {
            return Ok(Value::Int(1));
        }
        let waited = rt.now_ms().saturating_sub(started) as f64;
        let left = match limit {
            Some(limit) => {
                if waited >= limit {
                    return Ok(Value::Int(0));
                }
                limit - waited
            }
            None => {
                let left = rt.remaining_ms();
                if left == 0 {
                    return Ok(Value::Int(0));
                }
                left as f64
            }
        };
        rt.sleep_ms((left as u64).clamp(1, CLIP_POLL_MS));
    }
}

/// `ListViewGetContent(Options, Control, WinTitle)`: the rows of a list view,
/// cells by tabs and rows by line breaks.
///
/// Measured on the binary of v2.0.19 on 2026-11-10: with no options it answers
/// "alpha\t10\nbeta\t20", and the "Selected" option answers only the rows that
/// are chosen. The control is named by its `ClassNN` (`SysListView321`).
pub(crate) fn list_view_get_content(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let options = text_of(values, 0);
    let classnn = text_of(values, 1);
    let title = text_of(values, 2);
    the_window_of_the_script(rt, &title, line)?;
    if !rt.desktop().gui_is_open() {
        return Err(RuntimeError {
            message: TARGET_WINDOW.to_string(),
            line,
        });
    }
    let number = rt
        .desktop()
        .gui_number_named(&classnn)
        .map_err(|reason| desktop_failure(reason, line))?;
    let selected = options.eq_ignore_ascii_case("selected");
    rt.desktop()
        .gui_list_content(number as u64, selected)
        .map(Value::Text)
        .map_err(|e| desktop_failure(e, line))
}