ahk 0.6.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
//! The names of the v1 that the tree answers now.
//!
//! Measured on the binary of AutoHotkey v1.1.37.02: the
//! answer of each one of them, and the way the argument of the ones that
//! ask for a name arrives.
//!
//! The handler of a name of the v1 that the v2 shares is the handler of the
//! v2, and the handler of the names that are here is one of their own.

use alloc::format;
use alloc::string::{String, ToString};

use crate::ast::BinaryOp;
use crate::runtime::{Runtime, RuntimeError, Value};

/// The letters that the v1 does not accept in the name of a variable.
///
/// Measured on the binary of AutoHotkey v1.1.37.02
/// (the probe of the measurement): the name that the script builds may not have a space,
/// a tab, or one of the characters that are special in an expression. The
/// `#`, the `$` and the `@` are legal in the name of a variable, even
/// though they are special somewhere else.
pub(crate) fn the_illegal_letters_of_a_name() -> &'static [char] {
    &[
        ' ', '\t', '!', '"', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<',
        '=', '>', '?', '[', '\\', ']', '^', '`', '{', '|', '}', '~',
    ]
}

/// The place of the argument of this function that asks for the name of a
/// variable.
///
/// Measured on the binary of v1.1.37.02: the `IsSet` asks
/// for the name of the variable and not for its value -- `IsSet(y)` asks
/// whether the variable `y` has a value, and not whether the value of `y`
/// is the name of a variable -- and the `IsByRef` asks for the name as
/// well. The `IsFunc` asks for the value.
pub(crate) fn the_place_of_the_argument_that_wants_the_name(name: &str) -> Option<usize> {
    match name.to_lowercase().as_str() {
        "isset" | "isbyref" => Some(0),
        _ => None,
    }
}

/// The place of the argument of this function that asks for the variable of
/// the caller and not for its value.
///
/// Measured on the binary of v1.1.37.02: the
/// `VarSetCapacity` takes the variable itself and not its value --
/// `VarSetCapacity(y, 100)` empties `y`, and a target that is not a
/// variable is answered with zero -- and the variable is the first
/// argument. The `StrReplace` takes the variable that receives the number
/// of the replacements, and that variable is the fourth argument.
/// Whether every argument of this function that is a naked variable keeps
/// the variable of the caller.
///
/// Measured on the binary of v1.1.37.02: the `DllCall` of
/// the v1 writes the answer of the machine into the variable that the
/// parameter names. The source of the v1 says it at the line 13619 of
/// `script2.cpp`: "Output parameters are copied back only if its
/// counterpart parameter is a naked variable."
pub(crate) fn every_argument_that_is_a_variable_keeps_it(name: &str) -> bool {
    name.eq_ignore_ascii_case("DllCall")
}

/// The place of the argument of this function that asks for the variable of
/// the caller and not for its value.
pub(crate) fn the_place_of_the_argument_that_wants_the_variable(name: &str) -> Option<usize> {
    match name.to_lowercase().as_str() {
        "varsetcapacity" => Some(0),
        "strreplace" => Some(3),
        // The target of a `NumPut`/`NumGet` is a variable or an address:
        // a bare variable goes as the reference of its memory, and an
        // expression goes as the number that is the address.
        "numput" => Some(1),
        "numget" => Some(0),
        // Read in the CHM of the v1.1.37.02 (`LoadPicture.htm`): the third
        // parameter is `OutImageType`, the name of the variable that the
        // command writes into.
        "loadpicture" => Some(2),
        // `RegExMatch(Haystack, Needle, OutputVar, StartingPos)` and
        // `RegExReplace(Haystack, Needle, Repl, OutputVarCount, Limit, Start)`.
        "regexmatch" => Some(2),
        "regexreplace" => Some(3),
        // `LV_GetText(OutputVar, RowNumber, ColumnNumber)` and
        // `TV_GetText(OutputVar, ItemID)`.
        "lv_gettext" | "tv_gettext" => Some(0),
        _ => None,
    }
}

/// `SetFormat, Integer, H`: the format of the numbers of the v1.
///
/// Measured on the binary of v1.1.37.02: the number type is
/// "Integer", "IntegerFast", "Float" or "FloatFast", the format of the
/// whole numbers is "D", "H" or "h", and the format of the floats is
/// "<width>.<decimals>" with an optional "e" for the scientific notation.
/// The value that is not a format is refused with "Parameter #2 invalid."
/// and the value in the `Extra`.
pub(crate) fn set_format(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = |index: usize| {
        values
            .get(index)
            .map(|value| value.to_text())
            .unwrap_or_default()
            .trim()
            .to_string()
    };
    let number_type = text(0);
    let format = text(1);
    match super::parameters::the_kind_of_a_number(&number_type) {
        Some(super::parameters::TheKindOfANumber::Integer) => {
            let format = match super::parameters::the_format_of_the_whole_numbers(&format) {
                Some(format) => format,
                None => {
                    return Err(RuntimeError {
                        message: format!("Parameter #2 invalid.\n     Specifically: {format}"),
                        line,
                    });
                }
            };
            rt.set_integer_format(format);
        }
        Some(super::parameters::TheKindOfANumber::Float) => {
            let format = match super::parameters::the_format_of_the_floats(&format) {
                Some(format) => format,
                None => {
                    return Err(RuntimeError {
                        message: format!("Parameter #2 invalid.\n     Specifically: {format}"),
                        line,
                    });
                }
            };
            rt.set_float_format(format);
        }
        None => {
            return Err(RuntimeError {
                message: format!("Parameter #1 invalid.\n     Specifically: {number_type}"),
                line,
            });
        }
    }
    Ok(Value::Text(String::new()))
}

/// `AutoTrim, On`: the trim of the text of a legacy assignment.
///
/// Measured on the binary of v1.1.37.02: the command turns
/// the trim on and off, and the value that it does not know is refused with
/// "Parameter #1 invalid." and the value in the `Extra`.
pub(crate) fn auto_trim(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = the_one_parameter_of_a_command(values);
    let trimmed = text.trim();
    match super::parameters::the_switch_of_the_v1(trimmed) {
        Some(trim) => rt.set_auto_trim(trim),
        None => {
            return Err(RuntimeError {
                message: format!("Parameter #1 invalid.\n     Specifically: {trimmed}"),
                line,
            });
        }
    }
    Ok(Value::Text(String::new()))
}

/// `SetBatchLines, 20`: the number of the lines that the script runs at once.
///
/// Measured on the binary of v1.1.37.02: the parameter is a
/// whole number, and the value that is not one is refused with "Parameter #1
/// invalid." and the value in the message. The hex is a whole number as well
/// -- the "0x10" is sixteen -- and the number that is written is the one that
/// the name of the variable says: the "007" is seven. The zero is the default
/// of the dialect, and it is ten.
pub(crate) fn set_batch_lines(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = the_one_parameter_of_a_command(values);
    let trimmed = text.trim();
    let number = match trimmed.parse::<i64>() {
        Ok(number) => number,
        // The hex of the v1 is a whole number as well.
        Err(_) if super::numbers::the_text_is_a_hex(trimmed) => {
            super::numbers::the_whole_number_of_a_hex(trimmed)
        }
        Err(_) => {
            return Err(RuntimeError {
                message: format!("Parameter #1 invalid.\n     Specifically: {trimmed}"),
                line,
            });
        }
    };
    // The zero is the default of the dialect, and it is ten.
    let number = if number == 0 { 10 } else { number };
    rt.set_batch_lines(&number.to_string());
    Ok(Value::Text(String::new()))
}

/// The text of the parameter of a command of the v1 that takes one.
///
/// Measured on the binary of v1.1.37.02: the command takes the
/// parameter that it wants, and the text that is left of the line goes into it,
/// with a comma and a space between: the "AutoTrim, On, extra" is the
/// "On, extra", and it is refused because it is not "On".
pub(crate) fn the_one_parameter_of_a_command(values: &[Value]) -> String {
    let mut text = String::new();
    for (index, value) in values.iter().enumerate() {
        if index > 0 {
            text.push_str(", ");
        }
        text.push_str(&value.to_text());
    }
    text
}

/// `StringCaseSense, On`: the sense of the case of the comparisons.
///
/// Measured on the binary of v1.1.37.02: the command takes
/// "On", "Off" or "Locale", and the numbers one and zero are the two
/// first. The value that it does not know is refused with "Parameter #1
/// invalid." and the value in the `Extra`.
pub(crate) fn string_case_sense(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = the_one_parameter_of_a_command(values);
    let trimmed = text.trim();
    let sense = match super::parameters::the_case_sense_of_the_v1(trimmed) {
        Some(sense) => sense,
        None => {
            return Err(RuntimeError {
                message: format!("Parameter #1 invalid.\n     Specifically: {trimmed}"),
                line,
            });
        }
    };
    rt.set_case_sense(sense);
    Ok(Value::Text(String::new()))
}

/// `DetectHiddenText, On`: the text of the hidden windows is read.
///
/// Measured on the binary of AutoHotkey v1.1.37.02: the v1
/// takes the word "On" and the word "Off" -- and the numbers one and zero --
/// and the v2 takes a value that is true when it is not empty.
pub(crate) fn set_detect_hidden_text_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = super::parameters::the_switch_of_the_v1(
        &values
            .first()
            .map(|value| value.to_text())
            .unwrap_or_default(),
    )
    .unwrap_or(false);
    crate::settings::set_detect_hidden_text(rt, &[Value::Int(on as i64)], line, 0)
}

/// `DetectHiddenWindows, On`: the windows that are hidden are found.
///
/// Measured on the binary of AutoHotkey v1.1.37.02: the v1
/// takes the word "On" and the word "Off" -- and the numbers one and zero --
/// and the v2 takes a value that is true when it is not empty.
pub(crate) fn set_detect_hidden_windows_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = super::parameters::the_switch_of_the_v1(
        &values
            .first()
            .map(|value| value.to_text())
            .unwrap_or_default(),
    )
    .unwrap_or(false);
    crate::settings::set_detect_hidden_windows(rt, &[Value::Int(on as i64)], line, 0)
}

/// `SetStoreCapsLockMode, On`: whether the state of the caps lock is put back.
///
/// Measured on the binary of AutoHotkey v1.1.37.02: the v1
/// takes the word "On" and the word "Off" -- and the numbers one and zero --
/// and the v2 takes a value that is true when it is not empty.
pub(crate) fn set_store_caps_lock_mode_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let on = super::parameters::the_switch_of_the_v1(
        &values
            .first()
            .map(|value| value.to_text())
            .unwrap_or_default(),
    )
    .unwrap_or(false);
    crate::settings::set_store_caps_lock_mode(rt, &[Value::Int(on as i64)], line, 0)
}

/// `CoordMode, Mouse, Screen`: the way the coordinates are read.
///
/// Measured on the binary of v1.1.37.02: the v1 does not
/// check the target -- the "abc" changes nothing -- and the mode that it
/// does not know sets every mode to the "Event". The v2 refuses the target
/// and the mode that it does not know.
pub(crate) fn coord_mode_of_the_v1(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let target = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let relative = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    crate::settings::set_the_coord_mode_of_the_v1(&target, &relative);
    Ok(Value::Text(String::new()))
}

/// `SetControlDelay, 20`: the pause after a change of a control.
///
/// Measured on the binary of v1.1.37.02: the v1 does not
/// check the parameter -- the "abc" is zero and the "20abc" is zero -- and
/// the number that does not fit in the machine wraps around it. The v2
/// refuses a parameter that is not a number and a delay that is out of the
/// range of the machine.
pub(crate) fn set_control_delay_of_the_v1(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let delay = crate::v1::the_number_of_a_text(&text)
        .and_then(|value| value.to_number())
        .unwrap_or(0.0) as i32;
    let previous = crate::settings::set_the_control_delay_of_the_v1(delay);
    Ok(Value::Int(previous as i64))
}

/// `SetWinDelay, 20`: the pause after a windowing function.
///
/// Measured on the binary of v1.1.37.02: the v1 does not
/// check the parameter -- the "abc" is zero -- and the v2 refuses a
/// parameter that is not a number.
pub(crate) fn set_win_delay_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let text = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let delay = crate::v1::the_number_of_a_text(&text)
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    crate::settings::set_win_delay(rt, &[Value::Float(delay)], line, 0)
}

/// `SetMouseDelay, 20`: the pause after a movement of the mouse.
///
/// Measured on the binary of v1.1.37.02: the v1 does not
/// check the mode -- the "abc" is not the "Play" -- and the v2 refuses it.
pub(crate) fn set_mouse_delay_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let delay = values
        .first()
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    let mode = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let mode = if mode.trim().eq_ignore_ascii_case("play") {
        "Play"
    } else {
        ""
    };
    crate::settings::set_mouse_delay(
        rt,
        &[Value::Float(delay), Value::Text(mode.to_string())],
        line,
        0,
    )
}

/// `SetKeyDelay, 20`: the pause between the keys.
///
/// Measured on the binary of v1.1.37.02: the v1 does not
/// check the mode -- the "abc" is not the "Play" -- and the v2 refuses it.
pub(crate) fn set_key_delay_of_the_v1(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let delay = values
        .first()
        .and_then(|value| value.to_number())
        .unwrap_or(0.0);
    let mode = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let mode = if mode.trim().eq_ignore_ascii_case("play") {
        "Play"
    } else {
        ""
    };
    crate::settings::set_key_delay(
        rt,
        &[Value::Float(delay), Value::Text(mode.to_string())],
        line,
        0,
    )
}

/// `FileEncoding, UTF-8`: the encoding the files are opened with.
///
/// Measured on the binary of v1.1.37.02: the text that is
/// empty changes nothing, and the v2 refuses it.
pub(crate) fn file_encoding_of_the_v1(
    _rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    if name.trim().is_empty() {
        return Ok(Value::Text(crate::settings::file_encoding().to_string()));
    }
    crate::settings::set_file_encoding(&name)
        .map(|encoding| Value::Text(encoding.to_string()))
        .map_err(|message| RuntimeError { message, line })
}

/// The text of a value of a command, without the quotes that surround it.
///
/// Measured on the binary of v1.1.37.02: the numbers of the
/// `Transform` are the numbers of the text without its quotes: `Ceil, "1.2"`
/// is 2, and `Abs, "-5"` is "5". The `Asc` and the `Deref` see the text as
/// it is.
fn the_text_without_the_quotes(text: &str) -> &str {
    let text = text.trim();
    if text.len() >= 2 && text.starts_with('"') && text.ends_with('"') {
        return &text[1..text.len() - 1];
    }
    text
}

/// Whether the command of this name has a body.
///
/// Measured on the binary of v1.1.37.02: the `IfInString`,
/// the `IfNotInString` and the `IfMsgBox` have an action: the command that
/// is on the same line, the block, or the statement of the next line.
pub(crate) fn the_command_has_a_body(name: &str) -> bool {
    matches!(
        name.to_lowercase().as_str(),
        "ifinstring"
            | "ifnotinstring"
            | "ifmsgbox"
            | "ifexist"
            | "ifnotexist"
            | "ifequal"
            | "ifnotequal"
            | "ifless"
            | "iflessorequal"
            | "ifgreater"
            | "ifgreaterorequal"
            | "ifwinactive"
            | "ifwinnotactive"
            | "ifwinexist"
            | "ifwinnotexist"
    )
}

/// Whether the command of this name is the `else` of the v1.
///
/// Measured on the binary of v1.1.37.02: the `else` of the v1
/// is a command of its own, and it takes no parameter.
pub(crate) fn the_command_is_the_else(name: &str) -> bool {
    name.to_lowercase() == "else"
}

/// The condition of the `IfInString` of the v1.
///
/// Measured on the binary of v1.1.37.02: the command holds
/// when the text of the needle is in the variable, and the sense of the
/// case says whether the letters of them are the same. The needle that is
/// not there is a failure.
pub(crate) fn if_in_string(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_search(rt, values, line, "IfInString")
}

/// The condition of the `IfNotInString` of the v1.
///
/// Measured on the binary of v1.1.37.02: the command is the
/// other side of the `IfInString`.
pub(crate) fn if_not_in_string(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_search(rt, values, line, "IfNotInString")
}

/// The condition of a search of the v1 that has a body.
///
/// Measured on the binary of v1.1.37.02: the command holds
/// when the text of the needle is in the variable, and the sense of the
/// case says whether the letters of them are the same.
///
/// The needle that is empty is a refusal of the load, and not of the run:
/// the number of the parameters is checked there, and the needle that is
/// written as nothing does not count. The needle that becomes empty at the
/// run -- the substitution of a name that has no value -- is a text that is
/// in every text, and the command holds.
fn the_condition_of_the_search(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    name: &str,
) -> Result<Value, RuntimeError> {
    let haystack = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let needle = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let holds = crate::runtime::the_text_contains(&haystack, &needle, rt.case_sense().the_method());
    Ok(Value::Int(if name == "IfNotInString" {
        !holds
    } else {
        holds
    } as i64))
}

/// The condition of the `IfMsgBox` of the v1.
///
/// Measured on the binary of v1.1.37.02: the command holds
/// when the person pressed the button that is named. The message box of
/// this runtime has no buttons, and the button that was pressed is not
/// there: the condition is false.
pub(crate) fn if_msg_box(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(Value::Int(0))
}

/// `IfExist, FilePattern`: the file or the folder is there.
pub(crate) fn if_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_existence(rt, values, line, false)
}

/// `IfNotExist, FilePattern`: the other side of the `IfExist`.
pub(crate) fn if_not_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_existence(rt, values, line, true)
}

/// The condition of the existence of a file: the attributes of the pattern
/// are not empty when the file or the folder is there.
fn the_condition_of_existence(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    negated: bool,
) -> Result<Value, RuntimeError> {
    let pattern = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let attributes = rt
        .desktop()
        .attributes_of_the_pattern(&pattern, "")
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    let holds = !attributes.concat().is_empty();
    Ok(Value::Int((holds ^ negated) as i64))
}

/// `IfEqual, Var, Value`: the comparison of the legacy `if`.
pub(crate) fn if_equal(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::Equal)
}

/// `IfNotEqual, Var, Value`: the other side of the `IfEqual`.
pub(crate) fn if_not_equal(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::NotEqual)
}

/// `IfLess, Var, Value`: the order of the legacy `if`.
pub(crate) fn if_less(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::Less)
}

/// `IfLessOrEqual, Var, Value`: the order that holds the equal.
pub(crate) fn if_less_or_equal(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::LessEqual)
}

/// `IfGreater, Var, Value`: the order of the legacy `if`.
pub(crate) fn if_greater(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::Greater)
}

/// `IfGreaterOrEqual, Var, Value`: the order that holds the equal.
pub(crate) fn if_greater_or_equal(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_comparison(rt, values, line, BinaryOp::GreaterEqual)
}

/// The comparison of the commands of the legacy `if`: the numbers when
/// both sides are numbers, and the texts otherwise, with the sense of the
/// case of the script.
fn the_condition_of_the_comparison(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    op: BinaryOp,
) -> Result<Value, RuntimeError> {
    let left = values
        .first()
        .cloned()
        .unwrap_or(Value::Text(String::new()));
    let right = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let left_number = match &left {
        Value::Int(number) => Some(Value::Int(*number)),
        Value::Float(number) => Some(Value::Float(*number)),
        Value::Text(text) => crate::v1::the_number_of_a_text(text),
        _ => None,
    };
    let right_number = crate::v1::the_number_of_a_text(&right);
    let answer = match op {
        BinaryOp::Equal | BinaryOp::NotEqual => {
            let method = rt.case_sense().the_method();
            let same = match (left_number, right_number) {
                (Some(one), Some(other)) => crate::runtime::the_same_number(&one, &other),
                _ => crate::runtime::the_same_text(&left.to_text(), &right, method),
            };
            if op == BinaryOp::Equal {
                same
            } else {
                !same
            }
        }
        _ => {
            let numbers = match (left_number, right_number) {
                (Some(one), Some(other)) => Some((
                    one.to_number().unwrap_or(0.0),
                    other.to_number().unwrap_or(0.0),
                )),
                _ => None,
            };
            rt.the_order_of_the_v1(numbers, &left.to_text(), &right, &op)
        }
    };
    Ok(Value::Int(answer as i64))
}

/// `IfWinExist, WinTitle, ...`: the window is there.
pub(crate) fn if_win_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_window(rt, values, line, false, false)
}

/// `IfWinNotExist, WinTitle, ...`: the window is not there.
pub(crate) fn if_win_not_exist(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_window(rt, values, line, false, true)
}

/// `IfWinActive, WinTitle, ...`: the window is there and has the focus.
pub(crate) fn if_win_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_window(rt, values, line, true, false)
}

/// `IfWinNotActive, WinTitle, ...`: the window is not the one with the focus.
pub(crate) fn if_win_not_active(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    the_condition_of_the_window(rt, values, line, true, true)
}

/// The condition of a window of the legacy `if`.
fn the_condition_of_the_window(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    active: bool,
    negated: bool,
) -> Result<Value, RuntimeError> {
    let title = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let mode = crate::settings::title_match_mode();
    let holds = if active {
        match rt
            .desktop()
            .window_active(&title, mode)
            .map_err(|reason| RuntimeError {
                message: reason,
                line,
            })? {
            crate::desktop::WindowAnswer::Active => true,
            crate::desktop::WindowAnswer::NotActive | crate::desktop::WindowAnswer::Absent => false,
            crate::desktop::WindowAnswer::Unknown(reason) => {
                return Err(RuntimeError {
                    message: reason,
                    line,
                });
            }
        }
    } else {
        let windows = rt
            .desktop()
            .matching_windows(&title, mode)
            .map_err(|reason| RuntimeError {
                message: reason,
                line,
            })?;
        if let Some(window) = windows.first() {
            rt.remember_the_last_window_of_the_v1(&window.id);
            true
        } else {
            false
        }
    };
    Ok(Value::Int((holds ^ negated) as i64))
}

/// The types of the `if x is Type` of the v1, and the check of each.
///
/// Measured on the binary of v1.1.37.02: the empty text is digit, xdigit,
/// alpha, upper, lower, alnum and space; the number trims the spaces and
/// takes the sign and the hex, but not the exponent; the timestamp is the
/// `YYYYMMDDHH24MISS` of the machine, from the year 1601 on, cut at
/// fourteen digits and read in pairs.
pub(crate) fn the_type_of_the_is_is_known(word: &str) -> bool {
    matches!(
        word.trim().to_ascii_lowercase().as_str(),
        "integer"
            | "float"
            | "number"
            | "digit"
            | "xdigit"
            | "alpha"
            | "upper"
            | "lower"
            | "alnum"
            | "space"
            | "time"
            | "date"
    )
}

/// Whether the text is of the type the `is` of the v1 names.
pub(crate) fn the_value_is_of_the_type(text: &str, word: &str) -> bool {
    match word.trim().to_ascii_lowercase().as_str() {
        "integer" => the_text_is_an_integer_of_the_is(text),
        "float" => the_text_is_a_float_of_the_is(text),
        "number" => {
            the_text_is_an_integer_of_the_is(text) || the_text_is_a_float_of_the_is(text)
        }
        "digit" => text.chars().all(|character| character.is_ascii_digit()),
        "xdigit" => {
            // Measured on the binary of v1.1.37.02: the `0x` prefix is a
            // part of the hex: the `0x10` is xdigit, and the `0x` alone is
            // too; the sign and the spaces are not.
            let rest = text
                .strip_prefix("0x")
                .or_else(|| text.strip_prefix("0X"))
                .unwrap_or(text);
            rest.chars().all(|character| character.is_ascii_hexdigit())
        }
        "alpha" => text.chars().all(|character| character.is_alphabetic()),
        "upper" => text.chars().all(|character| character.is_uppercase()),
        "lower" => text.chars().all(|character| character.is_lowercase()),
        "alnum" => text.chars().all(|character| character.is_alphanumeric()),
        "space" => text.chars().all(|character| character.is_whitespace()),
        "time" | "date" => the_text_is_a_timestamp_of_the_is(text),
        _ => false,
    }
}

/// The integer of the `is`: the spaces around are not a part of it, the
/// sign is, the hex is, and the exponent is not.
fn the_text_is_an_integer_of_the_is(text: &str) -> bool {
    let trimmed = text.trim();
    let unsigned = trimmed
        .strip_prefix('+')
        .or_else(|| trimmed.strip_prefix('-'))
        .unwrap_or(trimmed);
    if let Some(hex) = unsigned
        .strip_prefix("0x")
        .or_else(|| unsigned.strip_prefix("0X"))
    {
        return !hex.is_empty() && hex.chars().all(|character| character.is_ascii_hexdigit());
    }
    !unsigned.is_empty() && unsigned.chars().all(|character| character.is_ascii_digit())
}

/// The float of the `is`: one point, digits around it, and no exponent.
fn the_text_is_a_float_of_the_is(text: &str) -> bool {
    let trimmed = text.trim();
    let unsigned = trimmed
        .strip_prefix('+')
        .or_else(|| trimmed.strip_prefix('-'))
        .unwrap_or(trimmed);
    if !unsigned.contains('.') {
        return false;
    }
    let mut points = 0;
    let mut digits = 0;
    for character in unsigned.chars() {
        if character == '.' {
            points += 1;
            if points > 1 {
                return false;
            }
        } else if character.is_ascii_digit() {
            digits += 1;
        } else {
            return false;
        }
    }
    digits > 0
}

/// The timestamp of the `is`: the pairs of the digits, from the year on,
/// and the year is the one of the machine, 1601 or later.
fn the_text_is_a_timestamp_of_the_is(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() || !trimmed.chars().all(|character| character.is_ascii_digit()) {
        return false;
    }
    let length = trimmed.len().min(14);
    if length < 4 || length % 2 != 0 {
        return false;
    }
    let part = |from: usize, to: usize| -> u32 {
        trimmed[from..to].parse().unwrap_or(0)
    };
    let year = part(0, 4);
    if year < 1601 {
        return false;
    }
    if length >= 6 {
        let month = part(4, 6);
        if !(1..=12).contains(&month) {
            return false;
        }
        if length >= 8 {
            let day = part(6, 8);
            if day < 1 || day > the_days_of_the_month(year, month) {
                return false;
            }
            if length >= 10 && part(8, 10) > 23 {
                return false;
            }
            if length >= 12 && part(10, 12) > 59 {
                return false;
            }
            if length >= 14 && part(12, 14) > 59 {
                return false;
            }
        }
    }
    true
}

/// The days of the month, and the leap year of the Gregorian calendar.
fn the_days_of_the_month(year: u32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
                29
            } else {
                28
            }
        }
        _ => 0,
    }
}

/// The `else` of the v1 that has no `if`.
///
/// Measured on the binary of v1.1.37.02: the `else` without
/// an `if` is refused at the load with "ELSE with no matching IF".
pub(crate) fn else_of_the_v1(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Err(RuntimeError {
        message: "ELSE with no matching IF".into(),
        line,
    })
}

/// `Transform, out, SubCommand, Value1, Value2`: the math of the v1.
///
/// Measured on the binary of v1.1.37.02: the command takes
/// the name of the variable of the answer, the sub-command and the two
/// values, and the answer goes into the variable. The sub-command that it
/// does not know is refused with "Parameter #2 invalid.".
pub(crate) fn transform(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let sub = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let first = values
        .get(2)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let second = values
        .get(3)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let answer = the_answer_of_the_transform(rt, &sub, &first, &second, line)?;
    crate::v1::write_the_answer(rt, "Transform", values, 0, answer.clone(), line)?;
    Ok(answer)
}

/// The answer of one sub-command of the `Transform`.
///
/// Measured on the binary of v1.1.37.02: every sub-command
/// has its own answer, and some of them have their own failure.
fn the_answer_of_the_transform(
    rt: &mut Runtime<'_>,
    sub: &str,
    first: &str,
    second: &str,
    line: u32,
) -> Result<Value, RuntimeError> {
    // The number of a value of the command: a text that is not a number is
    // zero, and the v1 does not fail.
    let number = |text: &str| {
        crate::v1::the_number_of_a_text(text)
            .and_then(|value| value.to_number())
            .unwrap_or(0.0)
    };
    // The value of the v1 as a number: a whole one or a float.
    let value = |text: &str| crate::v1::the_number_of_a_text(text);
    // The numbers of the command are the numbers of the text without the
    // quotes that surround it.
    fn plain(text: &str) -> &str {
        the_text_without_the_quotes(text)
    }
    let invalid = |message: String| Err(RuntimeError { message, line });
    match sub.trim().to_lowercase().as_str() {
        // The code of the first letter of the text, and an empty text is an
        // empty answer. The text of this one is the text as it is: the
        // quotes are a part of it.
        "asc" => Ok(match first.chars().next() {
            Some(character) => Value::Int(character as i64),
            None => Value::Text(String::new()),
        }),
        // The letter of a code: the codes of the v1 are the ones of the
        // ANSI, and the code zero is an empty letter.
        "chr" => {
            let code = number(plain(first));
            if !(0.0..=255.0).contains(&code) {
                return invalid(format!(
                    "Parameter #3 invalid.\n     Specifically: {}",
                    plain(first)
                ));
            }
            let code = code as u32;
            Ok(match char::from_u32(code) {
                Some(character) if code != 0 => Value::Text(character.to_string()),
                _ => Value::Text(String::new()),
            })
        }
        // The remainder of a division, and the divisor of zero is a failure.
        "mod" => {
            let divisor = number(plain(second));
            if divisor == 0.0 {
                return invalid(format!(
                    "Divide by zero\n     Specifically: {}",
                    plain(second)
                ));
            }
            let left = number(plain(first));
            Ok(Value::Int((left % divisor) as i64))
        }
        "exp" => Ok(Value::Float(crate::runtime::exp(number(plain(first))))),
        // The square root, and the number of the root that is not one.
        "sqrt" => {
            let root = number(plain(first));
            if root < 0.0 {
                return invalid(format!(
                    "Parameter #3 must be a positive integer in this case.\n     Specifically: {}",
                    plain(first)
                ));
            }
            Ok(Value::Float(crate::runtime::sqrt(root)))
        }
        // The logarithm, and the number of it that is not one.
        "log" | "ln" => {
            let logarithm = number(plain(first));
            if logarithm < 0.0 {
                return invalid(format!(
                    "Parameter #3 must be a positive integer in this case.\n     Specifically: {}",
                    plain(first)
                ));
            }
            let answer = if sub.trim().eq_ignore_ascii_case("log") {
                crate::runtime::log10(logarithm)
            } else {
                crate::runtime::ln(logarithm)
            };
            Ok(Value::Float(answer))
        }
        // The number rounded to the digits of the second value: without
        // them the answer is a whole number.
        "round" => {
            let digits = number(plain(second));
            let rounded = number(plain(first));
            let factor = crate::runtime::powf(10.0, digits);
            let answer = crate::runtime::round(rounded * factor) / factor;
            if digits <= 0.0 {
                return Ok(Value::Int(answer as i64));
            }
            Ok(Value::Float(answer))
        }
        "ceil" => Ok(Value::Int(crate::runtime::ceil(number(plain(first))) as i64)),
        "floor" => Ok(Value::Int(
            crate::runtime::floor(number(plain(first))) as i64
        )),
        // The absolute value of the v1 is the text of the number without the
        // sign of the minus: "5.50" stays "5.50". A text that does not
        // begin with a number is the text as it is.
        "abs" => {
            let text = plain(first);
            if text.is_empty() {
                return invalid("Parameter #3 must be a number in this case.".to_string());
            }
            let text = text.trim_start();
            match text.strip_prefix('-') {
                Some(rest) => {
                    if value(rest).is_none() {
                        return Ok(Value::Text(String::new()));
                    }
                    Ok(Value::Text(rest.to_string()))
                }
                None => Ok(Value::Text(text.to_string())),
            }
        }
        "sin" => Ok(Value::Float(crate::runtime::sin(number(plain(first))))),
        "cos" => Ok(Value::Float(crate::runtime::cos(number(plain(first))))),
        "tan" => Ok(Value::Float(crate::runtime::tan(number(plain(first))))),
        // The arc of the trigonometry: a number that is out of the arc is
        // not a number, and the v1 answers nothing.
        "asin" | "acos" | "atan" => {
            let arc = number(plain(first));
            let answer = match sub.trim().to_lowercase().as_str() {
                "asin" => crate::runtime::asin(arc),
                "acos" => crate::runtime::acos(arc),
                _ => crate::runtime::atan(arc),
            };
            if answer.is_nan() {
                return Ok(Value::Text(String::new()));
            }
            Ok(Value::Float(answer))
        }
        // The power, and the base that is negative is a failure.
        "pow" => {
            let base = number(plain(first));
            if base < 0.0 {
                return invalid(format!(
                    "Parameter #3 must be a positive integer in this case.\n     Specifically: {}",
                    plain(first)
                ));
            }
            // The v1 answers with a whole number when the two are whole.
            if let (Some(Value::Int(left)), Some(Value::Int(right))) =
                (value(plain(first)), value(plain(second)))
            {
                if right >= 0 {
                    if let Some(answer) = left.checked_pow(right as u32) {
                        return Ok(Value::Int(answer));
                    }
                }
            }
            Ok(Value::Float(crate::runtime::powf(
                base,
                number(plain(second)),
            )))
        }
        // The bits of the v1: the `BitNot` is of thirty-two bits and the
        // rest is of sixty-four.
        "bitnot" => {
            let bits = number(plain(first)) as u32;
            Ok(Value::Int((!bits) as i64))
        }
        "bitand" => Ok(Value::Int(
            number(plain(first)) as i64 & number(plain(second)) as i64,
        )),
        "bitor" => Ok(Value::Int(
            number(plain(first)) as i64 | number(plain(second)) as i64,
        )),
        "bitxor" => Ok(Value::Int(
            number(plain(first)) as i64 ^ number(plain(second)) as i64,
        )),
        "bitshiftleft" => Ok(Value::Int(
            (number(plain(first)) as i64) << (number(plain(second)) as i64 & 63),
        )),
        "bitshiftright" => Ok(Value::Int(
            (number(plain(first)) as i64) >> (number(plain(second)) as i64 & 63),
        )),
        // The references that are inside the text are expanded.
        "deref" => {
            let text = rt
                .the_substitution_of_the_v1(first, line)
                .map_err(|failure| RuntimeError {
                    message: crate::runtime::the_message_of(&failure),
                    line,
                })?;
            Ok(Value::Text(text))
        }
        // The HTML of the v1 is a table of the names of the characters that
        // are not of the English, and the tree does not carry it.
        "html" => invalid(
            "this runtime does not carry the sub-command of the v1.\n     Specifically: HTML"
                .to_string(),
        ),
        // The sub-command that the v1 does not know, and the one of the
        // clipboard that a Unicode build does not have.
        _ => invalid(format!("Parameter #2 invalid.\n     Specifically: {sub}")),
    }
}

/// `IsSet(name)`: whether the variable of that name has a value.
///
/// Measured on the binary of v1.1.37.02: the answer is 1 for
/// a variable that has a value and 0 for one that has none, and a built-in
/// variable of the v1 has a value.
pub(crate) fn is_set(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let answer = if rt.has_a_value(&name) { 1 } else { 0 };
    Ok(Value::Int(answer))
}

/// `IsFunc(name)`: whether the name is a function.
///
/// Measured on the binary of v1.1.37.02: the answer is 1 for
/// a function of the script, 2 for a built-in and 0 for a name that is
/// neither.
///
/// The `IsFunc` of the v1 takes a value and not a name: `IsFunc("StrLen")`
/// asks about the function of that name, and `IsFunc(StrLen)` asks about the
/// value of the name -- which is a blank text, because the name of a
/// function is not a value -- and it is zero. A command of the v1 is not a
/// function: `IsFunc("MsgBox")` is zero.
///
/// A reference to a function is a function: `IsFunc(Func("StrLen"))` is 2
/// and `IsFunc(Func("f"))` is 1.
pub(crate) fn is_func(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first();
    if let Some(Value::Object(object)) = value {
        let object = object.borrow();
        if object.class == "func" {
            let builtin = matches!(object.value_of("isbuiltin"), Some(Value::Int(1)));
            return Ok(Value::Int(if builtin { 2 } else { 1 }));
        }
    }
    let name = value.map(|value| value.to_text()).unwrap_or_default();
    let answer = if rt.has_a_function(&name) {
        1
    } else if rt.has_a_builtin_function(&name) {
        2
    } else {
        0
    };
    Ok(Value::Int(answer))
}

/// `IsByRef(name)`: whether the variable of that name is a reference.
///
/// Measured on the binary of v1.1.37.02: the answer is 1 for
/// a variable that is a reference and 0 for one that is not.
pub(crate) fn is_by_ref(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let answer = if rt.is_a_reference(&name) { 1 } else { 0 };
    Ok(Value::Int(answer))
}

/// `Object()`: an object of the v1.
///
/// Measured on the binary of v1.1.37.02: the object of the
/// v1 has no class, and its `__Class` is empty, and a property that is
/// written on it is a property of it.
pub(crate) fn object(
    _rt: &mut Runtime<'_>,
    _values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    Ok(crate::classes::object(""))
}

/// `Func(name)`: the reference to the function of that name.
///
/// Measured on the binary of v1.1.37.02: the answer is a
/// value that carries the name of the function and the number of its
/// parameters, and the call of it is the call of the function. The name of a
/// built-in function is a function too, and the name of a command is not a
/// function at all -- `Func("MsgBox")` is zero, and so is the name of
/// nothing.
pub(crate) fn func(
    rt: &mut Runtime<'_>,
    values: &[Value],
    _line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let name = values
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    if let Some(value) = rt.the_function_of_the_script(&name) {
        return Ok(value);
    }
    if let Some(value) = rt.the_builtin_function(&name) {
        return Ok(value);
    }
    Ok(Value::Int(0))
}

/// `OnError(Callback)`: the handler of the errors of the script.
///
/// Measured on the binary of v1.1.37.02: the callback of the v1 is a
/// **name**, and the documentation says so -- `OnError("Handler")` takes
/// the name of a function in quotes, and the old label form is refused.
/// The v2 is the other way round: it takes the object of the function, and a
/// text is refused with "requires an Object, but received a String.".
///
/// The name resolves to the function of the script, and the reference to it
/// is kept the way the v2 keeps its own. A name that is not a function of the
/// script is not a failure of the load, either: the handler is registered and
/// it is the run that says so, as the v1 does.
pub(crate) fn on_error(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let value = values.first();
    // The v2 form is taken as it is, so that a script that hands over the
    // object of the function still works.
    if let Some(Value::Object(object)) = value {
        if object.borrow().class == "func" {
            let callback = rt.the_callback(value, "OnError", line)?;
            let order = the_order_of_the_handler(values.get(1), line)?;
            match order {
                1 => rt.set_error_callback(&callback.name, line),
                -1 => {
                    rt.set_error_callback(&callback.name, line);
                    rt.order_error_callback(&callback.name, true);
                }
                _ => rt.remove_error_callback(&callback.name),
            }
            return Ok(Value::Int(1));
        }
    }
    let name = value.map(|value| value.to_text()).unwrap_or_default();
    if name.is_empty() {
        return Err(RuntimeError {
            message: crate::runtime::invalid_parameter(1, "OnError"),
            line,
        });
    }
    // The name of the callback is the name of the function as the script
    // wrote it, and the order is the second parameter of the v2.
    let order = the_order_of_the_handler(values.get(1), line)?;
    match order {
        1 => rt.set_error_callback(&name, line),
        -1 => {
            rt.set_error_callback(&name, line);
            rt.order_error_callback(&name, true);
        }
        _ => rt.remove_error_callback(&name),
    }
    Ok(Value::Int(1))
}

/// The order of the handler of the v1: 1, -1 or 0.
///
/// The v1 has no order of its own, and the number is the one of the v2: the
/// parameter that is not there is 1, and a value that is not a number is
/// refused with the reason of the parameter.
fn the_order_of_the_handler(value: Option<&Value>, line: u32) -> Result<i32, RuntimeError> {
    let Some(value) = value else { return Ok(1) };
    if value.to_text().is_empty() {
        return Ok(1);
    }
    let number = value.to_number_strict().map_err(|_| RuntimeError {
        message: crate::runtime::wants_a_reference(2, "OnError", "a Number", value),
        line,
    })?;
    Ok(number as i32)
}

/// `FileReadLine, name, file, n`: the n-th line of a file.
///
/// Measured on the binary of v1.1.37.02: the command wants
/// three parameters, and the answer is the line itself, without the line
/// ending, and it is empty when the file has no such line.
///
/// Measured on the binary of AutoHotkey v1.1.37.02: the file
/// that is not there is not a failure of the script: the `ErrorLevel` is one,
/// the script goes on, and the variable of the caller is empty.
pub(crate) fn file_read_line(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let path = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let number = values
        .get(2)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let number: usize = number.trim().parse().unwrap_or(0);
    let lines = match rt.desktop().read_file(&path) {
        Ok(lines) => lines,
        Err(reason) => {
            rt.set_the_error_level(Value::Int(1));
            rt.note(format!("the file {path} was not read: {reason}"));
            let answer = Value::Text(String::new());
            crate::v1::write_the_answer(rt, "FileReadLine", values, 0, answer.clone(), line)?;
            return Ok(answer);
        }
    };
    rt.set_the_error_level(Value::Int(0));
    let answer = match number.checked_sub(1).and_then(|at| lines.get(at)) {
        Some(text) => Value::Text(text.clone()),
        None => Value::Text(String::new()),
    };
    crate::v1::write_the_answer(rt, "FileReadLine", values, 0, answer.clone(), line)?;
    Ok(answer)
}

/// `Input, name, options, title, default`: what the user writes.
///
/// Measured on the binary of v1.1.37.02: the command asks
/// the user with a dialogue, and the text of the user is the answer.
pub(crate) fn input(
    rt: &mut Runtime<'_>,
    values: &[Value],
    line: u32,
    _variant: u8,
) -> Result<Value, RuntimeError> {
    let options = values
        .get(1)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let title = values
        .get(2)
        .map(|value| value.to_text())
        .unwrap_or_default();
    let default = values
        .get(3)
        .map(|value| value.to_text())
        .unwrap_or_default();
    // The title of the v1 is the prompt of the dialogue, and the options
    // are the ones that the v2 reads.
    let options = crate::dialogs::the_options_of_the_input_box(&options, line)?;
    let answer = rt
        .desktop()
        .input_box(&title, &title, &options, &default)
        .map_err(|reason| RuntimeError {
            message: reason,
            line,
        })?;
    let answer = Value::Text(answer.value);
    crate::v1::write_the_answer(rt, "Input", values, 0, answer.clone(), line)?;
    Ok(answer)
}