ahk 0.3.0

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
//! The class types of AutoHotkey v2.
//!
//! `Map`, `Array`, `Buffer`, `File`, `Func`, `Gui`, `Menu` and `Hotkey`
//! are the classes the runtime carries. Each of them lives in its own
//! module, and this one is the registry that knows which is which.
//!
//! A class type of the runtime is not a class of the script: the script
//! cannot extend it, and its methods are the ones the runtime answers
//! for. The state of the object lives in the property table of the
//! object, and only the class module touches it.
//!
//! The ones that are shaped for Windows -- `Gui` and its parts, and
//! `Hotkey` -- are carried and answer with the reason they cannot work
//! here. The others work anywhere.
//!
//! The eleven tables of the binary are Array, Buffer, File, Func, Gui,
//! Gui.Control, Gui.ListView, Gui.Menu, Gui.StatusBar, Hotkey and Map.
//! The methods of the menu are in the table of `Gui.Menu`, and the
//! script calls the class `Menu`, so the registry answers for both.
use alloc::collections::BTreeMap;

use alloc::format;

use alloc::rc::Rc;

use alloc::string::String;

use alloc::string::ToString;

use alloc::vec::Vec;

use core::cell::RefCell;

use crate::runtime::{Detail, Object, Runtime, RuntimeError, RuntimeFailure, TypeName, Value, put};

pub(crate) mod array;

pub(crate) mod buffer;

pub(crate) mod clipboard;

pub(crate) mod enumerator;

pub(crate) mod error;

pub(crate) mod file;

pub(crate) mod func;

pub(crate) mod gui;

pub(crate) mod hotkey;

pub(crate) mod inputhook;

pub(crate) mod map;

pub(crate) mod regexmatchinfo;

pub(crate) mod thread;

pub(crate) mod keyinfo;

pub(crate) mod realthread;

pub(crate) mod varref;

pub(crate) mod timer;

pub(crate) mod scriptprocess;

pub(crate) mod propref;

pub(crate) mod typed;

/// The methods of the class types, with the name v2 spells them and
/// the number of the arguments they take.
///
/// The names are the ones of the binary of v2.0.19 and the numbers were
/// measured on it on 2026-10-29. The first argument of every one of them
/// is the object itself: the reference is the method, and the object is
/// one of the arguments of the call.
const METHODS: [(&str, &str, &str, i64, i64); 59] = [
    ("map", "set", "Set", 1, 1),
    ("map", "get", "Get", 2, 3),
    ("map", "has", "Has", 2, 2),
    ("map", "delete", "Delete", 2, 2),
    ("map", "clear", "Clear", 1, 1),
    ("map", "clone", "Clone", 1, 1),
    ("map", "__new", "__New", 1, 1),
    ("map", "__enum", "__Enum", 1, 2),
    ("array", "push", "Push", 1, 1),
    ("array", "pop", "Pop", 1, 1),
    ("array", "insertat", "InsertAt", 2, 2),
    ("array", "removeat", "RemoveAt", 2, 3),
    ("array", "delete", "Delete", 2, 2),
    ("array", "get", "Get", 2, 3),
    ("array", "has", "Has", 2, 2),
    ("array", "clone", "Clone", 1, 1),
    ("array", "__new", "__New", 1, 1),
    ("array", "__enum", "__Enum", 1, 2),
    ("buffer", "__new", "__New", 1, 3),
    ("func", "call", "Call", 1, 1),
    ("func", "isoptional", "IsOptional", 1, 1),
    ("func", "isbyref", "IsByRef", 1, 1),
    ("func", "bind", "Bind", 1, 1),
    // The enumerator is a function of its own kind, and the `Call` of it

    // is the turn of the enumeration. Measured on the binary of v2.0.19 on

    // 2026-10-31: the call takes no arguments at all, and two when it

    // hands out a key and a value.
    ("enumerator", "call", "Call", 1, 3),
    ("enumerator", "isoptional", "IsOptional", 1, 1),
    ("enumerator", "isbyref", "IsByRef", 1, 1),
    ("enumerator", "bind", "Bind", 1, 1),
    ("error", "__new", "__New", 1, 4),
    ("file", "read", "Read", 1, 2),
    ("file", "readline", "ReadLine", 1, 1),
    ("file", "readchar", "ReadChar", 1, 1),
    ("file", "readuchar", "ReadUChar", 1, 1),
    ("file", "readshort", "ReadShort", 1, 1),
    ("file", "readushort", "ReadUShort", 1, 1),
    ("file", "readint", "ReadInt", 1, 1),
    ("file", "readuint", "ReadUInt", 1, 1),
    ("file", "readint64", "ReadInt64", 1, 1),
    ("file", "readfloat", "ReadFloat", 1, 1),
    ("file", "readdouble", "ReadDouble", 1, 1),
    ("file", "write", "Write", 2, 2),
    ("file", "writeline", "WriteLine", 1, 2),
    ("file", "writechar", "WriteChar", 2, 2),
    ("file", "writeuchar", "WriteUChar", 2, 2),
    ("file", "writeshort", "WriteShort", 2, 2),
    ("file", "writeushort", "WriteUShort", 2, 2),
    ("file", "writeint", "WriteInt", 2, 2),
    ("file", "writeuint", "WriteUInt", 2, 2),
    ("file", "writeint64", "WriteInt64", 2, 2),
    ("file", "writefloat", "WriteFloat", 2, 2),
    ("file", "writedouble", "WriteDouble", 2, 2),
    ("file", "rawread", "RawRead", 2, 3),
    ("file", "rawwrite", "RawWrite", 2, 3),
    ("file", "seek", "Seek", 2, 3),
    ("file", "close", "Close", 1, 1),
    // The members of a match are read with the object as the first

    // argument, and `Len`, `Pos` and `Name` take the place of a group as

    // well.
    ("regexmatchinfo", "__enum", "__Enum", 1, 2),
    ("regexmatchinfo", "__get", "__Get", 3, 3),
    ("regexmatchinfo", "len", "Len", 1, 2),
    ("regexmatchinfo", "name", "Name", 2, 2),
    ("regexmatchinfo", "pos", "Pos", 1, 2),
];

/// The number of the arguments of the calls of the members.
///
/// Measured on the binary of v2.0.19 on 2026-10-30. The numbers are the
/// ones of the call the script writes: `m.Get("a")` takes one argument,
/// and `m.Get` as a value takes two, because the object is one of the
/// arguments of that one. A number of `-1` means that the call takes any
/// number of arguments.
///
/// The methods of the base object are the ones every object has, and the
/// class of them is `object`.
const CALLS: [(&str, &str, i64, i64); 65] = [
    ("object", "ownprops", 0, 0),
    ("object", "clone", 0, 0),
    ("object", "hasownprop", 1, 1),
    ("object", "defineprop", 2, 2),
    ("object", "deleteprop", 1, 1),
    ("object", "getownpropdesc", 1, 1),
    ("object", "hasprop", 1, 1),
    ("object", "hasmethod", 0, 2),
    ("object", "getmethod", 0, 2),
    ("object", "hasbase", 1, 1),
    ("map", "set", 0, -1),
    ("map", "get", 1, 2),
    ("map", "has", 1, 1),
    ("map", "delete", 1, 1),
    ("map", "clear", 0, 0),
    ("map", "clone", 0, 0),
    ("map", "__new", 0, -1),
    ("map", "__enum", 0, 1),
    ("array", "push", 0, -1),
    ("array", "pop", 0, 0),
    ("array", "insertat", 1, -1),
    ("array", "removeat", 1, 2),
    ("array", "delete", 1, 1),
    ("array", "get", 1, 2),
    ("array", "has", 1, 1),
    ("array", "clone", 0, 0),
    ("array", "__new", 0, -1),
    ("array", "__enum", 0, 1),
    ("buffer", "__new", 0, 2),
    ("func", "isoptional", 0, -1),
    ("func", "isbyref", 0, -1),
    ("func", "bind", 0, -1),
    // The call of an enumerator takes no arguments at all, and two when

    // it hands out a key and a value. Measured on the binary of v2.0.19

    // on 2026-10-31.
    ("enumerator", "call", 0, 2),
    ("error", "__new", 0, 3),
    ("file", "read", 0, 1),
    ("file", "readline", 0, 0),
    ("file", "readchar", 0, 0),
    ("file", "readuchar", 0, 0),
    ("file", "readshort", 0, 0),
    ("file", "readushort", 0, 0),
    ("file", "readint", 0, 0),
    ("file", "readuint", 0, 0),
    ("file", "readint64", 0, 0),
    ("file", "readfloat", 0, 0),
    ("file", "readdouble", 0, 0),
    ("file", "write", 1, 1),
    ("file", "writeline", 0, 1),
    ("file", "writechar", 1, 1),
    ("file", "writeuchar", 1, 1),
    ("file", "writeshort", 1, 1),
    ("file", "writeushort", 1, 1),
    ("file", "writeint", 1, 1),
    ("file", "writeuint", 1, 1),
    ("file", "writeint64", 1, 1),
    ("file", "writefloat", 1, 1),
    ("file", "writedouble", 1, 1),
    ("file", "rawread", 1, 2),
    ("file", "rawwrite", 1, 2),
    ("file", "seek", 1, 2),
    ("file", "close", 0, 0),
    // The members of a match: the call the script writes does not pass the

    // object, and `Name` needs the place of a group.
    ("regexmatchinfo", "__enum", 0, 1),
    ("regexmatchinfo", "__get", 2, 2),
    ("regexmatchinfo", "len", 0, 1),
    ("regexmatchinfo", "name", 1, 1),
    ("regexmatchinfo", "pos", 0, 1),
];

/// The class types that v2 makes with a call of their own.
///
/// The arity is the number of the arguments that the constructor takes,
/// and the two names are the ones that v2 puts in the `What` and in the
/// `Extra` of the failure when the call has the wrong number of
/// arguments.
///
/// Measured on the binary of v2.0.19 on 2026-10-31. A number of `-1`
/// means that the constructor takes any number of arguments: the `Array`
/// is made out of the values it is given. The classes that go through the
/// base object -- the `Class`, the `Object` and the classes of the
/// failures -- carry the name of the base in the `What`, and the `Menu`
/// carries its own.
const CONSTRUCTORS: [(&str, i64, i64, &str, &str); 15] = [
    ("array", 0, -1, "Array.Call", "Array.Prototype.__New"),
    ("buffer", 0, 2, "Buffer.Call", "Buffer.Prototype.__New"),
    ("class", 0, 0, "Object.Call", ""),
    (
        "clipboardall",
        0,
        2,
        "ClipboardAll.Call",
        "ClipboardAll.Prototype.__New",
    ),
    ("comobject", 1, 2, "", "ComObject.Call"),
    ("comvalue", 2, 3, "", "ComValue.Call"),
    ("error", 0, 3, "Object.Call", "Error.Prototype.__New"),
    ("float", 1, 1, "", "Float.Call"),
    ("gui", 0, 3, "Gui.Call", "Gui.Prototype.__New"),
    (
        "inputhook",
        0,
        3,
        "InputHook.Call",
        "InputHook.Prototype.__New",
    ),
    ("integer", 1, 1, "", "Integer.Call"),
    ("menu", 0, 0, "Menu.Call", ""),
    ("number", 1, 1, "", "Number.Call"),
    ("object", 0, 0, "Object.Call", ""),
    ("string", 1, 1, "", "String.Call"),
];

/// The class types that v2 does not make.
///
/// A function is written in the script or it is one of the built-ins,
/// and a file is made by the `FileOpen` built-in. Neither of the two is
/// a class that can be made, and v2 answers "Invalid base." to both. The
/// enumerator is made out of the `__Enum` of a value, and not by a call.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the `BoundFunc`,
/// the `Closure` and the `RegExMatchInfo` are classes of the dialect that
/// the runtime makes, and not a script: the call of them is refused with
/// "Invalid base." as well.
const NOT_MADE: [&str; 6] = [
    "boundfunc",
    "closure",
    "file",
    "func",
    "enumerator",
    "regexmatchinfo",
];

/// The name v2 gives to the call of the base object.
///
/// The classes of the runtime that v2 does not make are called through
/// the base object, and the base of them has no such thing.
const THE_CALL_OF_THE_BASE: &str = "Object.Call";

/// The names of the `ClipboardAll` class.
///
/// The class is the buffer of the clipboard, and the binary keeps the
/// names of it outside its tables of the methods.
const THE_CLIPBOARD_ALL: [&str; 2] = ["ptr", "size"];

/// The names of the `ComValue` class.
///
/// The COM objects are a thing of Windows, and this runtime does not
/// carry them: the names of the class are here, because they are the
/// surface of v2.
const THE_COM_VALUE: [&str; 1] = ["ptr"];

/// The names of the base object.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the table of the
/// base object is the one that follows the table of the `Map`, and it
/// holds six names. The `Base` is a property of every object, and the
/// binary does not keep it in the table of the methods.
const THE_BASE_OBJECT: [&str; 7] = [
    "base",
    "clone",
    "defineprop",
    "deleteprop",
    "getownpropdesc",
    "hasownprop",
    "ownprops",
];

/// The names of the base object that the binary keeps outside its table.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: every object has these
/// four methods, and the table of the base object does not hold them.
const THE_BASE_OBJECT_OUTSIDE: [&str; 4] = ["getmethod", "hasbase", "hasmethod", "hasprop"];

/// The members of a class value.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the class of a class
/// value is "Class", and it has the base, the prototype, the call of the
/// class and the initialiser of it.
const THE_CLASS_VALUE: [&str; 4] = ["base", "call", "prototype", "__init"];

/// The names of the methods of the base object, the way v2 spells them.
///
/// The binary spells five of them with the class in front, and the four
/// that the script asks about every day plainly.
const BASE: [(&str, &str); 10] = [
    ("ownprops", "Object.Prototype.OwnProps"),
    ("hasownprop", "Object.Prototype.HasOwnProp"),
    ("defineprop", "Object.Prototype.DefineProp"),
    ("deleteprop", "Object.Prototype.DeleteProp"),
    ("getownpropdesc", "Object.Prototype.GetOwnPropDesc"),
    ("clone", "Object.Prototype.Clone"),
    ("hasprop", "HasProp"),
    ("hasmethod", "HasMethod"),
    ("getmethod", "GetMethod"),
    ("hasbase", "HasBase"),
];

/// The names of the properties of the class types, the way v2 spells
/// them.
const PROPERTIES: [(&str, &str, &str); 28] = [
    ("map", "count", "Count"),
    ("map", "capacity", "Capacity"),
    ("map", "casesense", "CaseSense"),
    ("array", "length", "Length"),
    ("array", "capacity", "Capacity"),
    ("buffer", "size", "Size"),
    ("buffer", "ptr", "Ptr"),
    ("func", "name", "Name"),
    ("func", "minparams", "MinParams"),
    ("func", "maxparams", "MaxParams"),
    ("func", "isbuiltin", "IsBuiltin"),
    ("func", "isvariadic", "IsVariadic"),
    // The enumerator is a function of its own kind, and it carries the

    // values of a function.
    ("enumerator", "name", "Name"),
    ("enumerator", "minparams", "MinParams"),
    ("enumerator", "maxparams", "MaxParams"),
    ("enumerator", "isbuiltin", "IsBuiltin"),
    ("enumerator", "isvariadic", "IsVariadic"),
    ("file", "pos", "Pos"),
    ("file", "length", "Length"),
    ("file", "ateof", "AtEOF"),
    ("file", "encoding", "Encoding"),
    ("file", "handle", "Handle"),
    ("error", "message", "Message"),
    ("error", "what", "What"),
    ("error", "extra", "Extra"),
    ("error", "file", "File"),
    ("error", "line", "Line"),
    ("error", "stack", "Stack"),
];

/// The properties of the class types that may not be written.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the write of one of them
/// is refused with "Property is read-only.", the name of the property goes in
/// the `Extra` of the error, and the `What` is empty. The other properties
/// are written the way the class says: the capacity and the case of a map,
/// the length and the capacity of an array, the size of a buffer, the
/// properties of an error, and the place, the length and the encoding of a
/// file.
const READ_ONLY: [(&str, &[&str]); 5] = [
    ("map", &["count"]),
    ("buffer", &["ptr"]),
    (
        "func",
        &["name", "minparams", "maxparams", "isbuiltin", "isvariadic"],
    ),
    (
        "enumerator",
        &["name", "minparams", "maxparams", "isbuiltin", "isvariadic"],
    ),
    ("file", &["ateof", "handle"]),
];

/// Whether the property of a class type may not be written.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the write of it is
/// refused with "Property is read-only.".
pub(crate) fn the_property_is_read_only(class: &str, name: &str) -> bool {
    let class = class.to_lowercase();

    let name = name.to_lowercase();

    READ_ONLY
        .iter()
        .any(|(owner, names)| *owner == class && names.iter().any(|property| *property == name))
}

/// The members that the prototype of a class owns.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the prototype of a class
/// owns the class of the value and the members that the class declares -- the
/// methods of it and the properties of it. The names are in the order of
/// v2, and the case of them does not count.
const PROTOTYPE_MEMBERS: [(&str, &[&str]); 16] = [
    (
        "object",
        &[
            "Clone",
            "DefineProp",
            "DeleteProp",
            "GetOwnPropDesc",
            "HasOwnProp",
            "OwnProps",
        ],
    ),
    (
        "map",
        &[
            "__Enum",
            "__Item",
            "__New",
            "Capacity",
            "CaseSense",
            "Clear",
            "Clone",
            "Count",
            "Delete",
            "Get",
            "Has",
            "Set",
        ],
    ),
    (
        "array",
        &[
            "__Enum", "__Item", "__New", "Capacity", "Clone", "Delete", "Get", "Has", "InsertAt",
            "Length", "Pop", "Push", "RemoveAt",
        ],
    ),
    ("buffer", &["__New", "Ptr", "Size"]),
    ("error", &["__New"]),
    (
        "file",
        &[
            "AtEOF",
            "Close",
            "Encoding",
            "Handle",
            "Length",
            "Pos",
            "RawRead",
            "RawWrite",
            "Read",
            "ReadChar",
            "ReadDouble",
            "ReadFloat",
            "ReadInt",
            "ReadInt64",
            "ReadLine",
            "ReadShort",
            "ReadUChar",
            "ReadUInt",
            "ReadUShort",
            "Seek",
            "Write",
            "WriteChar",
            "WriteDouble",
            "WriteFloat",
            "WriteInt",
            "WriteInt64",
            "WriteLine",
            "WriteShort",
            "WriteUChar",
            "WriteUInt",
            "WriteUShort",
        ],
    ),
    (
        "func",
        &[
            "Bind",
            "Call",
            "IsBuiltIn",
            "IsByRef",
            "IsOptional",
            "IsVariadic",
            "MaxParams",
            "MinParams",
            "Name",
        ],
    ),
    ("enumerator", &[]),
    (
        "menu",
        &[
            "Add",
            "AddStandard",
            "Check",
            "ClickCount",
            "Default",
            "Delete",
            "Disable",
            "Enable",
            "Handle",
            "Insert",
            "Rename",
            "SetColor",
            "SetIcon",
            "Show",
            "ToggleCheck",
            "ToggleEnable",
            "Uncheck",
        ],
    ),
    (
        "gui",
        &[
            "__Enum",
            "__Item",
            "__New",
            "Add",
            "AddActiveX",
            "AddButton",
            "AddCheckBox",
            "AddComboBox",
            "AddCustom",
            "AddDateTime",
            "AddDDL",
            "AddDropDownList",
            "AddEdit",
            "AddGroupBox",
            "AddHotkey",
            "AddLink",
            "AddListBox",
            "AddListView",
            "AddMonthCal",
            "AddPic",
            "AddPicture",
            "AddProgress",
            "AddRadio",
            "AddSlider",
            "AddStatusBar",
            "AddTab",
            "AddTab2",
            "AddTab3",
            "AddText",
            "AddTreeView",
            "AddUpDown",
            "BackColor",
            "Destroy",
            "Flash",
            "FocusedCtrl",
            "GetClientPos",
            "GetPos",
            "Hide",
            "Hwnd",
            "MarginX",
            "MarginY",
            "Maximize",
            "MenuBar",
            "Minimize",
            "Move",
            "Name",
            "OnEvent",
            "Opt",
            "Restore",
            "SetFont",
            "Show",
            "Submit",
            "Title",
        ],
    ),
    ("clipboardall", &["__New"]),
    (
        "inputhook",
        &[
            "__New",
            "BackspaceIsUndo",
            "CaseSensitive",
            "EndKey",
            "EndMods",
            "EndReason",
            "FindAnywhere",
            "InProgress",
            "Input",
            "KeyOpt",
            "Match",
            "MinSendLevel",
            "NotifyNonText",
            "OnChar",
            "OnEnd",
            "OnKeyDown",
            "OnKeyUp",
            "Start",
            "Stop",
            "Timeout",
            "VisibleNonText",
            "VisibleText",
            "Wait",
        ],
    ),
    (
        "regexmatchinfo",
        &[
            "__Enum", "__Get", "__Item", "Count", "Len", "Mark", "Name", "Pos",
        ],
    ),
    ("boundfunc", &[]),
    ("closure", &[]),
    ("class", &[]),
];

/// The members of the prototype of a class that are methods.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the prototype of a class
/// answers `HasMethod` with the names of the methods of it. The `__Item` of a
/// class is not one of them, and the `__Class` of the value is not one
/// either.
const PROTOTYPE_METHODS: [(&str, &[&str]); 16] = [
    (
        "object",
        &[
            "Clone",
            "DefineProp",
            "DeleteProp",
            "GetOwnPropDesc",
            "HasOwnProp",
            "OwnProps",
        ],
    ),
    (
        "map",
        &[
            "__Enum", "__New", "Clear", "Clone", "Delete", "Get", "Has", "Set",
        ],
    ),
    (
        "array",
        &[
            "__Enum", "__New", "Clone", "Delete", "Get", "Has", "InsertAt", "Pop", "Push",
            "RemoveAt",
        ],
    ),
    ("buffer", &["__New"]),
    ("error", &["__New"]),
    (
        "file",
        &[
            "Close",
            "RawRead",
            "RawWrite",
            "Read",
            "ReadChar",
            "ReadDouble",
            "ReadFloat",
            "ReadInt",
            "ReadInt64",
            "ReadLine",
            "ReadShort",
            "ReadUChar",
            "ReadUInt",
            "ReadUShort",
            "Seek",
            "Write",
            "WriteChar",
            "WriteDouble",
            "WriteFloat",
            "WriteInt",
            "WriteInt64",
            "WriteLine",
            "WriteShort",
            "WriteUChar",
            "WriteUInt",
            "WriteUShort",
        ],
    ),
    ("func", &["Bind", "Call", "IsByRef", "IsOptional"]),
    ("enumerator", &[]),
    (
        "menu",
        &[
            "Add",
            "AddStandard",
            "Check",
            "Delete",
            "Disable",
            "Enable",
            "Insert",
            "Rename",
            "SetColor",
            "SetIcon",
            "Show",
            "ToggleCheck",
            "ToggleEnable",
            "Uncheck",
        ],
    ),
    (
        "gui",
        &[
            "__Enum",
            "__New",
            "Add",
            "AddActiveX",
            "AddButton",
            "AddCheckBox",
            "AddComboBox",
            "AddCustom",
            "AddDateTime",
            "AddDDL",
            "AddDropDownList",
            "AddEdit",
            "AddGroupBox",
            "AddHotkey",
            "AddLink",
            "AddListBox",
            "AddListView",
            "AddMonthCal",
            "AddPic",
            "AddPicture",
            "AddProgress",
            "AddRadio",
            "AddSlider",
            "AddStatusBar",
            "AddTab",
            "AddTab2",
            "AddTab3",
            "AddText",
            "AddTreeView",
            "AddUpDown",
            "Destroy",
            "Flash",
            "GetClientPos",
            "GetPos",
            "Hide",
            "Maximize",
            "Minimize",
            "Move",
            "OnEvent",
            "Opt",
            "Restore",
            "SetFont",
            "Show",
            "Submit",
        ],
    ),
    ("clipboardall", &["__New"]),
    ("inputhook", &["__New", "KeyOpt", "Start", "Stop", "Wait"]),
    ("regexmatchinfo", &["__Enum", "__Get", "Len", "Name", "Pos"]),
    ("boundfunc", &[]),
    ("closure", &[]),
    ("class", &[]),
];

/// The classes whose prototype is not a prototype.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the prototype of an
/// `Any`, of a `ComObject` and of a `ComValue` is not one: it has no method
/// at all, and the refusal says 'This value of type "Prototype" has no method
/// named "OwnProps".'.
const NOT_A_PROTOTYPE: [&str; 4] = ["any", "comobject", "comvalue", "varref"];

/// The name of a method of the base object, the way v2 spells it.
///
/// The binary spells five of them with the class in front, and the four
/// that the script asks about every day plainly.
pub(crate) fn the_name_of_a_method_of_the_base_object(method: &str) -> String {
    let lower = method.to_lowercase();

    BASE.iter()
        .find(|(name, _)| *name == lower)
        .map(|(_, spelled)| spelled.to_string())
        .unwrap_or_else(|| method.to_string())
}

/// Whether the name is the name of a method of the base object.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the methods of the
/// base object are the methods of every object, and they are inherited.
pub(crate) fn the_base_object_has_the_method(name: &str) -> bool {
    let name = name.to_lowercase();

    CALLS
        .iter()
        .any(|(owner, member, _, _)| *owner == "object" && *member == name)
}

/// The name and the number of the arguments of a method of a class.
///
/// `None` means that the class type has no method of that name.
pub(crate) fn the_method_of(class: &str, method: &str) -> Option<(&'static str, i64, i64)> {
    let class = class.to_lowercase();

    let method = method.to_lowercase();

    METHODS
        .iter()
        .find(|(owner, name, _, _, _)| *owner == class && *name == method)
        .map(|(_, _, spelled, min, max)| (*spelled, *min, *max))
}

/// The number of the arguments of the call the script writes.
///
/// `None` means that the runtime does not know the number of the
/// arguments of that member.
pub(crate) fn the_arity_of(class: &str, method: &str) -> Option<(i64, i64)> {
    let class = class.to_lowercase();

    let method = method.to_lowercase();

    let own = CALLS
        .iter()
        .find(|(owner, name, _, _)| *owner == class && *name == method);

    let found = match own {
        Some(found) => Some(found),

        // Every object has the methods of the base object.
        None => CALLS
            .iter()
            .find(|(owner, name, _, _)| *owner == "object" && *name == method),
    };

    found.map(|(_, _, min, max)| (*min, *max))
}

/// The methods that every class has as static ones.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the methods of the
/// base object are the static methods of every class -- `HasProp`,
/// `HasMethod`, `GetMethod`, `HasBase`, `OwnProps`, `HasOwnProp`,
/// `DefineProp`, `DeleteProp`, `GetOwnPropDesc` and `Clone` -- and the
/// call of the class is one of them.
pub(crate) fn the_static_methods_of_a_class() -> [&'static str; 11] {
    [
        "call",
        "clone",
        "defineprop",
        "deleteprop",
        "getmethod",
        "getownpropdesc",
        "hasbase",
        "hasmethod",
        "hasownprop",
        "hasprop",
        "ownprops",
    ]
}

/// The name of a member of a class, the way v2 names it in a failure.
///
/// A method of a class type is "Map.Prototype.Get", and a method of the
/// base object keeps the name it has: "Object.Prototype.OwnProps", or
/// "HasProp" for the four that the script asks about every day.
pub(crate) fn the_name_of(class: &str, member: &str) -> String {
    format!("{}.Prototype.{}", the_spelling_of(class), member)
}

/// The name of the method of a class, the way v2 spells it.
///
/// The methods of the base object have a name of their own, and the
/// methods of the class types are in the table of the methods.
fn the_spelling_of_the_method(class: &str, method: &str) -> String {
    let lower = method.to_lowercase();

    if let Some((_, spelled)) = BASE.iter().find(|(name, _)| *name == lower) {
        return spelled.to_string();
    }

    the_method_of(class, method)
        .map(|(spelled, _, _)| spelled.to_string())
        .unwrap_or_else(|| method.to_string())
}

/// The name of the property of a class, the way v2 spells it.
fn the_spelling_of_the_property(class: &str, property: &str) -> String {
    let lower = property.to_lowercase();

    PROPERTIES
        .iter()
        .find(|(owner, name, _)| *owner == class && *name == lower)
        .map(|(_, _, spelled)| spelled.to_string())
        .unwrap_or_else(|| property.to_string())
}

/// The members that the prototype of a class owns.
///
/// The list is empty for a class that declares no member of its own: the
/// classes of the errors other than the `Error`, and the `BoundFunc`, the
/// `Closure` and the `Class`.
pub(crate) fn the_members_of_the_prototype(class: &str) -> &'static [&'static str] {
    let lower = class.to_lowercase();

    PROTOTYPE_MEMBERS
        .iter()
        .find(|(owner, _)| *owner == lower)
        .map(|(_, members)| *members)
        .unwrap_or(&[])
}

/// The methods that the prototype of a class owns.
pub(crate) fn the_methods_of_the_prototype(class: &str) -> &'static [&'static str] {
    let lower = class.to_lowercase();

    PROTOTYPE_METHODS
        .iter()
        .find(|(owner, _)| *owner == lower)
        .map(|(_, methods)| *methods)
        .unwrap_or(&[])
}

/// The property that the prototype of a class owns, if it owns one.
///
/// The members that are not methods are the properties of the class, and the
/// `__Item` of a class is one of them.
pub(crate) fn the_property_of_the_prototype(class: &str, property: &str) -> Option<&'static str> {
    let lower = property.to_lowercase();

    let methods = the_methods_of_the_prototype(class);

    the_members_of_the_prototype(class)
        .iter()
        .find(|member| member.to_lowercase() == lower)
        .filter(|_| !methods.iter().any(|method| method.to_lowercase() == lower))
        .copied()
}

/// Whether the prototype of a class is a prototype at all.
///
/// The `Any`, the `ComObject` and the `ComValue` have no prototype: the value
/// that stands for it has no method, and the refusal says so.
pub(crate) fn the_prototype_is_not_one(class: &str) -> bool {
    NOT_A_PROTOTYPE.contains(&class.to_lowercase().as_str())
}

/// The name of a method of a class, the way v2 names it in a failure.
///
/// The methods of the base object keep the name they have, and the
/// methods of the class types carry the class in front.
fn the_full_name_of(class: &str, method: &str) -> String {
    let lower = method.to_lowercase();

    if BASE.iter().any(|(name, _)| *name == lower) {
        return the_spelling_of_the_method(class, method);
    }

    the_name_of(class, &the_spelling_of_the_method(class, method))
}

/// The failure of a member of a class, with the name of the member in
/// it.
///
/// v2 carries the name of the member in the `What` of the error. A
/// failure that carries a name of its own keeps it.
pub(crate) fn named(failure: RuntimeFailure, what: &str) -> RuntimeFailure {
    match failure {
        RuntimeFailure::Error(error) => RuntimeFailure::Detailed(
            error,
            Detail {
                what: what.to_string(),

                extra: String::new(),
            },
        ),

        RuntimeFailure::Detailed(error, mut detail) => {
            if detail.what.is_empty() {
                detail.what = what.to_string();
            }

            RuntimeFailure::Detailed(error, detail)
        }

        other => other,
    }
}

/// The failure of a member of a class, with the value that failed.
///
/// v2 carries the value the member complained about in the `Extra` of
/// the error: the key of a map, the place of an array.
pub(crate) fn the_failure_with(message: &str, extra: &str, line: u32) -> RuntimeFailure {
    RuntimeFailure::Detailed(
        RuntimeError {
            message: message.to_string(),

            line,
        },
        Detail {
            what: String::new(),

            extra: extra.to_string(),
        },
    )
}

/// The failure of a call that does not have the number of the arguments
/// the member wants.
///
/// v2 checks the number of the arguments when the script writes the
/// call, and the name of the member goes in the `Extra` of the error,
/// and nothing goes in the `What`.
pub(crate) fn the_arity_failure(
    class: &str,

    method: &str,

    message: &str,

    line: u32,
) -> RuntimeFailure {
    RuntimeFailure::Detailed(
        RuntimeError {
            message: message.to_string(),

            line,
        },
        Detail {
            what: String::new(),

            extra: the_full_name_of(class, method),
        },
    )
}

/// The failure of a call that goes through a value of a method of a
/// class type.
///
/// v2 names the method that made the call in the `What` of the error,
/// and the method that was called in the `Extra`.
pub(crate) fn the_arity_failure_of_a_method(
    class: &str,

    method: &str,

    message: &str,

    line: u32,
) -> RuntimeFailure {
    RuntimeFailure::Detailed(
        RuntimeError {
            message: message.to_string(),

            line,
        },
        Detail {
            what: the_name_of("func", "Call"),

            extra: the_full_name_of(class, method),
        },
    )
}

/// The number of the arguments that the constructor of a class type
/// takes, and the names that v2 puts in a failure of it.
///
/// `None` means that the class type is made with any number of
/// arguments, or that the runtime does not know the number.
fn the_constructor_of(class: &str) -> Option<(i64, i64, &'static str, &'static str)> {
    let class = class.to_lowercase();

    // The classes of the errors are made the way the root of them is.

    let owner = if error::is_a_class(&class) {
        "error"
    } else {
        class.as_str()
    };

    CONSTRUCTORS
        .iter()
        .find(|(name, _, _, _, _)| *name == owner)
        .map(|(_, min, max, what, extra)| (*min, *max, *what, *extra))
}

/// The failure of a class type that v2 does not make.
///
/// The call goes through the base object, and the base of the class has
/// no such thing: "Invalid base.".
fn the_failure_of_a_class_that_is_not_made(line: u32) -> RuntimeFailure {
    RuntimeFailure::Detailed(
        RuntimeError {
            message: "Invalid base.".to_string(),

            line,
        },
        Detail {
            what: THE_CALL_OF_THE_BASE.to_string(),

            extra: String::new(),
        },
    )
}

/// The failure of a constructor that has too many arguments.
///
/// v2 names the call in the `What` of the error, and the constructor in
/// the `Extra`.
fn the_arity_failure_of_a_constructor(
    what: &str,

    extra: &str,

    message: &str,

    line: u32,
) -> RuntimeFailure {
    RuntimeFailure::Detailed(
        RuntimeError {
            message: message.to_string(),

            line,
        },
        Detail {
            what: what.to_string(),

            extra: extra.to_string(),
        },
    )
}

/// The class types the runtime carries.
///
/// `Object` is the root of every class: v2 has it, and every object of
/// the tree is one.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the classes of the
/// dialect are the ones that a script can read as a class, and these are
/// they. The hotkey is the one that is not a name of its own: the name
/// `Hotkey` is a function of the dialect, and the class of a hotkey is
/// the class of the object that the function makes.
pub(crate) const TYPES: [&str; 26] = [
    // The reference of a variable is a class of v2 too: measured on the

    // binary of v2.0.19 on 2026-11-10, Type(VarRef) is Class and

    // IsSet(&x) then `x` is VarRef is one.
    "any",
    "array",
    "boundfunc",
    "buffer",
    "class",
    "clipboardall",
    "closure",
    "comobject",
    "comvalue",
    "enumerator",
    "error",
    "file",
    "float",
    "func",
    "gui",
    "hotkey",
    "inputhook",
    "integer",
    "map",
    "menu",
    "number",
    "object",
    "primitive",
    "regexmatchinfo",
    "string",
    "varref",
];

/// Whether the name is a class type of the runtime.
pub(crate) fn is_type(name: &str) -> bool {
    let name = name.to_lowercase();

    TYPES.contains(&name.as_str()) || error::is_a_class(&name)
}

/// Whether the name is a class that a script can read.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: `x := Hotkey` is a
/// function of the dialect, and not the class of a hotkey. Every other
/// class of the runtime is a name of its own, and a script reads it as
/// the class.
pub fn is_a_name_of_a_class(name: &str) -> bool {
    let name = name.to_lowercase();

    (TYPES.contains(&name.as_str()) && name != "hotkey") || error::is_a_class(&name)
}

/// The class types the runtime carries, the way v2 spells them.
pub fn the_class_types() -> Vec<String> {
    let mut names: Vec<String> = TYPES
        .iter()
        .filter(|name| **name != "hotkey")
        .map(|name| the_spelling_of(name))
        .collect();

    for (name, spelled, _) in error::CLASSES.iter() {
        if *name != "error" {
            names.push(spelled.to_string());
        }
    }

    names
}

/// The classes whose class value owns the call of it.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the class value of
/// the `Map` owns the call and the prototype, and the class value of the
/// `Error` owns the prototype alone. The classes that a script calls are
/// the ones that own the call.
const THE_CLASSES_THAT_OWN_THE_CALL: [&str; 10] = [
    "object",
    "map",
    "array",
    "buffer",
    "menu",
    "inputhook",
    "clipboardall",
    "gui",
    "comobject",
    "comvalue",
];

/// Whether the class value of the class owns the call of it.
///
/// The classes of the errors are not among them, and neither are the
/// functions: a `Func` and a `BoundFunc` are made by a definition, and not
/// by a call.
pub(crate) fn the_class_owns_the_call(class: &str) -> bool {
    THE_CLASSES_THAT_OWN_THE_CALL.contains(&class.to_lowercase().as_str())
}

/// The classes of v2 that this runtime does not carry.
///
/// The COM objects are a thing of Windows, and this runtime does not
/// carry them. A script reads the name of the class -- the `ComObject`
/// and the `ComValue` are classes of the dialect -- and the call of it
/// fails with the reason of the machine.
///
/// The number of the arguments is checked before that reason: the
/// dialect checks it first, and a script that calls the `ComObject`
/// without the name of the class is told that it forgot it.
const THE_CLASSES_THAT_ARE_NOT_HERE: [&str; 2] = ["comobject", "comvalue"];

/// The reason of a class of v2 that this runtime does not carry.
///
/// The COM objects are a thing of Windows, and this runtime does not
/// carry them.
fn the_failure_of_a_class_that_is_not_here(line: u32) -> RuntimeFailure {
    RuntimeFailure::Error(RuntimeError {
        message: "the COM objects are a thing of Windows, and this runtime does not carry them."
            .to_string(),

        line,
    })
}

/// The kind of an argument of the `ComValue`.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the first argument
/// is the type of the value and the third one is the flags of the
/// wrapper, and the two are numbers. The value in the middle is
/// anything.
///
/// The check of the kind comes before the reason of the machine: the
/// dialect refuses the call before it tries to make the COM object.
fn the_kind_of_a_com_value_argument(
    index: usize,

    value: Option<&Value>,

    line: u32,
) -> Option<RuntimeFailure> {
    let value = value?;

    match value {
        Value::Int(_) | Value::Float(_) => None,

        other => Some(RuntimeFailure::Detailed(
            RuntimeError {
                message: crate::runtime::requires(index, "ComValue.Call", TypeName::Number, other),

                line,
            },
            Detail {
                what: "ComValue.Call".to_string(),

                extra: other.to_text(),
            },
        )),
    }
}

/// The failure of a class that a script cannot call.
///
/// The `Any` is the type of any value, and it is not a class that can be
/// made: the call of it goes through the `Call` method of the class, and
/// a class has none. Measured on the binary of v2.0.19 on 2026-10-31:
/// "This value of type "Class" has no method named "Call".". The failure
/// is of the class `MethodError`.
fn the_failure_of_a_class_that_cannot_be_called(rt: &Runtime, line: u32) -> RuntimeFailure {
    // The class value of the runtime, so that the refusal names the kind

    // of it: a class is a "Class".

    let value = rt
        .class_value_of("any")
        .unwrap_or_else(|| class_value("any"));

    rt.no_method(&value, "Call", line)
}

/// The class that a class of the dialect extends.
///
/// Measured on the binary of v2.0.19 on 2026-10-31: the base of the
/// `Object` is the `Any`, and the base of every other class is the
/// `Object`. The `Any` is the root of the tree of the classes, and it
/// has no base.
///
/// The errors of v2 are a tree of their own, and the enumerator is a
/// function of its own kind: the two have a base of their own.
pub(crate) fn the_base_class_of_a_class(class: &str) -> Option<&'static str> {
    let class = class.to_lowercase();

    if class == "any" {
        return None;
    }

    if class == "object" || class == "primitive" {
        return Some("any");
    }

    // The primitive types of v2 are a tree of their own: the `Number` and the

    // `String` are `Primitive`, and the `Integer` and the `Float` are

    // `Number`. Measured on the binary of v2.0.19: `3 is Number` and `3 is

    // Primitive` are one, and `1.5 is Integer` is zero.

    if let Some(base) = the_base_of_the_primitive(&class) {
        return Some(base);
    }

    // The errors of v2 are a tree of their own, and the enumerator is a

    // function of its own kind: the two have a base of their own.

    if let Some(base) = the_base_of(&class) {
        return Some(base);
    }

    Some("object")
}

/// The base of a primitive type of v2.
///
/// Measured on the binary of the v2.0.19: the `Primitive` is under the
/// `Any`, the `Number` and the `String` are under the `Primitive`, and the
/// `Integer` and the `Float` are under the `Number`.
fn the_base_of_the_primitive(class: &str) -> Option<&'static str> {
    match class {
        "number" | "string" => Some("primitive"),

        "integer" | "float" => Some("number"),

        "primitive" => Some("any"),

        _ => None,
    }
}

/// The base of a primitive type of v2, for the chain of the `is`.
///
/// It is the function the runtime walks the chain with when it meets a name
/// that is not a class of the script and not a class type of the tree: the
/// `Integer` and the `Float` are under the `Number`, the `Number` and the
/// `String` under the `Primitive`, and the `Primitive` under the `Any`.
pub(crate) fn the_base_of_the_primitive_of_the_class(class: &str) -> Option<&'static str> {
    the_base_of_the_primitive(&class.to_lowercase())
}

/// The class a class type of the runtime derives from.
///
/// The errors of v2 are a tree of their own: a `PropertyError` is a
/// `MemberError` and an `UnsetError` as well, and every one of them is
/// an `Error`. The other classes of the runtime are the root of it.
pub(crate) fn the_base_of(class: &str) -> Option<&'static str> {
    // The enumerator is a function of its own kind: it derives from

    // `Func`, and the docs of v2 say so.

    if class.eq_ignore_ascii_case("enumerator") {
        return Some("func");
    }

    // Measured on the binary of v2.0.19 on 2026-11-10: a `Closure` is a

    // `Func` as well -- `f() is Closure` and `f() is Func` are both one when

    // the function of `f` reads a local of the function that has it.

    if class.eq_ignore_ascii_case("closure") {
        return Some("func");
    }

    error::the_base_of(class)
}

/// The value of a class type: the class itself.
///
/// The class carries its prototype, the way a class of the script does:
/// the base of an object of this type is the prototype of it.
pub(crate) fn class_value(name: &str) -> Value {
    let mut table = BTreeMap::new();

    // The name of the class is the one v2 spells: the name of the

    // runtime carries it in lower case. v2 does not show it, and the

    // tree keeps it under a key of its own.

    put(
        &mut table,
        crate::runtime::CLASS_NAME,
        Value::Text(the_spelling_of(name)),
    );

    put(
        &mut table,
        "prototype",
        crate::runtime::prototype_value(name),
    );

    Value::Object(Rc::new(RefCell::new(Object {
        class: name.to_lowercase(),

        properties: table,
    })))
}

/// The object of a class type, with nothing in it yet.
pub(crate) fn object(class: &str) -> Value {
    Value::Object(Rc::new(RefCell::new(Object {
        class: class.to_lowercase(),

        properties: BTreeMap::new(),
    })))
}

/// The object of a class type, with a property in it.
pub(crate) fn object_with(class: &str, properties: Vec<(&str, Value)>) -> Value {
    let mut table = BTreeMap::new();

    for (name, value) in properties {
        put(&mut table, name, value);
    }

    Value::Object(Rc::new(RefCell::new(Object {
        class: class.to_lowercase(),

        properties: table,
    })))
}

/// The class types the runtime carries, and the name that v2 spells them
/// with.
///
/// The dialect spells some of them with more than one capital, and the
/// name of the class is the name that the dialect uses.
const THE_SPELLINGS: [(&str, &str); 7] = [
    ("boundfunc", "BoundFunc"),
    ("clipboardall", "ClipboardAll"),
    ("closure", "Closure"),
    ("comobject", "ComObject"),
    ("comvalue", "ComValue"),
    ("inputhook", "InputHook"),
    ("regexmatchinfo", "RegExMatchInfo"),
];

/// The name of a class of the runtime, the way v2 spells it.
///
/// The classes of the errors have a spelling of their own: `TypeError`,
/// and not `Typeerror`.
pub(crate) fn the_spelling_of(name: &str) -> String {
    if let Some(spelled) = error::the_spelling_of(name) {
        return spelled;
    }

    let lower = name.to_lowercase();

    if let Some((_, spelled)) = THE_SPELLINGS.iter().find(|(key, _)| *key == lower) {
        return spelled.to_string();
    }

    // The classes of the `ks` dialect are spelled the way KeySharp spells

    // them: `PropRef` and not `Propref`.

    if let Some((_, spelled)) = THE_KS_SPELLINGS.iter().find(|(key, _)| *key == lower) {
        return spelled.to_string();
    }

    let mut spelled = name.to_string();

    if let Some(first) = spelled.get_mut(0..1) {
        first.make_ascii_uppercase();
    }

    spelled
}

/// The spelling of the classes that the `ks` dialect adds.
///
/// The v2.0.19 has none of them, and a script of the v2 cannot make one,
/// so the table is only read for the objects of the `ks` dialect.
const THE_KS_SPELLINGS: &[(&str, &str)] = &[
    ("int8", "Int8"),
    ("uint8", "UInt8"),
    ("int16", "Int16"),
    ("uint16", "UInt16"),
    ("int32", "Int32"),
    ("uint32", "UInt32"),
    ("int64", "Int64"),
    ("intptr", "IntPtr"),
    ("float32", "Float32"),
    ("float64", "Float64"),
    ("struct", "Struct"),
    ("thread", "Thread"),
    ("propref", "PropRef"),
    ("timer", "Timer"),
    ("keyinfo", "KeyInfo"),
    ("realthread", "RealThread"),
    ("scriptprocess", "ScriptProcess"),
    ("argumenterror", "ArgumentError"),
    ("unsupportederror", "UnsupportedError"),
];

/// The object a class type makes.
///
/// `None` means the name is not a class type of the runtime.
pub(crate) fn construct(
    class: &str,

    arguments: &[Value],

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    // A class type that v2 does not make: the call goes through the

    // base object, and the base of the class has no such thing.

    if NOT_MADE.contains(&class.to_lowercase().as_str()) {
        return Some(Err(the_failure_of_a_class_that_is_not_made(line)));
    }

    // The number of the arguments of the constructor is checked before

    // the object is made, and before the reason of the machine: the

    // dialect checks the number of the arguments first.

    if let Some((min, max, what, extra)) = the_constructor_of(class) {
        let count = arguments.len() as i64;

        if count < min || (max >= 0 && count > max) {
            let message = if count < min {
                "Too few parameters passed to function."
            } else {
                "Too many parameters passed to function."
            };

            return Some(Err(the_arity_failure_of_a_constructor(
                what, extra, message, line,
            )));
        }
    }

    // The `Any` is the type of any value, and it is not a class that can

    // be made.

    if class.eq_ignore_ascii_case("any") {
        return Some(Err(the_failure_of_a_class_that_cannot_be_called(rt, line)));
    }

    // The COM objects are a thing of Windows, and this runtime does not

    // carry them. The kinds of the arguments are the dialect's, and they

    // come first.

    if class.eq_ignore_ascii_case("comvalue") {
        if let Some(failure) = the_kind_of_a_com_value_argument(1, arguments.first(), line) {
            return Some(Err(failure));
        }

        if let Some(failure) = the_kind_of_a_com_value_argument(3, arguments.get(2), line) {
            return Some(Err(failure));
        }
    }

    // The `ks` dialect makes the object of the `InputHook` even though

    // this runtime has no hook: the object carries the settings of it,

    // and the hook itself is not installed.

    if class.eq_ignore_ascii_case("inputhook")
        && rt
            .dialect()
            .carries_the_member_of_the_extension("inputhook", "beforehotkeys")
    {
        return Some(inputhook::construct_the_extension(rt, line));
    }

    if THE_CLASSES_THAT_ARE_NOT_HERE.contains(&class.to_lowercase().as_str()) {
        return Some(Err(the_failure_of_a_class_that_is_not_here(line)));
    }

    // The errors of the `ks` dialect: the `ArgumentError` and the

    // `UnsupportedError` are made the way the errors of v2 are.

    if rt.dialect().carries_the_class_of_the_extension(class) {
        if let Some(result) = error::construct_the_extension(class, arguments, rt, line) {
            return Some(result);
        }

        if class.eq_ignore_ascii_case("scriptprocess") {
            return scriptprocess::construct(class, arguments, rt, line);
        }

        if class.eq_ignore_ascii_case("propref") {
            return propref::construct(class, arguments, rt, line);
        }
    }

    // The errors of v2 are a tree of classes, and every one of them is

    // made the way the root of it is.

    if error::is_a_class(class) {
        return Some(
            error::construct(class, arguments, rt, line)
                .map_err(|failure| named(failure, &the_name_of(class, "__New"))),
        );
    }

    // The classes of the numbers and of the text are the conversions of the

    // dialect: the call of one converts its argument, and what the class

    // itself is does not change.

    if let Some(converted) = the_conversion(class, arguments, rt, line) {
        return Some(converted);
    }

    // The typed numbers of the `ks` dialect: a struct of one field, of

    // the width the class names. The v2.0.19 has none of them, and the

    // dialect is what says so.

    if rt.dialect().carries_the_class_of_the_extension(class) {
        if let Some(result) = typed::construct(class, arguments, rt, line) {
            return Some(result);
        }
    }

    let made = match class.to_lowercase().as_str() {
        "array" => Some(array::construct(arguments, rt, line)),

        "buffer" => Some(buffer::construct(arguments, rt, line)),

        "clipboardall" => Some(clipboard::construct(arguments, rt, line)),

        "hotkey" => Some(hotkey::construct(arguments, rt, line)),

        "map" => Some(map::construct(arguments, rt, line)),
        "thread" if rt.dialect().carries_the_class_of_the_extension("thread") => {
            Some(thread::construct(arguments, rt, line))
        }

        "gui" | "menu" | "gui.control" | "gui.listview" | "gui.menu" | "gui.statusbar" => {
            Some(gui::construct(class, arguments, rt, line))
        }

        _ => None,
    };

    made.map(|result| result.map_err(|failure| named(failure, &the_name_of(class, "__New"))))
}

/// The object a class of a number or of the text makes: a conversion.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: `Integer("0x1F")` is 31,
/// `Integer(3.9)` is 3, `Float("1.5")` is 1.5, `Number("0x10")` is 16,
/// `Number("1.5")` is 1.5 and `String(42)` is "42". The classes themselves
/// stay what they are -- `Type(Integer)` is "Class" and `Integer is Class` is
/// 1 -- and only the call of one is the conversion.
///
/// A value of the wrong kind is refused with the name of the call in the
/// `What` and the value in the `Extra`, and `String` of an object asks its
/// `ToString` method.
fn the_conversion(
    class: &str,

    arguments: &[Value],

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    let what = match class.to_lowercase().as_str() {
        "integer" => "Integer.Call",

        "float" => "Float.Call",

        "number" => "Number.Call",

        "string" => "String.Call",

        _ => return None,
    };

    let value = arguments
        .first()
        .cloned()
        .unwrap_or_else(|| Value::Text(String::new()));

    // The value that is not a number is refused with the kind it got, and

    // the value itself goes in the `Extra` of the failure.

    let wants_a_number = || -> Option<RuntimeFailure> {
        if crate::builtins::is_numeric_value(&value) {
            return None;
        }

        Some(RuntimeFailure::Detailed(
            RuntimeError {
                message: crate::runtime::requires(1, what, TypeName::Number, &value),

                line,
            },
            Detail {
                what: what.to_string(),

                extra: value.to_text(),
            },
        ))
    };

    match class.to_lowercase().as_str() {
        "integer" => match wants_a_number() {
            Some(failure) => Some(Err(failure)),

            None => Some(Ok(Value::Int(crate::builtins::token_to_int64(&value)))),
        },

        "float" => match wants_a_number() {
            Some(failure) => Some(Err(failure)),

            None => Some(Ok(Value::Float(crate::builtins::token_to_double(&value)))),
        },

        "number" => match wants_a_number() {
            Some(failure) => Some(Err(failure)),

            None => Some(Ok(match &value {
                Value::Int(number) => Value::Int(*number),

                Value::Float(number) => Value::Float(*number),

                // The number a text holds keeps the shape it was written

                // with: `"0x10"` is the integer 16 and `"1.5"` the float.
                Value::Text(text) if crate::builtins::text_holds_an_integer(text) => {
                    Value::Int(crate::builtins::text_to_int64(text))
                }

                Value::Text(text) => Value::Float(crate::builtins::text_to_double(text)),

                other => other.clone(),
            })),
        },

        _ => Some(the_string_conversion(&value, rt, line, what)),
    }
}

/// `String(Value)`: the text of a value.
///
/// Measured on the binary of v2.0.19 on 2026-11-09: an object is asked for
/// its `ToString` method, and one that has none answers "This value of type
/// `Map` has no method named `ToString`.".
fn the_string_conversion(
    value: &Value,

    rt: &mut Runtime,

    line: u32,

    what: &str,
) -> Result<Value, RuntimeFailure> {
    match value {
        Value::Int(number) => Ok(Value::Text(number.to_string())),

        Value::Float(number) => Ok(Value::Text(crate::float_text::the_text_of(*number))),

        Value::Text(text) => Ok(Value::Text(text.clone())),

        Value::Object(_) => {
            let arguments = Vec::new();

            match rt.call_a_method_of_an_object(value, "ToString", &arguments, line) {
                Ok(answer) => Ok(Value::Text(answer.to_text())),

                Err(failure) => Err(named(failure, what)),
            }
        }

        other => Err(named(
            RuntimeFailure::Error(RuntimeError {
                message: format!(
                    "This value of type \"{}\" has no method named \"ToString\".",
                    other.the_kind()
                ),

                line,
            }),
            what,
        )),
    }
}

/// A method of a class type.
///
/// `None` means the method is not one of this class's: the runtime then
/// says the value has no such method.
pub(crate) fn call(
    class: &str,

    method: &str,

    this: &Value,

    arguments: &[Value],

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    // `__Item` is the method behind the index syntax, and a script may

    // call it by its name. The classes that have one answer it here.

    if method.eq_ignore_ascii_case("__item") {
        let key = arguments
            .first()
            .cloned()
            .unwrap_or(Value::Text(String::new()));

        if let Some(result) = item(class, &key, this, rt, line) {
            return Some(result);
        }
    }

    let answer = call_once(class, method, this, arguments, rt, line);

    // The name of a method is spelled the way the script spells it, and

    // the module matches the names of the table of the binary. The

    // second try is the name in lower case.

    match answer {
        Some(result) => {
            Some(result.map_err(|failure| named(failure, &the_full_name_of(class, method))))
        }

        None => {
            let lower = method.to_lowercase();

            if lower == method {
                return None;
            }

            call_once(class, &lower, this, arguments, rt, line).map(|result| {
                result.map_err(|failure| named(failure, &the_full_name_of(class, method)))
            })
        }
    }
}

/// A method of a class type, with the name as it is.
/// A member of a text, the way the `ks` dialect adds them.
///
/// The `ks` dialect gives the class of the `String` two members that the
/// v2.0.19 does not have: `StartsWith` and `EndsWith`. The comparison is
/// the ordinal one -- the case matters -- and the answer is one when the
/// text begins or ends with the other, and zero when it does not.
fn the_member_of_a_text(
    method: &str,

    this: &Value,

    arguments: &[Value],

    _rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    let Value::Text(text) = this else {
        return None;
    };

    let other = match arguments.first() {
        Some(value) => value.to_text(),

        None => {
            return Some(Err(RuntimeFailure::Error(RuntimeError {
                message: "Too few parameters passed to function.".to_string(),

                line,
            })));
        }
    };

    let answer = match method.to_lowercase().as_str() {
        "startswith" => text.starts_with(&other),

        "endswith" => text.ends_with(&other),

        _ => return None,
    };

    Some(Ok(Value::Int(if answer { 1 } else { 0 })))
}

fn call_once(
    class: &str,

    method: &str,

    this: &Value,

    arguments: &[Value],

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    match class.to_lowercase().as_str() {
        "array" => array::call(method, this, arguments, rt, line),

        "buffer" => buffer::call(method, this, arguments, rt, line),

        "enumerator" => enumerator::call(method, this, arguments, rt, line),

        "error" => error::call(method, this, arguments, rt, line),

        "file" => file::call(method, this, arguments, rt, line),

        "func" | "closure" | "boundfunc" => func::call(method, this, arguments, rt, line),

        "hotkey" => hotkey::call(method, this, arguments, rt, line),

        "map" => map::call(method, this, arguments, rt, line),

        "regexmatchinfo" => regexmatchinfo::call(method, this, arguments, rt, line),

        "thread" if rt.dialect().carries_the_class_of_the_extension("thread") => {
            thread::call(method, this, arguments, rt, line)
        }

        "scriptprocess"
            if rt
                .dialect()
                .carries_the_class_of_the_extension("scriptprocess") =>
        {
            scriptprocess::call(class, method, this, arguments, rt, line)
        }

        "realthread"
            if rt
                .dialect()
                .carries_the_class_of_the_extension("realthread") =>
        {
            realthread::call(class, method, this, arguments, rt, line)
        }

        // The static method of a typed class: `Struct.At` and the

        // ones beside it. The guard is the dialect's, so the v2

        // keeps refusing the name it does not have.
        _ if rt.dialect().carries_the_class_of_the_extension(class) && typed::is_a_class(class) => {
            typed::the_static_call(class, method, arguments, line)
        }

        "string" => the_member_of_a_text(method, this, arguments, rt, line),

        // The methods of the base object are the methods of every object,

        // and they are answered by the runtime.
        "object" => rt.base_method(this, method, arguments, line),

        "gui" | "menu" | "gui.control" | "gui.listview" | "gui.menu" | "gui.statusbar" => {
            gui::call(class, method, this, arguments, rt, line)
        }

        _ => None,
    }
}

/// The call of a value.
///
/// The value is called, and not the `Call` method of it: v2 tells the two
/// apart in the failure of the number of the arguments.
pub(crate) fn call_the_value(
    class: &str,

    this: &Value,

    arguments: &[Value],

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    match class.to_lowercase().as_str() {
        "func" | "closure" | "boundfunc" => func::call_the_value(this, arguments, rt, line),

        // The enumerator is a function of its own kind, and the call of

        // its value is the turn of the enumeration.
        "enumerator" => enumerator::call_the_value(this, arguments, rt, line),

        _ => call(class, "call", this, arguments, rt, line),
    }
}

pub(crate) fn property(
    class: &str,

    name: &str,

    this: &Value,

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    match class.to_lowercase().as_str() {
        "array" => array::property(name, this, rt, line),

        "buffer" => buffer::property(name, this, rt, line),

        "enumerator" => enumerator::property(name, this, rt, line),

        "error" => error::property(name, this, rt, line),

        "file" => file::property(name, this, rt, line),

        "func" | "closure" => func::property(name, this, rt, line),

        "hotkey" => hotkey::property(name, this, rt, line),

        "map" => map::property(name, this, rt, line),

        "regexmatchinfo" => regexmatchinfo::property(name, this, rt, line),

        "thread" if rt.dialect().carries_the_class_of_the_extension("thread") => {
            thread::property(name, this, rt, line)
        }

        "inputhook" => inputhook::property_the_extension(name, this, rt, line),

        _ if rt.dialect().carries_the_class_of_the_extension(class) => {
            propref::property(class, name, this, line)
                .or_else(|| scriptprocess::property(class, name, this, rt, line))
                .or_else(|| timer::property(class, name, this, rt, line))
                .or_else(|| keyinfo::property(class, name, this, rt, line))
                .or_else(|| realthread::property(class, name, this, rt, line))
                .or_else(|| varref::property(class, name, this, rt, line))
                .or_else(|| typed::property(class, name, this, line))
        }

        "gui" | "menu" | "gui.control" | "gui.listview" | "gui.menu" | "gui.statusbar" => {
            gui::property(class, name, this, rt, line)
        }

        _ => None,
    }
}

/// A property of a class type that is read with the parameters of the
/// access: `m.Len[2]`.
///
/// `None` means the class does not own the name with parameters: the
/// runtime then reads the value of the property and indexes it, which is
/// what the members of the other classes do. `Some` means the member
/// answered the whole access, brackets and all.
pub(crate) fn property_with_params(
    class: &str,

    name: &str,

    params: &[Value],

    this: &Value,

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    match class.to_lowercase().as_str() {
        "regexmatchinfo" => regexmatchinfo::property_with_params(name, params, this, rt, line),

        _ => None,
    }
}

/// A property of a class type that is written.
///
/// `None` means the class does not own the name: the runtime then
/// writes it in the property table of the object.
pub(crate) fn set_property(
    class: &str,

    name: &str,

    this: &Value,

    value: Value,

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<(), RuntimeFailure>> {
    let written = match class.to_lowercase().as_str() {
        "array" => array::set_property(name, this, value, rt, line),

        "buffer" => buffer::set_property(name, this, value, rt, line),

        "error" => error::set_property(name, this, value, rt, line),

        "file" => file::set_property(name, this, value, rt, line),

        "func" | "closure" => func::set_property(name, this, value, rt, line),

        "hotkey" => hotkey::set_property(name, this, value, rt, line),

        "map" => map::set_property(name, this, value, rt, line),

        "inputhook" => inputhook::set_property_the_extension(name, this, value, rt, line),

        "gui" | "menu" | "gui.control" | "gui.listview" | "gui.menu" | "gui.statusbar" => {
            gui::set_property(class, name, this, value, rt, line)
        }

        _ => None,
    };

    let what = the_name_of(
        class,
        &format!("{}.Set", the_spelling_of_the_property(class, name)),
    );

    written.map(|result| result.map_err(|failure| named(failure, &what)))
}

/// The item of an object: the `__Item` of the class.
///
/// `None` means the class has no `__Item` of its own.
pub(crate) fn item(
    class: &str,

    key: &Value,

    this: &Value,

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    let read = match class.to_lowercase().as_str() {
        "array" => array::item(key, this, rt, line),

        "file" => file::item(key, this, rt, line),

        "map" => map::item(key, this, rt, line),

        "regexmatchinfo" => regexmatchinfo::item(key, this, rt, line),

        _ => None,
    };

    let what = the_name_of(class, "__Item.Get");

    read.map(|result| result.map_err(|failure| named(failure, &what)))
}

/// Write an item of an object of a class type.
///
/// `None` means the class has no way to write an item of its own.
pub(crate) fn set_item(
    class: &str,

    key: &Value,

    this: &Value,

    value: Value,

    rt: &mut Runtime,

    line: u32,
) -> Option<Result<(), RuntimeFailure>> {
    let written = match class {
        "array" => array::set_item(key, this, value, rt, line),

        "map" => map::set_item(key, this, value, rt, line),

        _ => None,
    };

    let what = the_name_of(class, "__Item.Set");

    written.map(|result| result.map_err(|failure| named(failure, &what)))
}

/// The names of v2 that a class type answers.
///
/// A name is a method of the class or a property of it, and the two are
/// told apart by the module that owns the class. The names are in lower
/// case, the way the script spells them.
pub fn names(class: &str) -> Vec<&'static str> {
    if error::is_a_class(class) {
        return error::names();
    }

    match class.to_lowercase().as_str() {
        "array" => array::names(),

        "buffer" => buffer::names(),

        "clipboardall" => THE_CLIPBOARD_ALL.to_vec(),

        "comvalue" => THE_COM_VALUE.to_vec(),

        "enumerator" => enumerator::names(),

        "error" => error::names(),

        "file" => file::names(),

        "func" | "closure" => func::names(),

        "hotkey" => hotkey::names(),

        "map" => map::names(),

        "gui" => gui::names("gui"),

        "menu" | "gui.menu" => gui::names("gui.menu"),

        "gui.control" => gui::names("gui.control"),

        "gui.listview" => gui::names("gui.listview"),

        "gui.statusbar" => gui::names("gui.statusbar"),

        "gui.treeview" => gui::names("gui.treeview"),

        "inputhook" => inputhook::NAMES.to_vec(),

        "regexmatchinfo" => regexmatchinfo::names(),

        "thread" => thread::names(),

        // The classes of the `ks` dialect: they carry the members the

        // extensions add, and the table of the names is where the probe

        // of the surface looks for them.
        "keyinfo" => keyinfo::names(),

        "realthread" => realthread::names(),

        "scriptprocess" => scriptprocess::names(),

        "timer" => timer::names(),

        _ if typed::is_a_class(class) => typed::names(),

        "propref" => propref::names(),

        "class" => THE_CLASS_VALUE.to_vec(),

        "object" => THE_BASE_OBJECT
            .iter()
            .chain(THE_BASE_OBJECT_OUTSIDE.iter())
            .copied()
            .collect(),

        _ => Vec::new(),
    }
}

/// Whether a class type answers the name.
///
/// The case of the name does not matter: the script spells a name the
/// way it likes.
pub fn carries(class: &str, name: &str) -> bool {
    let name = name.to_lowercase();

    names(class).iter().any(|carried| *carried == name)
}

/// The class types that this runtime does not carry.
///
/// The name of the class is a name of the dialect, and a script reads it
/// as the class. The members of it are not carried: the tree says so when
/// a script asks for one, and it does not say that the name is not there
/// -- the name is there, the tree does not carry it.
///
/// The base object is not one of them: the plain object of a script is
/// one, and the refusal of a member that is not there keeps the words of
/// the dialect.
const THE_CLASSES_THAT_ARE_NOT_CARRIED: [&str; 6] = [
    "any",
    "class",
    "clipboardall",
    "comobject",
    "comvalue",
    "inputhook",
];

/// The reason of a name of a class that this runtime does not carry.
pub(crate) fn the_reason_of_a_class_that_is_not_carried(class: &str) -> Option<&'static str> {
    let class = class.to_lowercase();

    if THE_CLASSES_THAT_ARE_NOT_CARRIED.contains(&class.as_str()) {
        return Some("this runtime does not carry that class yet.");
    }

    None
}

pub(crate) mod menu;

/// The number that names a control of a window of the script.
///
/// It is the `Hwnd` the control object carries, which is the number `gui_add`
/// answered. A value that is not such an object has none.
pub(crate) fn the_number_of_a_control(this: &Value) -> Option<u64> {
    if let Value::Object(object) = this {
        if let Some(property) = object.borrow().properties.get("hwnd") {
            if let Value::Int(number) = property.value {
                return Some(number as u64);
            }
        }
    }
    None
}