ahk 0.3.2

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
//! The `File` class.
//!
//! A file is an open file on the disk. The box can serve this one: it
//! is the class that touches the machine.
//!
//! The class does no I/O of its own: it asks the desktop for the bytes
//! and it keeps the handle, the position and the encoding of the file
//! in the property table of the object, under one key.
//!
//! The text of a file is the code page of the machine, or UTF-8, or
//! UTF-16: the three encodings the runtime carries. An encoding it does
//! not carry is a failure with the reason, and not a text that is
//! written in the wrong bytes.

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::rc::Rc;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;

use crate::classes::buffer;
use crate::classes::enumerator;
use crate::classes::object_with;
use crate::runtime::{
    Object, Runtime, RuntimeError, RuntimeFailure, TypeName, Value, expected_number, expected_type,
    put,
};

/// The key the state of a file lives under.
///
/// The key has a space in it, so that a script cannot reach the inside
/// of a file by name.
const STATE: &str = "file state";

/// The class of the object that carries the state of a file.
const STATE_CLASS: &str = "file-state";

/// The properties of a file.
const PROPERTIES: [&str; 5] = ["pos", "length", "ateof", "encoding", "handle"];

/// The methods of a file.
///
/// The binary of v2.0.19 has no other: a file is not made again, and it
/// has no unsigned number of sixty-four bits.
const METHODS: [&str; 35] = [
    "read",
    "readline",
    "readchar",
    "readuchar",
    "readshort",
    "readushort",
    "readint",
    "readuint",
    "readint64",
    "readfloat",
    "readdouble",
    "write",
    "writeline",
    "writechar",
    "writeuchar",
    "writeshort",
    "writeushort",
    "writeint",
    "writeuint",
    "writeint64",
    "writefloat",
    "writedouble",
    "rawread",
    "rawwrite",
    "seek",
    "close",
    "ownprops",
    "hasownprop",
    "defineprop",
    "deleteprop",
    "getownpropdesc",
    "hasprop",
    "hasmethod",
    "getmethod",
    "hasbase",
];

/// The handle of a file that is closed.
const CLOSED: i64 = -1;

/// The handle of the console of the machine.
///
/// The star is the name of the standard output and of the standard
/// input, and v2 opens them as files.
const CONSOLE: i64 = -2;

/// How many bytes are read at a time when a line is looked for.
const CHUNK: i64 = 4096;

/// The state of a file: the handle, the position, the encoding and the
/// mode it was opened with.
struct File {
    handle: i64,
    pos: i64,
    encoding: Encoding,
    mode: String,
}

impl File {
    /// Whether the file may be read.
    ///
    /// The mode says it: a file that is opened to be written is not one
    /// that may be read.
    fn can_read(&self) -> bool {
        self.mode.contains('r')
    }

    /// Whether the file may be written.
    ///
    /// The mode says it: a file that is opened to be read is not one that
    /// may be written.
    fn can_write(&self) -> bool {
        self.mode.contains('w') || self.mode.contains('a')
    }
}

/// The encodings the runtime carries.
///
/// The code page of the machine is one of them: it is the encoding of
/// the files when the script does not say which one it wants, and it is
/// the code page of the machine where the dialect was measured.
///
/// The raw files have no byte order mark: the suffix of their name says
/// so.
#[derive(Clone, Copy)]
pub(crate) enum Encoding {
    /// The code page of the machine.
    Cp1252,
    /// The text of v2, in UTF-8.
    Utf8 { raw: bool },
    /// The text of v2, in UTF-16.
    Utf16 { raw: bool },
}

/// The object a `File` makes.
/// The names a file answers: its properties and its methods.
pub(crate) fn names() -> Vec<&'static str> {
    PROPERTIES.iter().chain(METHODS.iter()).copied().collect()
}

/// Open a file, and answer the object of it.
///
/// The class of v2 is not made: `File(...)` answers "Invalid base.". The
/// file is made by the `FileOpen` built-in, and this is what it asks.
pub(crate) fn open_file(
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let file = open(arguments, rt, line)?;
    Ok(object_with("file", vec![(STATE, stored(&file))]))
}

/// A method of a `File`.
///
/// `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(
    method: &str,
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    let method = method.to_lowercase();
    // The member that the KeySharp extension adds: none of its names is a
    // method of the v2.
    if rt
        .dialect()
        .carries_the_member_of_the_extension("file", &method)
    {
        if method == "flush" {
            // The writes of a file of this runtime reach the disk as the
            // statements write them, so there is nothing to flush: the
            // answer is the empty text, the way the writes answer.
            return Some(Ok(Value::Text(String::new())));
        }
        return None;
    }
    match method.as_str() {
        "read" => Some(read_text(this, arguments, rt, line)),
        "readline" => Some(read_line(this, rt, line)),
        "readchar" => Some(read_number(rt, this, 1, line, |bytes| {
            Value::Int(bytes[0] as i8 as i64)
        })),
        "readuchar" => Some(read_number(rt, this, 1, line, |bytes| {
            Value::Int(bytes[0] as i64)
        })),
        "readshort" => Some(read_number(rt, this, 2, line, |bytes| {
            Value::Int(little(bytes) as u16 as i16 as i64)
        })),
        "readushort" => Some(read_number(rt, this, 2, line, |bytes| {
            Value::Int(little(bytes) as u16 as i64)
        })),
        "readint" => Some(read_number(rt, this, 4, line, |bytes| {
            Value::Int(little(bytes) as u32 as i32 as i64)
        })),
        "readuint" => Some(read_number(rt, this, 4, line, |bytes| {
            Value::Int(little(bytes) as u32 as i64)
        })),
        "readint64" => Some(read_number(rt, this, 8, line, |bytes| {
            Value::Int(little(bytes) as i64)
        })),
        "readfloat" => Some(read_number(rt, this, 4, line, |bytes| {
            Value::Float(f32::from_bits(little(bytes) as u32) as f64)
        })),
        "readdouble" => Some(read_number(rt, this, 8, line, |bytes| {
            Value::Float(f64::from_bits(little(bytes)))
        })),
        "write" => Some(write_text(this, arguments, rt, line)),
        "writeline" => Some(write_line(this, arguments, rt, line)),
        "writechar" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFF, 1)
        })),
        "writeuchar" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFF, 1)
        })),
        "writeshort" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFFFF, 2)
        })),
        "writeushort" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFFFF, 2)
        })),
        "writeint" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFFFF_FFFF, 4)
        })),
        "writeuint" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64 & 0xFFFF_FFFF, 4)
        })),
        "writeint64" => Some(write_number(rt, this, arguments, line, |value| {
            little_bytes(value as i64 as u64, 8)
        })),
        "writefloat" => Some(write_number(rt, this, arguments, line, |value| {
            float_bytes(value, true)
        })),
        "writedouble" => Some(write_number(rt, this, arguments, line, |value| {
            float_bytes(value, false)
        })),
        "rawread" => Some(raw_read(this, arguments, rt, line)),
        "rawwrite" => Some(raw_write(this, arguments, rt, line)),
        "seek" => Some(seek(this, arguments, rt, line)),
        "close" => Some(close(this, rt, line)),
        // The methods of the base object are answered here too: the
        // runtime knows nothing of the class types of the runtime.
        _ => base_method(&method, this, arguments, rt, line),
    }
}

/// A property of a `File`.
///
/// `None` means the name is not a property of this class: the runtime
/// then looks in the property table of the object.
pub(crate) fn property(
    name: &str,
    this: &Value,
    rt: &mut Runtime,
    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    match name.to_lowercase().as_str() {
        "pos" => Some(state(this, line).map(|file| {
            // v2 answers minus one when the file is closed.
            Value::Int(if is_closed(&file) { -1 } else { file.pos })
        })),
        "length" => Some(length(rt, this, line)),
        "ateof" => Some(at_eof(rt, this, line)),
        "encoding" => {
            Some(state(this, line).map(|file| Value::Text(file.encoding.name().to_string())))
        }
        "handle" => Some(state(this, line).map(|file| Value::Int(file.handle))),
        _ => None,
    }
}

/// A property of a `File` 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(
    name: &str,
    this: &Value,
    value: Value,
    rt: &mut Runtime,
    line: u32,
) -> Option<Result<(), RuntimeFailure>> {
    match name.to_lowercase().as_str() {
        "pos" => Some(set_pos(this, value, line)),
        "length" => Some(set_length(rt, this, value, line)),
        "encoding" => Some(set_encoding(this, value, line)),
        _ => None,
    }
}

/// The item of a `File`: the `__Item` of the class.
///
/// `None` means the class has no `__Item` of its own.
pub(crate) fn item(
    _key: &Value,
    _this: &Value,
    _rt: &mut Runtime,
    _line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    None
}

// -- the state ------------------------------------------------------------------

/// The failure of a file, with the line the script was on.
///
/// The reason of the machine carries the code of the system at its end,
/// and v2 puts it in front.
fn fail(message: impl Into<String>, line: u32) -> RuntimeFailure {
    let message = message.into();
    RuntimeFailure::Error(RuntimeError {
        message: the_reason_of_the_machine(&message),
        line,
    })
}

/// The reason of the machine, the way v2 writes it.
///
/// v2 puts the code of the system in front of what it says: "(2) The
/// system cannot find the file specified."
fn the_reason_of_the_machine(reason: &str) -> String {
    let Some(without_the_bracket) = reason.strip_suffix(')') else {
        return reason.to_string();
    };
    let Some((message, number)) = without_the_bracket.rsplit_once(" (os error ") else {
        return reason.to_string();
    };
    match number.parse::<i64>() {
        Ok(number) => format!("({number}) {message}"),
        Err(_) => reason.to_string(),
    }
}

/// The whole number an argument holds.
///
/// A float is truncated, the way AutoHotkey truncates it.
fn whole(value: &Value, line: u32) -> Result<i64, RuntimeFailure> {
    match value {
        Value::Int(number) => Ok(*number),
        Value::Float(number) => Ok(*number as i64),
        other => Err(fail(
            expected_type(TypeName::Integer, other.type_name()),
            line,
        )),
    }
}

/// The number an argument holds.
fn number(value: &Value, line: u32) -> Result<f64, RuntimeFailure> {
    value
        .to_number_strict()
        .map_err(|_| fail(expected_number(value), line))
}

/// The state of a file, as the object holds it.
fn state(this: &Value, line: u32) -> Result<File, RuntimeFailure> {
    let Value::Object(object) = this else {
        return Err(fail("this value is not a file.", line));
    };
    let inner = match object.borrow().value_of(STATE) {
        Some(Value::Object(inner)) => inner.clone(),
        _ => return Err(fail("this value is not a file.", line)),
    };
    let inner = inner.borrow();
    let handle = inner
        .value_of("handle")
        .and_then(|value| value.to_number())
        .unwrap_or(CLOSED as f64) as i64;
    let pos = inner
        .value_of("pos")
        .and_then(|value| value.to_number())
        .unwrap_or(0.0) as i64;
    let mode = inner
        .value_of("mode")
        .map(|value| value.to_text())
        .unwrap_or_else(|| "rw".to_string());
    let encoding = match inner.value_of("encoding") {
        Some(value) => Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?,
        None => Encoding::of(crate::files::encoding()).map_err(|reason| fail(reason, line))?,
    };
    Ok(File {
        handle,
        pos,
        encoding,
        mode,
    })
}

/// The state of a file, as the property table holds it.
fn stored(file: &File) -> Value {
    object_with(
        STATE_CLASS,
        vec![
            ("handle", Value::Int(file.handle)),
            ("pos", Value::Int(file.pos)),
            ("encoding", Value::Text(file.encoding.name().to_string())),
            ("mode", Value::Text(file.mode.clone())),
        ],
    )
}

/// Put the state back into the object.
fn restore(this: &Value, file: &File) {
    let Value::Object(object) = this else { return };
    put(&mut object.borrow_mut().properties, STATE, stored(file));
}

/// Whether the file is closed.
///
/// A file that is closed has no handle, and v2 answers the operations on
/// it with a value and not with a failure.
fn is_closed(file: &File) -> bool {
    file.handle == CLOSED
}

/// Whether the file is the console of the machine.
fn is_console(file: &File) -> bool {
    file.handle == CONSOLE
}

/// The text of the console of the machine.
///
/// The tree has no console of its own: the output of the script is the
/// output of the report.
fn write_to_the_console(rt: &mut Runtime, bytes: &[u8], encoding: Encoding) {
    let text = match decode(bytes, encoding) {
        Ok((text, _)) => text,
        Err(_) => String::new(),
    };
    rt.push_output(text);
}

/// The bytes of the file at a place in it.
fn read_at(
    rt: &mut Runtime,
    handle: i64,
    pos: i64,
    count: i64,
    line: u32,
) -> Result<Vec<u8>, RuntimeFailure> {
    rt.desktop()
        .read_file_at(handle, pos, count)
        .map_err(|reason| fail(reason, line))
}

/// Open a file and answer the state of it.
fn open(arguments: &[Value], rt: &mut Runtime, line: u32) -> Result<File, RuntimeFailure> {
    let path = match arguments.first() {
        Some(value) => value.to_text(),
        None => return Err(fail("the file needs a path.", line)),
    };
    let mode = match arguments.get(1) {
        Some(value) => value.to_text(),
        None => "r".to_string(),
    };
    // The modes of v2 are "r", "w", "a" and "rw", and the case of the
    // letters is not the case of the words.
    let kind = mode.to_lowercase();
    if !matches!(kind.as_str(), "r" | "w" | "a" | "rw") {
        return Err(fail("Invalid parameter(s).", line));
    }
    // The file is opened with the encoding of the script when the
    // script does not say which one it wants.
    let encoding = match arguments.get(2) {
        Some(value) => Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?,
        None => Encoding::of(crate::files::encoding()).map_err(|reason| fail(reason, line))?,
    };
    // The star is the console of the machine: the standard output and
    // the standard input, and v2 opens them as files.
    if path == "*" {
        return Ok(File {
            handle: CONSOLE,
            pos: 0,
            encoding,
            mode,
        });
    }
    let handle = rt
        .desktop()
        .open_file(&path, &mode)
        .map_err(|reason| fail(reason, line))?;
    // A file that is opened to be appended to starts at its end.
    let pos = if mode.contains('a') {
        rt.desktop()
            .file_size(handle)
            .map_err(|reason| fail(reason, line))?
    } else {
        0
    };
    let mut file = File {
        handle,
        pos,
        encoding,
        mode,
    };
    // The bytes of the file decide the encoding of it: a file that
    // begins with a byte order mark is read with the encoding of that
    // mark, whatever the script asked for. The desktop that cannot read
    // the head of the file keeps the encoding of the script.
    if kind.contains('r') || kind == "a" {
        if let Ok(bytes) = read_at(rt, handle, 0, 3, line) {
            if let Some((encoding, at)) = Encoding::detect(&bytes) {
                file.encoding = encoding;
                if file.pos == 0 {
                    file.pos = at as i64;
                }
            }
        }
    }
    // The mark of the encoding is written when the file is written from
    // its start. The raw files have none.
    if (kind == "w" || kind == "a") && file.pos == 0 {
        if let Some(mark) = file.encoding.mark() {
            write_bytes(rt, &mut file, &mark, line)?;
        }
    }
    Ok(file)
}

/// `Read`: the text of the file at its position.
fn read_text(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    let count = match arguments.first() {
        Some(value) => Some(whole(value, line)?),
        None => None,
    };
    let text = read_chars(rt, &mut file, count, line)?;
    restore(this, &file);
    Ok(Value::Text(text))
}

/// The text of the file at its position, and the position moves on.
fn read_chars(
    rt: &mut Runtime,
    file: &mut File,
    count: Option<i64>,
    line: u32,
) -> Result<String, RuntimeFailure> {
    // v2 answers an empty text when the file is closed, and when it
    // was opened to be written. The console has no more to give: the
    // standard input of the tree is the script itself.
    if is_closed(file) || is_console(file) || !file.can_read() {
        return Ok(String::new());
    }
    let handle = file.handle;
    let (text, used) = match count {
        Some(count) => {
            if count < 0 {
                return Err(fail("the count of characters cannot be negative.", line));
            }
            // A character is at most four bytes, and a UTF-16 one is
            // two: the read is wide enough for what was asked for.
            let wide = match file.encoding {
                // A character of the code page is one byte.
                Encoding::Cp1252 => count,
                Encoding::Utf8 { .. } => count * 4,
                Encoding::Utf16 { .. } => count * 2,
            };
            let bytes = read_at(rt, handle, file.pos, wide, line)?;
            let (text, used) =
                decode(&bytes, file.encoding).map_err(|reason| fail(reason, line))?;
            match file.encoding {
                // The characters of a UTF-8 text are counted by the
                // bytes they take, so the cut is where the text says.
                Encoding::Utf8 { .. } => {
                    let (text, used) = take(&text, count as usize);
                    (text, used)
                }
                // A character of the code page is one byte, and the cut
                // is where the text says too.
                Encoding::Cp1252 => {
                    let (text, used) = take(&text, count as usize);
                    (text, used)
                }
                // A UTF-16 character is two bytes, and the read was
                // wide enough for the units that were asked for.
                Encoding::Utf16 { .. } => (text, used),
            }
        }
        None => {
            let size = rt
                .desktop()
                .file_size(handle)
                .map_err(|reason| fail(reason, line))?;
            let bytes = read_at(rt, handle, file.pos, (size - file.pos).max(0), line)?;
            decode(&bytes, file.encoding).map_err(|reason| fail(reason, line))?
        }
    };
    file.pos += used as i64;
    Ok(text)
}

/// `ReadLine`: the line of the file at its position.
fn read_line(this: &Value, rt: &mut Runtime, line: u32) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    // v2 answers an empty text when the file is closed, and when it
    // was opened to be written. The console has no more to give: the
    // standard input of the tree is the script itself.
    if is_closed(&file) || is_console(&file) || !file.can_read() {
        return Ok(Value::Text(String::new()));
    }
    let handle = file.handle;
    let mut raw: Vec<u8> = Vec::new();
    let text = loop {
        let bytes = read_at(rt, handle, file.pos + raw.len() as i64, CHUNK, line)?;
        let at_end = bytes.is_empty();
        raw.extend_from_slice(&bytes);
        match line_of(&raw, file.encoding) {
            Some((end, after)) => {
                let (text, _) =
                    decode(&raw[..end], file.encoding).map_err(|reason| fail(reason, line))?;
                file.pos += after as i64;
                break text;
            }
            // The last line of a file has no newline after it.
            None if at_end => {
                let (text, used) =
                    decode(&raw, file.encoding).map_err(|reason| fail(reason, line))?;
                file.pos += used as i64;
                break text;
            }
            None => {}
        }
    };
    restore(this, &file);
    Ok(Value::Text(text))
}

/// The bytes of a number of the file at its position.
fn read_number(
    rt: &mut Runtime,
    this: &Value,
    count: usize,
    line: u32,
    of: fn(&[u8]) -> Value,
) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    // v2 answers an empty text when the file is closed, and when it
    // was opened to be written. The console has no more to give: the
    // standard input of the tree is the script itself.
    if is_closed(&file) || is_console(&file) || !file.can_read() {
        return Ok(Value::Text(String::new()));
    }
    let handle = file.handle;
    let bytes = read_at(rt, handle, file.pos, count as i64, line)?;
    if bytes.is_empty() {
        return Err(fail("the read is past the end of the file.", line));
    }
    // A number that is cut in half at the end of the file is zero on
    // the bytes that are missing, the way v2 reads one.
    let mut full = bytes.clone();
    full.resize(count, 0);
    file.pos += bytes.len() as i64;
    restore(this, &file);
    Ok(of(&full))
}

/// `Write`: the text of the script into the file.
fn write_text(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let text = match arguments.first() {
        Some(value) => value.to_text(),
        None => return Err(fail("Too few parameters passed to function.", line)),
    };
    let mut file = state(this, line)?;
    // v2 answers the number of characters it wrote, and a file that is
    // closed takes them all and keeps none.
    let written = text.chars().count() as i64;
    if !is_closed(&file) && file.can_write() {
        if is_console(&file) {
            rt.push_output(text);
            file.pos += written;
        } else {
            let bytes = encode(&text, file.encoding);
            write_bytes(rt, &mut file, &bytes, line)?;
        }
        restore(this, &file);
    }
    Ok(Value::Int(written))
}

/// `WriteLine`: the text of the script, and a newline, into the file.
fn write_line(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let text = match arguments.first() {
        Some(value) => value.to_text(),
        None => String::new(),
    };
    let mut file = state(this, line)?;
    // The newline is a character of the file too.
    let written = text.chars().count() as i64 + 1;
    if !is_closed(&file) && file.can_write() {
        if is_console(&file) {
            let mut line_of_text = text;
            line_of_text.push('\n');
            rt.push_output(line_of_text);
            file.pos += written;
        } else {
            let mut bytes = encode(&text, file.encoding);
            bytes.extend_from_slice(&encode("\n", file.encoding));
            write_bytes(rt, &mut file, &bytes, line)?;
        }
        restore(this, &file);
    }
    Ok(Value::Int(written))
}

/// The bytes of a number, written into the file at its position.
fn write_number(
    rt: &mut Runtime,
    this: &Value,
    arguments: &[Value],
    line: u32,
    of: fn(f64) -> Vec<u8>,
) -> Result<Value, RuntimeFailure> {
    let value = match arguments.first() {
        Some(value) => number(value, line)?,
        None => return Err(fail("Too few parameters passed to function.", line)),
    };
    let mut file = state(this, line)?;
    let bytes = of(value);
    let written = bytes.len() as i64;
    if !is_closed(&file) && file.can_write() {
        if is_console(&file) {
            write_to_the_console(rt, &bytes, file.encoding);
            file.pos += written;
        } else {
            write_bytes(rt, &mut file, &bytes, line)?;
        }
        restore(this, &file);
    }
    Ok(Value::Int(written))
}

/// The bytes of the file at its position, written over what is there.
fn write_bytes(
    rt: &mut Runtime,
    file: &mut File,
    bytes: &[u8],
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let handle = file.handle;
    let written = rt
        .desktop()
        .write_file_at(handle, file.pos, bytes)
        .map_err(|reason| fail(reason, line))?;
    file.pos += written as i64;
    Ok(Value::Int(written as i64))
}

/// `RawRead`: the bytes of the file, into a buffer.
fn raw_read(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    // v2 answers zero when the file is closed, and when it was opened
    // to be written.
    if is_closed(&file) || !file.can_read() {
        return Ok(Value::Int(0));
    }
    let handle = file.handle;
    let target = match arguments.first() {
        Some(value) => value.clone(),
        None => return Err(fail("Too few parameters passed to function.", line)),
    };
    // The bytes are read into a buffer, and the buffer takes them all.
    let count = match arguments.get(1) {
        Some(value) => whole(value, line)?,
        None => buffer::size_of(&target, line)?,
    };
    if count < 0 {
        return Err(fail("the count of bytes cannot be negative.", line));
    }
    let bytes = read_at(rt, handle, file.pos, count, line)?;
    let written = buffer::fill(&target, &bytes, line)?;
    file.pos += bytes.len() as i64;
    restore(this, &file);
    Ok(Value::Int(written as i64))
}

/// `RawWrite`: the bytes of a buffer or of a string, into the file.
fn raw_write(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    let bytes = match arguments.first() {
        // A buffer is written as it is, and a string is written as it
        // is: the bytes of the UTF-16, the way v2 writes it.
        Some(Value::Object(_)) => buffer::raw_bytes(&arguments[0], line)?,
        Some(Value::Text(text)) => encode(text, Encoding::Utf16 { raw: false }),
        Some(other) => {
            return Err(fail(
                expected_type(TypeName::Object, other.type_name()),
                line,
            ));
        }
        None => return Err(fail("Too few parameters passed to function.", line)),
    };
    let count = match arguments.get(1) {
        Some(value) => whole(value, line)?,
        None => bytes.len() as i64,
    };
    if count < 0 || count as usize > bytes.len() {
        return Err(fail("there are not that many bytes to write.", line));
    }
    let written = count;
    if !is_closed(&file) && file.can_write() {
        if is_console(&file) {
            write_to_the_console(rt, &bytes[..count as usize], file.encoding);
            file.pos += written;
        } else {
            write_bytes(rt, &mut file, &bytes[..count as usize], line)?;
        }
        restore(this, &file);
    }
    Ok(Value::Int(written))
}

/// `Seek`: the position of the file, somewhere else.
fn seek(
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Result<Value, RuntimeFailure> {
    let distance = match arguments.first() {
        Some(value) => whole(value, line)?,
        None => return Err(fail("Too few parameters passed to function.", line)),
    };
    let mut file = state(this, line)?;
    // v2 answers zero when the file is closed, and when the file is
    // the console of the machine.
    if is_closed(&file) || is_console(&file) {
        return Ok(Value::Int(0));
    }
    let handle = file.handle;
    // A distance that is negative moves from the end of the file, the
    // way v2 moves it.
    let origin = match arguments.get(1) {
        Some(value) => whole(value, line)?,
        None => {
            if distance < 0 {
                2
            } else {
                0
            }
        }
    };
    let target = match origin {
        0 => distance,
        1 => file.pos + distance,
        2 => {
            let size = rt
                .desktop()
                .file_size(handle)
                .map_err(|reason| fail(reason, line))?;
            size + distance
        }
        _ => return Ok(Value::Int(0)),
    };
    if target < 0 {
        return Ok(Value::Int(0));
    }
    file.pos = target;
    restore(this, &file);
    Ok(Value::Int(1))
}

/// `Close`: the file is closed and the handle is gone.
fn close(this: &Value, rt: &mut Runtime, line: u32) -> Result<Value, RuntimeFailure> {
    let mut file = state(this, line)?;
    if file.handle == CONSOLE {
        return Ok(Value::Text(String::new()));
    }
    if file.handle >= 0 {
        rt.desktop()
            .close_file(file.handle)
            .map_err(|reason| fail(reason, line))?;
        file.handle = CLOSED;
        restore(this, &file);
    }
    Ok(Value::Text(String::new()))
}

/// How long the file is.
fn length(rt: &mut Runtime, this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
    let file = state(this, line)?;
    // v2 answers zero when the file is closed. The console is as long
    // as what was written to it.
    if is_closed(&file) {
        return Ok(Value::Int(0));
    }
    if is_console(&file) {
        return Ok(Value::Int(file.pos));
    }
    let handle = file.handle;
    let size = rt
        .desktop()
        .file_size(handle)
        .map_err(|reason| fail(reason, line))?;
    Ok(Value::Int(size))
}

/// Whether the file is at its end.
fn at_eof(rt: &mut Runtime, this: &Value, line: u32) -> Result<Value, RuntimeFailure> {
    let file = state(this, line)?;
    // v2 answers one when the file is closed: there is nothing more to
    // read. The console is at its end too.
    if is_closed(&file) || is_console(&file) {
        return Ok(Value::Int(1));
    }
    let handle = file.handle;
    let size = rt
        .desktop()
        .file_size(handle)
        .map_err(|reason| fail(reason, line))?;
    Ok(Value::Int(if file.pos >= size { 1 } else { 0 }))
}

/// Put the position of the file somewhere else.
fn set_pos(this: &Value, value: Value, line: u32) -> Result<(), RuntimeFailure> {
    let pos = whole(&value, line)?;
    if pos < 0 {
        return Err(fail("the position of a file cannot be negative.", line));
    }
    let mut file = state(this, line)?;
    // v2 keeps the position of a file that is closed.
    if is_closed(&file) {
        return Ok(());
    }
    file.pos = pos;
    restore(this, &file);
    Ok(())
}

/// Make the file of another length.
///
/// The desktop can make a file longer, by writing at its end, but it
/// cannot cut one: a file that is made shorter fails with the reason.
fn set_length(
    rt: &mut Runtime,
    this: &Value,
    value: Value,
    line: u32,
) -> Result<(), RuntimeFailure> {
    let size = whole(&value, line)?;
    if size < 0 {
        return Err(fail("the length of a file cannot be negative.", line));
    }
    let file = state(this, line)?;
    // v2 keeps the length of a file that is closed.
    if is_closed(&file) {
        return Ok(());
    }
    let handle = file.handle;
    let current = rt
        .desktop()
        .file_size(handle)
        .map_err(|reason| fail(reason, line))?;
    if size < current {
        return Err(fail(
            "this desktop cannot make a file shorter: it cannot cut one.",
            line,
        ));
    }
    if size > current {
        let zeros = vec![0u8; (size - current) as usize];
        rt.desktop()
            .write_file_at(handle, current, &zeros)
            .map_err(|reason| fail(reason, line))?;
    }
    Ok(())
}

/// Put the encoding of the file somewhere else.
fn set_encoding(this: &Value, value: Value, line: u32) -> Result<(), RuntimeFailure> {
    let encoding = Encoding::of(&value.to_text()).map_err(|reason| fail(reason, line))?;
    let mut file = state(this, line)?;
    file.encoding = encoding;
    restore(this, &file);
    Ok(())
}

// -- the encoding ---------------------------------------------------------------

impl Encoding {
    /// The encoding of a name, as v2 spells it.
    ///
    /// The suffix of the raw files says that the file has no byte order
    /// mark: v2 keeps the suffix in the name of the encoding of the
    /// script, and the file of a raw script has no mark.
    pub(crate) fn of(name: &str) -> Result<Encoding, String> {
        let name = name.trim().to_uppercase();
        let (name, raw) = match name.strip_suffix("-RAW") {
            Some(short) => (short, true),
            None => (name.as_str(), false),
        };
        match name {
            "UTF-8" | "UTF8" => Ok(Encoding::Utf8 { raw }),
            "UTF-16" | "UTF16" => Ok(Encoding::Utf16 { raw }),
            // The code page of the machine is the one of the machine
            // where the dialect was measured.
            "CP0" | "CP1252" => Ok(Encoding::Cp1252),
            other => Err(format!(
                "the encoding {other:?} is not one this runtime carries: it knows the code page of the machine (CP1252), UTF-8 and UTF-16."
            )),
        }
    }

    /// The name of the encoding, as v2 spells it.
    ///
    /// The suffix of the raw files is not in the name: v2 answers the
    /// encoding of a file of raw text with the name of the encoding.
    fn name(self) -> &'static str {
        match self {
            Encoding::Cp1252 => "CP1252",
            Encoding::Utf8 { .. } => "UTF-8",
            Encoding::Utf16 { .. } => "UTF-16",
        }
    }

    /// The bytes of the byte order mark of the encoding, if it has one.
    ///
    /// Measured on the binary of v2.0.19 on 2026-10-29: a file of UTF-8
    /// begins with the mark of three bytes, and a file of UTF-16 with the
    /// mark of two, and the code page has none.
    pub(crate) fn mark(self) -> Option<Vec<u8>> {
        match self {
            Encoding::Cp1252 => None,
            Encoding::Utf8 { raw } => {
                if raw {
                    None
                } else {
                    Some(vec![0xEF, 0xBB, 0xBF])
                }
            }
            Encoding::Utf16 { raw } => {
                if raw {
                    None
                } else {
                    Some(vec![0xFF, 0xFE])
                }
            }
        }
    }

    /// The encoding of the bytes of a file that begin with a mark.
    ///
    /// Measured on the binary of v2.0.19 on 2026-10-30: the bytes of a
    /// file decide the encoding of it, whatever the script asked for: a
    /// file that begins with the mark of UTF-8 is read with UTF-8, and
    /// the position of the file goes over the mark.
    pub(crate) fn detect(bytes: &[u8]) -> Option<(Encoding, usize)> {
        if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
            return Some((Encoding::Utf8 { raw: false }, 3));
        }
        if bytes.starts_with(&[0xFF, 0xFE]) {
            return Some((Encoding::Utf16 { raw: false }, 2));
        }
        None
    }
}

/// The characters of the code page of the machine that are not Latin-1.
///
/// The code page is CP1252, and the range 0x80-0x9F is the one that is
/// not Latin-1: the euro, the quotes of Windows and the letters with a
/// cedilla and a caron.
const CP1252: [(u8, char); 27] = [
    (0x80, '\u{20AC}'),
    (0x82, '\u{201A}'),
    (0x83, '\u{0192}'),
    (0x84, '\u{201E}'),
    (0x85, '\u{2026}'),
    (0x86, '\u{2020}'),
    (0x87, '\u{2021}'),
    (0x88, '\u{02C6}'),
    (0x89, '\u{2030}'),
    (0x8A, '\u{0160}'),
    (0x8B, '\u{2039}'),
    (0x8C, '\u{0152}'),
    (0x8E, '\u{017D}'),
    (0x91, '\u{2018}'),
    (0x92, '\u{2019}'),
    (0x93, '\u{201C}'),
    (0x94, '\u{201D}'),
    (0x95, '\u{2022}'),
    (0x96, '\u{2013}'),
    (0x97, '\u{2014}'),
    (0x98, '\u{02DC}'),
    (0x99, '\u{2122}'),
    (0x9A, '\u{0161}'),
    (0x9B, '\u{203A}'),
    (0x9C, '\u{0153}'),
    (0x9E, '\u{017E}'),
    (0x9F, '\u{0178}'),
];

/// The bytes of the text, in the code page of the machine.
///
/// A character that the code page does not have is a question mark: the
/// machine has no way to write it.
fn encode_cp1252(text: &str) -> Vec<u8> {
    let mut bytes = Vec::new();
    for character in text.chars() {
        match the_byte_of_cp1252(character) {
            Some(byte) => bytes.push(byte),
            None => bytes.push(b'?'),
        }
    }
    bytes
}

/// The byte of a character in the code page of the machine.
fn the_byte_of_cp1252(character: char) -> Option<u8> {
    let code = character as u32;
    if code < 0x80 || (0xA0..=0xFF).contains(&code) {
        return Some(code as u8);
    }
    CP1252
        .iter()
        .find(|(_, other)| *other == character)
        .map(|(byte, _)| *byte)
}

/// The text of the bytes of the code page of the machine.
///
/// Every byte is a character, and the byte that the code page does not
/// have is the replacement character.
fn decode_cp1252(bytes: &[u8]) -> (String, usize) {
    let mut text = String::new();
    for byte in bytes {
        text.push(the_character_of_cp1252(*byte));
    }
    (text, bytes.len())
}

/// The character of a byte in the code page of the machine.
fn the_character_of_cp1252(byte: u8) -> char {
    match byte {
        0x80..=0x9F => match CP1252.iter().find(|(code, _)| *code == byte) {
            Some((_, character)) => *character,
            None => '\u{FFFD}',
        },
        other => other as char,
    }
}

/// The bytes of the text, in the encoding.
pub(crate) fn encode(text: &str, encoding: Encoding) -> Vec<u8> {
    match encoding {
        Encoding::Cp1252 => encode_cp1252(text),
        Encoding::Utf8 { .. } => text.as_bytes().to_vec(),
        Encoding::Utf16 { .. } => {
            let mut bytes = Vec::new();
            for character in text.chars() {
                let mut units = [0u16; 2];
                for unit in character.encode_utf16(&mut units) {
                    bytes.extend_from_slice(&unit.to_le_bytes());
                }
            }
            bytes
        }
    }
}

/// The text of the bytes, in the encoding, and how many bytes of them
/// the text is.
pub(crate) fn decode(bytes: &[u8], encoding: Encoding) -> Result<(String, usize), String> {
    match encoding {
        Encoding::Cp1252 => Ok(decode_cp1252(bytes)),
        Encoding::Utf8 { .. } => decode_utf8(bytes),
        Encoding::Utf16 { .. } => decode_utf16(bytes),
    }
}

/// The text of the bytes of a UTF-8 file, and how many of them it used.
///
/// A character that is cut in half at the end of the bytes is not text
/// yet: it is left for the next read.
fn decode_utf8(bytes: &[u8]) -> Result<(String, usize), String> {
    match core::str::from_utf8(bytes) {
        Ok(text) => Ok((text.to_string(), bytes.len())),
        Err(error) if error.error_len().is_none() => {
            let used = error.valid_up_to();
            let text = core::str::from_utf8(&bytes[..used]).map_err(|_| broken())?;
            Ok((text.to_string(), used))
        }
        Err(_) => Err(broken()),
    }
}

/// The text of the bytes of a UTF-16 file, and how many of them it used.
///
/// The units are little endian, and a unit that is cut in half at the
/// end of the bytes is left for the next read.
fn decode_utf16(bytes: &[u8]) -> Result<(String, usize), String> {
    let mut text = String::new();
    let mut used = 0usize;
    let mut lead: Option<u16> = None;
    let mut index = 0usize;
    while index + 1 < bytes.len() {
        let unit = u16::from_le_bytes([bytes[index], bytes[index + 1]]);
        match lead.take() {
            Some(high) => {
                if !(0xDC00..0xE000).contains(&unit) {
                    return Err(broken());
                }
                let code = 0x10000 + ((high as u32 - 0xD800) << 10) + (unit as u32 - 0xDC00);
                text.push(char::from_u32(code).ok_or_else(broken)?);
                used = index + 2;
            }
            None => {
                if (0xD800..0xDC00).contains(&unit) {
                    // The unit is the first half of a pair: the second
                    // half may be in the next read.
                    lead = Some(unit);
                } else if (0xDC00..0xE000).contains(&unit) {
                    return Err(broken());
                } else {
                    text.push(char::from_u32(unit as u32).ok_or_else(broken)?);
                    used = index + 2;
                }
            }
        }
        index += 2;
    }
    Ok((text, used))
}

/// The reason why the bytes of a file are not text.
fn broken() -> String {
    "the bytes of the file are not text in this encoding.".to_string()
}

/// The first characters of the text, and the bytes they take.
fn take(text: &str, count: usize) -> (String, usize) {
    match text.char_indices().nth(count) {
        Some((at, _)) => (text[..at].to_string(), at),
        None => (text.to_string(), text.len()),
    }
}

/// The bytes of the line, and the byte after the newline that ends it.
fn line_of(bytes: &[u8], encoding: Encoding) -> Option<(usize, usize)> {
    match encoding {
        // The line of a text of the code page ends with the same byte
        // as the line of a text of UTF-8.
        Encoding::Cp1252 | Encoding::Utf8 { .. } => {
            let at = bytes.iter().position(|byte| *byte == 0x0A)?;
            // A line that ends with a carriage return and a newline
            // does not carry the carriage return.
            let end = if at > 0 && bytes[at - 1] == 0x0D {
                at - 1
            } else {
                at
            };
            Some((end, at + 1))
        }
        Encoding::Utf16 { .. } => {
            let at = bytes
                .windows(2)
                .position(|pair| pair[0] == 0x0A && pair[1] == 0x00)?;
            let end = if at >= 2 && bytes[at - 2] == 0x0D && bytes[at - 1] == 0x00 {
                at - 2
            } else {
                at
            };
            Some((end, at + 2))
        }
    }
}

/// A whole number out of the bytes, little endian.
fn little(bytes: &[u8]) -> u64 {
    bytes
        .iter()
        .fold(0u64, |acc, byte| (acc << 8) | *byte as u64)
}

/// The bytes of a whole number, little endian, as many as the type
/// takes.
fn little_bytes(number: u64, count: usize) -> Vec<u8> {
    let mut bytes = vec![0u8; count];
    for (index, byte) in bytes.iter_mut().rev().enumerate() {
        *byte = ((number >> (index * 8)) & 0xFF) as u8;
    }
    bytes
}

/// The bytes of a float, little endian: four of them for a single
/// precision float, eight for a double.
fn float_bytes(number: f64, single: bool) -> Vec<u8> {
    if single {
        little_bytes((number as f32).to_bits() as u64, 4)
    } else {
        little_bytes(number.to_bits(), 8)
    }
}

// -- the base object ----------------------------------------------------------

/// The methods of the base object, answered for a file.
///
/// The runtime answers them for the classes of the script, and it knows
/// nothing of the class types of the runtime: a file has no method of
/// the script, and the handle of a file is not a property of it.
fn base_method(
    method: &str,
    this: &Value,
    arguments: &[Value],
    rt: &mut Runtime,
    line: u32,
) -> Option<Result<Value, RuntimeFailure>> {
    let Value::Object(object) = this else {
        return None;
    };
    let failure = |message: &str| {
        Some(Err(RuntimeFailure::Error(RuntimeError {
            message: message.to_string(),
            line,
        })))
    };
    let name = arguments
        .first()
        .map(|value| value.to_text())
        .unwrap_or_default();
    let key = name.to_lowercase();
    match method {
        "ownprops" => {
            // Measured on the binary of v2.0.19 on 2026-10-31: the own
            // properties of v2 are an enumerator, and it gives the name
            // when the caller wants one value.
            let pairs: Vec<(Value, Value)> = object
                .borrow()
                .properties
                .iter()
                .filter(|(name, _)| name.as_str() != STATE)
                .map(|(_, property)| (Value::Text(property.name.clone()), property.value.clone()))
                .collect();
            Some(Ok(enumerator::make(pairs, enumerator::Alone::TheKey)))
        }
        "hasownprop" => Some(Ok(Value::Int(own_property(object, &key) as i64))),
        "hasprop" => Some(Ok(Value::Int(
            (PROPERTIES.contains(&key.as_str())
                // The methods of the class are the properties of the value.
                //
                // Measured on the binary of v2.0.19 on 2026-10-31:
                // `m.HasProp("Get")` answers 1.
                || METHODS.contains(&key.as_str())
                || own_property(object, &key)
                // Every value carries its class, and the base object has
                // the property of it.
                || key == "__class"
                // Every class has an initialiser, and every object has a
                // base.
                //
                // Measured on the binary of v2.0.19 on 2026-10-31:
                // `m.HasProp("__Init")` and `m.HasProp("Base")` answer 1.
                || key == "__init"
                || key == "base") as i64,
        ))),
        "hasmethod" => Some(Ok(Value::Int(
            (METHODS.contains(&key.as_str())
                // Every class has an initialiser.
                //
                // Measured on the binary of v2.0.19 on 2026-10-31:
                // `m.HasMethod("__Init")` answers 1.
                || key == "__init") as i64,
        ))),
        "getownpropdesc" => {
            let name = arguments
                .first()
                .map(|value| value.to_text())
                .unwrap_or_default();
            let value = object.borrow().value_of(&key);
            match value {
                Some(value) => {
                    // Measured on the binary of v2.0.19 on 2026-10-31: the
                    // descriptor that comes back is an object with the
                    // members of it.
                    let table = match rt.the_members_of_a_descriptor(&value) {
                        Some(members) => members,
                        None => {
                            let mut table = BTreeMap::new();
                            put(&mut table, "value", value);
                            table
                        }
                    };
                    Some(Ok(Value::Object(Rc::new(RefCell::new(Object {
                        class: "object".to_string(),
                        properties: table,
                    })))))
                }
                // The property is not there: v2 says so.
                None => Some(Err(rt.no_property(this, &name, line))),
            }
        }
        "defineprop" => {
            if key == STATE {
                return failure("the state of a file is not a property of it.");
            }
            // Measured on the binary of v2.0.19 on 2026-10-31: the second
            // parameter is a descriptor, and a value that is not one is
            // refused with the reason.
            let descriptor = match rt.the_descriptor(arguments.get(1), line) {
                Ok(descriptor) => descriptor,
                Err(failure) => return Some(Err(failure)),
            };
            put(&mut object.borrow_mut().properties, &name, descriptor);
            // The answer of v2 is the object itself.
            Some(Ok(this.clone()))
        }
        "deleteprop" => {
            if key == STATE {
                return Some(Ok(Value::Text(String::new())));
            }
            let gone = object
                .borrow_mut()
                .properties
                .remove(&key)
                .map(|property| property.value);
            // Measured on the binary of v2.0.19 on 2026-10-31: the answer
            // is the value of the property that is taken away, and an
            // empty text when there was none.
            Some(Ok(match gone {
                None => Value::Text(String::new()),
                Some(value) => match rt.the_value_of_the_descriptor(&value, this, &name, line) {
                    Ok(Some(value)) => value,
                    _ => value,
                },
            }))
        }
        _ => None,
    }
}

/// Whether the file has a property of that name.
///
/// The state of the file is not a property of it: it is the inside of
/// the file, and the script never wrote it.
fn own_property(object: &Rc<RefCell<Object>>, key: &str) -> bool {
    key != STATE && object.borrow().properties.contains_key(key)
}