hexicon 0.2.0

Hexicon, for writing interactive fiction: builds a game, plays it in a terminal, tests it, documents it, and serves editors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
//! The `hexicon` command-line tool.

mod build;
mod doc;
mod new;
mod preprocess;
mod resources;
mod terminal;
mod test;
mod windows_zones;

use std::fmt::Write as _;
use std::io::Write as _;
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;

use hexicon_bytecode::listing::{Names, write_function};
use hexicon_bytecode::{Extent, discover};
use hexicon_host::{FileError, FileInfo, Host, Input, Sandbox, file_attr, file_type, pane};
use hexicon_image::{Image, Pool, Value};
use hexicon_vm::Vm;

const USAGE: &str = "\
usage: hexicon <command>

commands:
  new [--choices] <folder>     start a game in a new folder: a manifest
                               (hexicon.toml) and a first source
                               (start.hxn) on Hexad, ready to build;
                               with --choices, a game played by
                               choosing, on Hexad's choices extension
  ifid                         print a new IFID, the identifier that tells
                               a game from every other: give it to a
                               game's story, and keep it in every version
  run [options] <game> [args...]
                               play a game (a .hxg file); the options
                               are:
      --no-random              make the same random choices on every run,
                               even when the program reseeds at random
      --plain                  treat a terminal as plain input and output:
                               80 columns, no pauses, and keys read as lines
      --rich                   be a rich display that can show and play
                               everything, and write the document the
                               game's markup makes, checked, as text
      --no-pause               do not pause when a screenful has gone by
      --clock <time>           start the clock at a time in UTC
                               (2000-01-01T09:15:00), and move it on a
                               millisecond each time the program reads it,
                               so that it reads the same on every run
      --script <file>          read input from a command script before
                               asking for any
      --sandbox <dir>          the folder the program's file access is
                               confined to (default: the image's folder)
      --safety <read><write>   how far file access is confined, as two
                               digits: 0 for anywhere, 1 for reading
                               anywhere but writing only in the sandbox,
                               2 for the sandbox only, 3 for reading in
                               the sandbox only, 4 for nowhere (default 22)
  build [options] [<module>...]
                               build a game from its sources and
                               libraries, as its manifest (hexicon.toml)
                               says; with no options, the manifest in
                               the current folder. The options say the
                               same as a manifest can. A source named
                               without an extension is a .hxn file. A
                               library is a folder with a hexicon.toml,
                               or a .toml manifest of its name:
      -f <manifest>            read more options and modules from a
                               manifest, or a folder with one (default:
                               hexicon.toml, if nothing else is given);
                               a .toml file among the modules is the same
      --source <file>          a source file, whatever its name
      --test <file>            a source built only for debugging (-d),
                               such as a game's scenarios; a manifest's
                               tests are these
      --library <file>         a library, whatever its name; --exclude
                               <name> after it leaves out one of its
                               sources, and --include <path> adds a
                               source from its folder, such as one of
                               its extensions
      -o <game>                where to write the game (default: the
                               manifest's image, or beside the first
                               source, as a .hxg file)
      -I <dir>                 a folder to look for included files in
      -D <name>[=<text>]       define a macro (as nothing, without a text)
      -U <name>                undefine a macro
      --charset <name>         the character set of source files that do
                               not say what they are in (default: UTF-8)
      --library-path <dir>     a folder to look for sources and libraries
                               in, before those of HEXICON_LIB and the
                               libraries built in
      --no-system              build without the system library, which
                               every program is otherwise built on; the
                               program defines its own _main
      --no-preinit, --preinit  whether to run the program before the
                               image is written (default: --preinit,
                               unless -d)
      -d                       build for debugging: __DEBUG defined, no
                               preinitialization by default, resources
                               linked to their files, and the symbols and
                               macros a debugger uses (every build records
                               the line each statement is on, so that a
                               run-time error says where it happened)
      --no-warnings, --warnings, --warnings-as-errors
                               no warnings; warnings; warnings stop the
                               build
      -v                       list the sources as they are compiled
      --resources <file>...    after the modules: files and folders to
                               bundle as resources, each as <file> or
                               <file>=<name>, with --no-recurse and
                               --recurse for whether a folder's folders
                               go too
      --unspecified <file>     list the parts of the image that mean
                               nothing, such as the time it was compiled,
                               each as an offset and a length; a comparison
                               of two images should skip them
  test [options] [<name>...]   build a game for debugging, play its
                               scenarios (or the scenarios and
                               walkthroughs named), and report how they
                               went: the exit status is 0 if they all
                               passed, 1 if not, and 2 if the game could
                               not be built or played them. The game
                               includes Hexad's extensions/scenarios.
                               The options are:
      -f <manifest>, --library-path <dir>
                               as for build
      --walkthroughs           play every walkthrough as well
      --transcript <file>      keep what the game said
      --report <file>          write what happened there too, in JSON,
                               for programs (as VS Code's Testing view
                               reads it), even if the game is not built
  test [-f <manifest>] --print <walkthrough> [--for-players]
                               play a walkthrough, and if it passes,
                               write it as a commented walkthrough in
                               Markdown; how it went goes to the error
                               output. --for-players writes it in the
                               words the game gives players, each part
                               closed until it is opened
  doc [-f <manifest> | --library <name>] [--library-path <dir>]
      [-D <name>=<value>] [-o <folder>]
                               write the game's reference, as pages of
                               HTML: every class and object its sources
                               and libraries define, with what each is
                               built on, its properties and methods, and
                               the comments above them; its source
                               files, extensions, functions, actions,
                               messages, macros, and enumerations; and a
                               search; in the folder reference, unless
                               -o names another. --library writes a
                               library's reference instead, with no
                               game: the library (hexad), every one of
                               its extensions, and the libraries it is
                               built on; LANGUAGE is english unless -D
                               says
  english <source>...          show the Hexicon source English sources
                               (.hxe files) become, read together as a
                               build reads them, or what in them could
                               not be read
  lsp [--stdio]                be a language server for an editor, over
                               standard input and output: the problems
                               of a game's sources as they are typed,
                               their outlines, where a name
                               is defined and what it is, completion,
                               where it is used, renaming it, a search
                               of the names, and a game's map
  preinit [--unspecified <file>] <game> <new-game> [args...]
                               run a program as it is run before its
                               image is written, and write the image it
                               leaves
  preprocess [options] <source>
                               write a source file's preprocessed text;
                               the options are:
      -f <manifest>            read the source as the game's build reads
                               it: with the macros, include paths, and
                               libraries the manifest (or a folder with
                               one) gives, and the options below as
                               build takes them
      -I <dir>                 a folder to look for included files in
      -D <name>[=<text>]       define a macro (as 1, without a text;
                               with -f, as build does)
      -U <name>                undefine a macro
      --charset <name>         the character set of source files that do
                               not say what they are in (default: UTF-8)
      -d                       with -f, as a build for debugging
      --test                   name files without their folders
  tokens [options] <source>    list a source file's tokens, as the compiler
                               reads them; the options are the same
  dump <game>                  describe the contents of a game file
  disasm <game>                list the byte code of every function found
  disasm --summary <game>      report how much of the code was accounted for
  --version                    say which version of hexicon this is
";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    if let ["run", rest @ ..] = args.as_slice() {
        let mut options = RunOptions {
            seed_random: true,
            plain: false,
            rich: false,
            paging: true,
            script: None,
            sandbox: None,
            safety: (2, 2),
            clock: None,
        };
        let mut rest = rest;
        loop {
            match rest {
                ["--no-random", tail @ ..] => {
                    options.seed_random = false;
                    rest = tail;
                }
                ["--plain", tail @ ..] => {
                    options.plain = true;
                    rest = tail;
                }
                ["--rich", tail @ ..] => {
                    options.rich = true;
                    options.plain = true;
                    rest = tail;
                }
                ["--no-pause", tail @ ..] => {
                    options.paging = false;
                    rest = tail;
                }
                ["--clock", time, tail @ ..] => {
                    let Some(millis) = unix_millis_of(time) else {
                        eprintln!(
                            "hexicon: --clock takes a time such as 2000-01-01T09:15:00, \
                             not \"{time}\""
                        );
                        return ExitCode::FAILURE;
                    };
                    options.clock = Some(millis);
                    rest = tail;
                }
                ["--script", file, tail @ ..] => {
                    options.script = Some(file);
                    rest = tail;
                }
                ["--sandbox", dir, tail @ ..] => {
                    options.sandbox = Some(dir);
                    rest = tail;
                }
                ["--safety", levels, tail @ ..] => {
                    let digits: Vec<u8> = levels
                        .bytes()
                        .filter(|digit| (b'0'..=b'4').contains(digit))
                        .map(|digit| digit - b'0')
                        .collect();
                    options.safety = match (digits.as_slice(), levels.len()) {
                        ([both], 1) => (*both, *both),
                        ([read, write], 2) => (*read, *write),
                        _ => {
                            eprint!("{USAGE}");
                            return ExitCode::from(2);
                        }
                    };
                    rest = tail;
                }
                [path, program_args @ ..] if !path.starts_with('-') => {
                    return run(path, program_args, &options);
                }
                _ => {
                    eprint!("{USAGE}");
                    return ExitCode::from(2);
                }
            }
        }
    }
    if let ["preinit", rest @ ..] = args.as_slice() {
        return preinit(rest);
    }
    if let ["build", rest @ ..] = args.as_slice() {
        return build::run(rest, USAGE);
    }
    if let ["new", rest @ ..] = args.as_slice() {
        return new::run(rest, USAGE);
    }
    if let ["test", rest @ ..] = args.as_slice() {
        return test::run(rest, USAGE);
    }
    if let ["doc", rest @ ..] = args.as_slice() {
        return doc::run(rest, USAGE);
    }
    // `--stdio` names what it speaks over anyway, as clients often say.
    if let ["lsp"] | ["lsp", "--stdio"] = args.as_slice() {
        return match hexicon_lsp::run(build::default_paths()) {
            Ok(()) => ExitCode::SUCCESS,
            Err(problem) => {
                eprintln!("hexicon lsp: {problem}");
                ExitCode::FAILURE
            }
        };
    }
    if let ["english", rest @ ..] = args.as_slice() {
        return english(rest);
    }
    if let ["preprocess", rest @ ..] = args.as_slice() {
        return preprocess::run(rest, USAGE, preprocess::Output::Text);
    }
    if let ["tokens", rest @ ..] = args.as_slice() {
        return preprocess::run(rest, USAGE, preprocess::Output::Tokens);
    }
    let (path, result) = match args.as_slice() {
        ["dump", path] => (path, dump(path)),
        ["disasm", "--summary", path] => (path, disasm(path, true)),
        ["disasm", path] => (path, disasm(path, false)),
        ["ifid"] => {
            println!("{}", hexicon_compiler::ifid::new());
            return ExitCode::SUCCESS;
        }
        ["--version"] => {
            println!("hexicon {}", env!("CARGO_PKG_VERSION"));
            return ExitCode::SUCCESS;
        }
        ["help" | "--help" | "-h"] => {
            emit(USAGE);
            return ExitCode::SUCCESS;
        }
        _ => {
            eprint!("{USAGE}");
            return ExitCode::from(2);
        }
    };
    match result {
        Ok(text) => {
            emit(&text);
            ExitCode::SUCCESS
        }
        Err(message) => {
            eprintln!("hexicon: {path}: {message}");
            ExitCode::FAILURE
        }
    }
}

/// `hexicon english`: the Hexicon source English sources become, read
/// together as a build reads them, or what in them could not be read, as
/// the build shows a problem.
fn english(args: &[&str]) -> ExitCode {
    if args.is_empty() || args.iter().any(|arg| arg.starts_with('-')) {
        eprint!("{USAGE}");
        return ExitCode::from(2);
    }
    let mut texts = Vec::new();
    for path in args {
        match std::fs::read(path) {
            Ok(bytes) => texts.push(String::from_utf8_lossy(&bytes).into_owned()),
            Err(err) => {
                eprintln!("hexicon: {path}: {err}");
                return ExitCode::FAILURE;
            }
        }
    }
    let sources: Vec<(&str, &str)> = args
        .iter()
        .zip(&texts)
        .map(|(path, text)| (*path, text.as_str()))
        .collect();
    let translations = hexicon_compiler::english::translate_all(&sources);
    if translations.iter().all(|t| t.problems.is_empty()) {
        let mut out = String::new();
        for (path, translation) in args.iter().zip(&translations) {
            if args.len() > 1 {
                out.push_str(&format!("// {path}\n"));
            }
            out.push_str(&translation.text());
            if args.len() > 1 {
                out.push('\n');
            }
        }
        emit(&out);
        return ExitCode::SUCCESS;
    }
    for (path, translation) in args.iter().zip(&translations) {
        for (line, message) in &translation.problems {
            let problem = hexicon_compiler::pp::Diagnostic {
                file: (*path).to_owned(),
                line: *line,
                message: message.clone(),
                hexicon: true,
                ..Default::default()
            };
            eprint!("{}", build::show_hexicon(&problem, "error"));
        }
    }
    ExitCode::FAILURE
}

/// Write to standard output. A reader that stops early, such as a pager, is
/// not an error.
fn emit(text: &str) {
    let _ = std::io::stdout().lock().write_all(text.as_bytes());
}

/// How to run a program.
struct RunOptions<'a> {
    /// Seed the random number generator from the system.
    seed_random: bool,
    /// Make nothing of standard input and output being a terminal.
    plain: bool,
    /// Be a rich display that can do everything, and write the document
    /// the program's markup makes, checked, as text.
    rich: bool,
    /// Pause when a screenful of text has gone by.
    paging: bool,
    /// A command script to read input from.
    script: Option<&'a str>,
    /// The folder file access is confined to, if not the image's.
    sandbox: Option<&'a str>,
    /// The file safety levels for reading and for writing.
    safety: (u8, u8),
    /// The time the clock starts at, in milliseconds since 1970 began,
    /// for a clock that reads the same on every run.
    clock: Option<i64>,
}

/// A time written `YYYY-MM-DDTHH:MM:SS`, in UTC, as milliseconds since
/// 1970 began.
fn unix_millis_of(text: &str) -> Option<i64> {
    let (date, time) = text.split_once('T')?;
    let numbers = |part: &str, sep: char| -> Option<Vec<i64>> {
        part.split(sep).map(|n| n.parse().ok()).collect()
    };
    let [year, month, day] = numbers(date, '-')?[..] else {
        return None;
    };
    let [hour, minute, second] = numbers(time, ':')?[..] else {
        return None;
    };
    if !(1..=12).contains(&month)
        || !(1..=31).contains(&day)
        || hour > 23
        || minute > 59
        || second > 59
    {
        return None;
    }
    // Days since 1970 began, by the civil calendar.
    let (y, m) = if month <= 2 {
        (year - 1, month + 9)
    } else {
        (year, month - 3)
    };
    let era = y.div_euclid(400);
    let year_of_era = y - era * 400;
    let day_of_year = (153 * m + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    let days = era * 146_097 + day_of_era - 719_468;
    Some(((days * 24 + hour) * 60 + minute) * 60_000 + second * 1000)
}

/// A host that writes program output to standard output, reads input
/// from standard input, and keeps the program's files beside its image,
/// as the reference interpreter does.
struct Console {
    /// The folder a file name without one is taken to be in.
    file_base: PathBuf,
    /// The folder the program's file access is confined to.
    sandbox: PathBuf,
    /// How many temporary file names have been handed out.
    temp_count: u32,
    /// The terminal, when that is what the program is being run in.
    terminal: Option<terminal::Terminal>,
    /// Make the program stop and resume at every read, to test that.
    stall: bool,
    stalled: bool,
    /// Whether seeding at random uses the system's entropy. Without it,
    /// every seed is the same, so that a program which reseeds at random
    /// (`randomize()`) still makes the same choices on every run.
    entropy: bool,
    /// For a clock that reads the same on every run, the time it reads
    /// next, in milliseconds since 1970 began.
    clock: Option<i64>,
    /// On a rich display, the checkers the program's markup goes through,
    /// and its panes.
    rich: Option<RichConsole>,
}

/// A rich display that writes the document it is given, checked, as text.
struct RichConsole {
    /// The document, the main window's and the panes'.
    document: hexicon_host::rich::Document,
    /// The panes, laid out on a screen of the plain console's size.
    screen: pane::Screen,
}

impl RichConsole {
    fn new() -> Self {
        RichConsole {
            document: hexicon_host::rich::Document::new(),
            // A rich display can have panes at the main window's sides.
            screen: pane::Screen::new(24, 81, true),
        }
    }

    /// Write out what the document has been given since last time.
    fn emit(&mut self) {
        emit(&self.document.take_text());
    }
}

impl Console {
    /// The file a program's name for it refers to.
    fn path(&self, name: &str) -> PathBuf {
        self.file_base.join(name)
    }

    /// Change the terminal's panes, if it has any, and draw them.
    fn with_panes(&mut self, change: impl FnOnce(&mut pane::Screen)) {
        if let Some(terminal) = &mut self.terminal {
            terminal.panes(change);
        }
    }

    /// Change what the terminal's panes hold, to be drawn later.
    fn with_panes_later(&mut self, change: impl FnOnce(&mut pane::Screen)) {
        if let Some(terminal) = &mut self.terminal {
            terminal.panes_later(change);
        }
    }
}

/// A path from its root, with `.` and `..` worked out by name alone, so
/// that it has an answer for a file that does not exist yet.
fn full_path(path: &Path) -> PathBuf {
    // An empty path is the current folder.
    let path = if path.as_os_str().is_empty() {
        Path::new(".")
    } else {
        path
    };
    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
    let mut out = PathBuf::new();
    for part in absolute.components() {
        match part {
            Component::CurDir => {}
            Component::ParentDir => {
                out.pop();
            }
            other => out.push(other),
        }
    }
    out
}

/// A path in the syntax programs use, with `/` between the parts.
fn program_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// Whether two paths are the same, on a system where the case of
/// letters does not tell names apart.
fn same_part(a: &std::ffi::OsStr, b: &std::ffi::OsStr) -> bool {
    if cfg!(windows) {
        a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase()
    } else {
        a == b
    }
}

/// Whether `path` is `dir` or somewhere within it.
fn starts_with(path: &Path, dir: &Path) -> bool {
    let mut parts = path.components();
    dir.components().all(|part| {
        parts
            .next()
            .is_some_and(|other| same_part(other.as_os_str(), part.as_os_str()))
    })
}

fn seconds(time: std::io::Result<std::time::SystemTime>) -> Option<i64> {
    let since = time.ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;
    Some(since.as_secs() as i64)
}

impl Host for Console {
    fn print(&mut self, text: &str) {
        match &mut self.terminal {
            Some(terminal) => terminal.print(text),
            None => emit(text),
        }
    }

    fn rich_display(&self) -> Option<hexicon_host::rich::RichDisplay> {
        self.rich
            .as_ref()
            .map(|_| hexicon_host::rich::RichDisplay::full())
    }

    fn print_markup(&mut self, markup: &str) {
        if let Some(rich) = &mut self.rich {
            rich.document.write(markup);
            rich.emit();
        }
    }

    fn print_input(&mut self, text: &str) {
        if let Some(rich) = &mut self.rich {
            rich.document.input(text);
            rich.emit();
        }
    }

    fn pane_write_markup(&mut self, id: u32, markup: &str) {
        if let Some(rich) = &mut self.rich {
            rich.document.pane_write(id, markup);
        }
    }

    fn console_width(&mut self) -> Option<usize> {
        self.terminal.as_mut()?.width()
    }

    fn script_input(&mut self) {
        if let Some(terminal) = &mut self.terminal {
            terminal.start_page();
        }
    }

    fn random_bytes(&mut self, buffer: &mut [u8]) {
        if !self.entropy {
            return;
        }
        // The standard library seeds each hasher state from the system's
        // entropy source, which is the only access to it without another
        // dependency.
        use std::hash::{BuildHasher, Hasher};
        for chunk in buffer.chunks_mut(8) {
            let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
            hasher.write_u64(0);
            let bytes = hasher.finish().to_le_bytes();
            chunk.copy_from_slice(&bytes[..chunk.len()]);
        }
    }

    // A file name is a path, relative to the folder the image is in.
    fn read_file(&mut self, name: &str) -> Result<Vec<u8>, FileError> {
        std::fs::read(self.path(name)).map_err(file_error)
    }

    fn write_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
        std::fs::write(self.path(name), data).map_err(file_error)
    }

    fn file_info(&mut self, name: &str, follow_links: bool) -> Option<FileInfo> {
        let path = self.path(name);
        let meta = if follow_links {
            std::fs::metadata(&path)
        } else {
            std::fs::symlink_metadata(&path)
        }
        .ok()?;
        let kind = if meta.is_dir() {
            file_type::DIR
        } else if meta.is_file() {
            file_type::FILE
        } else if meta.file_type().is_symlink() {
            file_type::LINK
        } else {
            0
        };
        let hidden = Path::new(name)
            .file_name()
            .is_some_and(|base| base.to_string_lossy().starts_with('.'));
        let mut attrs = file_attr::READ;
        if !meta.permissions().readonly() {
            attrs |= file_attr::WRITE;
        }
        if hidden {
            attrs |= file_attr::HIDDEN;
        }
        Some(FileInfo {
            kind,
            attrs,
            size: if meta.is_dir() { 0 } else { meta.len() },
            accessed: seconds(meta.accessed()),
            modified: seconds(meta.modified()),
            created: seconds(meta.created()),
            link_target: std::fs::read_link(&path)
                .ok()
                .map(|target| program_path(&target)),
        })
    }

    fn delete_file(&mut self, name: &str) -> Result<(), FileError> {
        std::fs::remove_file(self.path(name)).map_err(file_error)
    }

    fn rename_file(&mut self, from: &str, to: &str) -> Result<(), FileError> {
        std::fs::rename(self.path(from), self.path(to)).map_err(file_error)
    }

    fn create_dir(&mut self, name: &str, parents: bool) -> Result<(), FileError> {
        let path = self.path(name);
        if path.exists() {
            return Err(FileError::Failed);
        }
        if parents {
            std::fs::create_dir_all(path)
        } else {
            std::fs::create_dir(path)
        }
        .map_err(file_error)
    }

    fn remove_dir(&mut self, name: &str, contents: bool) -> Result<(), FileError> {
        let path = self.path(name);
        if contents {
            std::fs::remove_dir_all(path)
        } else {
            std::fs::remove_dir(path)
        }
        .map_err(file_error)
    }

    // The entries for the directory itself and its parent come first, as
    // systems that list them do.
    fn list_dir(&mut self, name: &str) -> Option<Vec<String>> {
        let mut names = vec![".".to_owned(), "..".to_owned()];
        for entry in std::fs::read_dir(self.path(name)).ok()? {
            names.push(entry.ok()?.file_name().to_string_lossy().into_owned());
        }
        Some(names)
    }

    fn absolute_path(&mut self, name: &str) -> Option<String> {
        Some(program_path(&full_path(&self.path(name))))
    }

    fn root_dirs(&mut self) -> Vec<String> {
        if cfg!(windows) {
            (b'A'..=b'Z')
                .map(|letter| format!("{}:/", char::from(letter)))
                .filter(|root| Path::new(root).exists())
                .collect()
        } else {
            vec!["/".to_owned()]
        }
    }

    fn sandbox(&mut self, name: &str) -> Sandbox {
        let path = full_path(&self.path(name));
        let sandbox = full_path(&self.sandbox);
        let inside = starts_with(&path, &sandbox);
        let contains = starts_with(&sandbox, &path);
        match (inside, contains) {
            (true, true) => Sandbox::Itself,
            (true, false) => Sandbox::Inside,
            (false, true) => Sandbox::Contains,
            (false, false) => Sandbox::Outside,
        }
    }

    fn temp_file_name(&mut self) -> Option<String> {
        let dir = std::env::temp_dir();
        loop {
            self.temp_count += 1;
            let name = format!("hexicon-{}-{}.tmp", std::process::id(), self.temp_count);
            let path = dir.join(name);
            if !path.exists() {
                return Some(program_path(&path));
            }
        }
    }

    // The settings that games share are kept in the user's own
    // configuration folder.
    fn special_file(&mut self, id: i32) -> Option<String> {
        let name = match id {
            1 => "settings.txt",
            2 => "webprefs.txt",
            _ => return None,
        };
        let base = if cfg!(windows) {
            PathBuf::from(std::env::var_os("APPDATA")?)
        } else if let Some(config) = std::env::var_os("XDG_CONFIG_HOME") {
            PathBuf::from(config)
        } else {
            PathBuf::from(std::env::var_os("HOME")?).join(".config")
        };
        let dir = base.join(if cfg!(windows) { "Hexicon" } else { "hexicon" });
        // The folder has to be there before a file can be written in it.
        let _ = std::fs::create_dir_all(&dir);
        Some(program_path(&dir.join(name)))
    }

    fn append_file(&mut self, name: &str, data: &[u8]) -> Result<(), FileError> {
        std::fs::OpenOptions::new()
            .append(true)
            .create(true)
            .open(self.path(name))
            .and_then(|mut file| file.write_all(data))
            .map_err(file_error)
    }

    fn read_line(&mut self) -> Input {
        // For testing the VM's ability to stop and resume: have nothing
        // ready the first time each line is asked for.
        if self.stall {
            self.stalled = !self.stalled;
            if self.stalled {
                return Input::Pending;
            }
        }
        let _ = std::io::stdout().flush();
        if let Some(terminal) = &mut self.terminal {
            terminal.start_page();
        }
        let mut line = String::new();
        match std::io::stdin().read_line(&mut line) {
            Ok(0) | Err(_) => Input::End,
            Ok(_) => {
                let len = line.trim_end_matches(['\r', '\n']).len();
                line.truncate(len);
                Input::Text(line)
            }
        }
    }

    // A terminal delivers keys as they are pressed. Input that is not a
    // terminal, such as a file or a pipe, gives a key a character at a
    // time, as the reference's plain console does, so that what is left
    // of a line goes to whatever reads next. A terminal in plain mode
    // delivers whole lines, so a key is the first character of a line,
    // and an empty line is the Enter key.
    fn read_key(&mut self) -> Input {
        if let Some(terminal) = &mut self.terminal {
            return match terminal.read_key() {
                Some(key) => Input::Text(key),
                None => Input::End,
            };
        }
        if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
            let _ = std::io::stdout().flush();
            return match read_char(&mut std::io::stdin().lock()) {
                Some(key) => Input::Text(key),
                None => Input::End,
            };
        }
        match self.read_line() {
            Input::Text(line) => Input::Text(match line.chars().next() {
                Some(key) => key.to_string(),
                None => "\n".to_owned(),
            }),
            other => other,
        }
    }

    // A stream of text cannot be cleared, and the reference interpreter's
    // plain console does nothing.
    fn clear_screen(&mut self) {
        if let Some(terminal) = &mut self.terminal {
            terminal.clear();
        }
    }

    // A terminal shows the status line at the top, as a pane would be.
    fn status_line(&mut self, text: &str) {
        if let Some(terminal) = &mut self.terminal {
            terminal.set_status(Some(text), None);
        }
    }

    fn status_right(&mut self, text: &str) {
        if let Some(terminal) = &mut self.terminal {
            terminal.set_status(None, Some(text));
        }
    }

    // Panes are for a terminal. Plain output has none, as the
    // reference's plain console has none.
    // A rich display has panes of its own.
    fn has_panes(&self) -> bool {
        self.rich.is_some()
            || self
                .terminal
                .as_ref()
                .is_some_and(terminal::Terminal::has_panes)
    }

    fn pane_create(
        &mut self,
        parent: Option<u32>,
        placement: pane::Placement,
        spec: pane::PaneSpec,
    ) -> Option<u32> {
        if let Some(rich) = &mut self.rich {
            let id = rich.screen.create(parent, placement, spec)?;
            rich.document.pane_created(id);
            rich.emit();
            return Some(id);
        }
        self.terminal.as_mut()?.create_pane(parent, placement, spec)
    }

    fn pane_delete(&mut self, id: u32) {
        if let Some(rich) = &mut self.rich {
            rich.screen.delete(id);
            rich.document.pane_deleted(id);
            rich.emit();
            return;
        }
        self.with_panes(|screen| screen.delete(id));
    }

    fn pane_clear(&mut self, id: u32) {
        if let Some(rich) = &mut self.rich {
            rich.screen.clear(id);
            rich.document.pane_cleared(id);
            rich.emit();
            return;
        }
        self.with_panes_later(|screen| screen.clear(id));
    }

    fn pane_write(&mut self, id: u32, text: &str) {
        self.with_panes_later(|screen| screen.write(id, text));
    }

    fn pane_flush(&mut self, _id: u32) {
        if let Some(rich) = &mut self.rich {
            rich.document.pane_flush();
            rich.emit();
        }
        if let Some(terminal) = &mut self.terminal {
            terminal.flush_panes();
        }
    }

    fn pane_set_size(&mut self, id: u32, size: i32, units: i32, advisory: bool) {
        self.with_panes(|screen| screen.set_size(id, size, units, advisory));
    }

    fn pane_size_to_contents(&mut self, id: u32) {
        self.with_panes(|screen| screen.size_to_contents(id));
    }

    fn pane_go_to(&mut self, id: u32, row: usize, column: usize) {
        self.with_panes_later(|screen| screen.go_to(id, row, column));
    }

    fn pane_info(&mut self, id: u32) -> Option<pane::PaneInfo> {
        if let Some(rich) = &mut self.rich {
            return rich.screen.info(id);
        }
        self.terminal.as_mut()?.pane_info(id)
    }

    fn pane_set_screen_color(&mut self, id: u32, color: u32) {
        self.with_panes_later(|screen| screen.set_screen_color(id, color));
    }

    // The system's name for its zone is found by asking it, since the
    // standard library does not know.
    fn local_time_zone(&mut self) -> Option<String> {
        if let Ok(zone) = std::env::var("TZ") {
            let zone = zone.trim_start_matches(':');
            if zone.contains('/') {
                return Some(zone.to_owned());
            }
        }
        if cfg!(windows) {
            // Windows has names of its own, which a table maps to the
            // database's.
            let output = std::process::Command::new("tzutil")
                .arg("/g")
                .output()
                .ok()?;
            let name = String::from_utf8_lossy(&output.stdout);
            let name = name.trim().trim_end_matches("_dstoff");
            windows_zones::WINDOWS_ZONES
                .iter()
                .find(|(windows, _)| *windows == name)
                .map(|(_, zone)| (*zone).to_owned())
        } else {
            // The system's zone is a link into the zoneinfo folder, or
            // is named in a file.
            if let Ok(target) = std::fs::read_link("/etc/localtime") {
                let target = target.to_string_lossy().into_owned();
                if let Some((_, zone)) = target.split_once("zoneinfo/") {
                    return Some(zone.to_owned());
                }
            }
            let name = std::fs::read_to_string("/etc/timezone").ok()?;
            Some(name.trim().to_owned()).filter(|name| !name.is_empty())
        }
    }

    // The standard library does not know the local time zone's offset,
    // so without a zone name local time is UTC.
    fn time(&mut self) -> hexicon_host::Time {
        if let Some(next) = &mut self.clock {
            let unix_millis = *next;
            *next += 1;
            return hexicon_host::Time {
                unix_millis,
                utc_offset_seconds: 0,
            };
        }
        let unix_millis = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |elapsed| elapsed.as_millis() as i64);
        hexicon_host::Time {
            unix_millis,
            utc_offset_seconds: 0,
        }
    }

    fn sleep(&mut self, milliseconds: u32) -> bool {
        let _ = std::io::stdout().flush();
        std::thread::sleep(std::time::Duration::from_millis(milliseconds.into()));
        true
    }
}

fn file_error(error: std::io::Error) -> FileError {
    match error.kind() {
        std::io::ErrorKind::NotFound => FileError::NotFound,
        std::io::ErrorKind::PermissionDenied => FileError::Denied,
        _ => FileError::Failed,
    }
}

/// Run a program. The program sees its own file name as its first
/// argument, followed by the ones given on the command line.
fn run(path: &str, program_args: &[&str], options: &RunOptions<'_>) -> ExitCode {
    let fail = |message: String| {
        eprintln!("hexicon: {path}: {message}");
        ExitCode::FAILURE
    };
    let data = match std::fs::read(path) {
        Ok(data) => data,
        Err(error) => return fail(error.to_string()),
    };
    let image = match Image::parse(&data) {
        Ok(image) => image,
        Err(error) => return fail(error.to_string()),
    };
    let file_base = Path::new(path)
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    let console = Console {
        sandbox: options
            .sandbox
            .map_or_else(|| file_base.clone(), PathBuf::from),
        file_base,
        temp_count: 0,
        terminal: if options.plain {
            None
        } else {
            terminal::Terminal::detect(options.paging).map(|mut terminal| {
                // The game has the screen to itself, as its panes take
                // the top of it: what the shell showed before is cleared
                // away (into the scrollback, in most terminals).
                if terminal.has_panes() && !options.rich {
                    terminal.clear();
                }
                terminal
            })
        },
        stall: std::env::var_os("HEXICON_TEST_SUSPEND").is_some(),
        stalled: false,
        entropy: options.seed_random,
        clock: options.clock,
        rich: options.rich.then(RichConsole::new),
    };
    let mut vm = match Vm::new(&image, Box::new(console)) {
        Ok(vm) => vm,
        Err(error) => return fail(error.to_string()),
    };
    vm.set_file_safety(options.safety.0, options.safety.1);
    for resource in &image.resources {
        if let Some(contents) = data.get(resource.offset..resource.offset + resource.size as usize)
        {
            vm.add_resource(&resource.name, contents);
        }
    }
    vm.set_error_trace(std::env::var_os("HEXICON_TRACE_ERRORS").is_some());
    vm.set_image_name(path);
    if options.seed_random {
        vm.seed_random();
    }
    if let Some(script) = options.script {
        match std::fs::read(script) {
            // Output is not paused while a script supplies the input.
            Ok(data) => vm.push_input_script(&data, false, false),
            Err(error) => {
                eprintln!("hexicon: {script}: {error}");
                return ExitCode::FAILURE;
            }
        }
    }
    // As under the reference interpreter, the program sees the image's
    // file name without its directory.
    let name = std::path::Path::new(path).file_name().map_or_else(
        || path.to_owned(),
        |name| name.to_string_lossy().into_owned(),
    );
    let mut args = vec![name];
    args.extend(program_args.iter().map(|arg| (*arg).to_owned()));
    let result = vm.run(&args);
    #[cfg(feature = "profile")]
    hexicon_vm::prof::report();
    let code = match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            // The reference interpreter reports the error before it
            // writes out the last, unfinished line of output.
            let message = vm.error_message(&error, true);
            emit(&format!(
                "{message}
"
            ));
            ExitCode::FAILURE
        }
    };
    vm.flush_output();
    vm.close_files();
    code
}

/// Run a program as it is run before its image is written, and write
/// the image it leaves: preinitialization. `path` is the image's name,
/// and `data` the image; the program sees `program_args` as its
/// arguments. Its output goes to the console, as when it runs.
pub(crate) fn preinit_image(
    path: &str,
    data: &[u8],
    unspecified: &[(usize, usize)],
    program_args: &[String],
    symbols: Option<(Vec<hexicon_image::GlobalSymbol>, Vec<hexicon_image::Macro>)>,
) -> Result<hexicon_vm::RebuiltImage, String> {
    let image = Image::parse(data).map_err(|error| error.to_string())?;
    let file_base = Path::new(path)
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    let console = Console {
        sandbox: file_base.clone(),
        file_base,
        temp_count: 0,
        terminal: None,
        stall: false,
        stalled: false,
        entropy: true,
        clock: None,
        rich: None,
    };
    let mut vm = Vm::new(&image, Box::new(console)).map_err(|error| error.to_string())?;
    vm.set_image_name(path);
    if let Some((symbols, macros)) = symbols {
        vm.set_runtime_symbols(symbols, macros);
    }
    let result = vm.run_preinit(program_args);
    if let Err(error) = result {
        // The program has shown an exception it did not handle, with
        // where it happened; what is said here is what it was.
        let message = vm.error_message(&error, false);
        vm.flush_output();
        return Err(message);
    }
    vm.flush_output();
    let rebuilt = vm
        .rewrite_image_keeping(data, unspecified)
        .map_err(|error| vm.error_message(&error, false));
    vm.close_files();
    rebuilt
}

/// `hexicon preinit`: run a program as it is run before its image is
/// written, and write the image it leaves.
fn preinit(args: &[&str]) -> ExitCode {
    let mut unspecified = None;
    let mut rest = args;
    if let ["--unspecified", path, tail @ ..] = rest {
        unspecified = Some(*path);
        rest = tail;
    }
    let [input, output, program_args @ ..] = rest else {
        eprint!("{USAGE}");
        return ExitCode::from(2);
    };
    let data = match std::fs::read(input) {
        Ok(data) => data,
        Err(error) => {
            eprintln!("hexicon: {input}: {error}");
            return ExitCode::FAILURE;
        }
    };
    // The program is given the new image's name, and then its
    // arguments.
    let program_args: Vec<String> = std::iter::once(output)
        .chain(program_args.iter())
        .map(|arg| (*arg).to_owned())
        .collect();
    match preinit_image(input, &data, &[], &program_args, None) {
        Ok(rebuilt) => {
            if let Err(error) = std::fs::write(output, &rebuilt.bytes) {
                eprintln!("hexicon: {output}: {error}");
                return ExitCode::FAILURE;
            }
            if let Some(path) = unspecified {
                let list: String = rebuilt
                    .unspecified
                    .iter()
                    .map(|(offset, len)| {
                        format!(
                            "{offset} {len}
"
                        )
                    })
                    .collect();
                if let Err(error) = std::fs::write(path, list) {
                    eprintln!("hexicon: {path}: {error}");
                    return ExitCode::FAILURE;
                }
            }
            ExitCode::SUCCESS
        }
        Err(message) => {
            eprintln!("error: preinitialization failed: {message}");
            ExitCode::FAILURE
        }
    }
}

fn load(path: &str) -> Result<(Image, usize), String> {
    let data = std::fs::read(path).map_err(|e| e.to_string())?;
    let image = Image::parse(&data).map_err(|e| e.to_string())?;
    Ok((image, data.len()))
}

fn dump(path: &str) -> Result<String, String> {
    let (image, file_size) = load(path)?;
    Ok(describe(&image, file_size))
}

fn disasm(path: &str, summary_only: bool) -> Result<String, String> {
    let (image, _) = load(path)?;
    let found = discover(&image);
    let mut out = String::new();

    if !summary_only {
        let names = Names::new(&image);
        for function in found.functions() {
            write_function(&mut out, &image, &names, function);
            out.push('\n');
        }
    }

    // How much of the code pool the functions account for: their headers,
    // code, exception tables, and debug records.
    let total = image.code_pool.data_len();
    let mut covered = 0usize;
    let mut instructions = 0usize;
    let mut gaps = 0usize;
    let mut gap_bytes = 0usize;
    for function in found.functions() {
        covered += function.size as usize;
        instructions += function.instructions.len();
        if let Extent::Gap { len, .. } = function.extent {
            gaps += 1;
            gap_bytes += len as usize;
        }
    }
    let errors: Vec<_> = found.errors().collect();
    let _ = writeln!(
        out,
        "functions      {}",
        found.by_address.len() - errors.len()
    );
    let _ = writeln!(out, "instructions   {instructions}");
    let _ = writeln!(
        out,
        "code covered   {covered} of {total} bytes ({:.1}%)",
        if total == 0 {
            100.0
        } else {
            covered as f64 * 100.0 / total as f64
        }
    );
    let _ = writeln!(out, "gaps           {gaps} ({gap_bytes} bytes not decoded)");
    let known = image.debug.method_headers.len();
    if known != 0 {
        let _ = writeln!(out, "debug list     {known} method headers in the image");
    }
    let stray: usize = found.functions().map(|f| f.stray_branches.len()).sum();
    let _ = writeln!(out, "stray branches {stray}");
    let _ = writeln!(out, "unreferenced   {}", found.unreferenced.len());
    let _ = writeln!(
        out,
        "dangling       {} references to discarded code",
        found.dangling.len()
    );
    let _ = writeln!(out, "failures       {}", errors.len());
    for (address, error) in errors.iter().take(20) {
        let _ = writeln!(out, "  {address:#x}: {error}");
    }
    Ok(out)
}

/// One character of input, read as UTF-8, or `None` at the end. A
/// carriage return is passed over, so that a line ends the same way
/// whatever wrote it.
fn read_char(input: &mut impl std::io::Read) -> Option<String> {
    let mut byte = [0u8; 1];
    let first = loop {
        match input.read(&mut byte) {
            Ok(1) if byte[0] == b'\r' => continue,
            Ok(1) => break byte[0],
            _ => return None,
        }
    };
    let len = match first {
        0xc0..=0xdf => 2,
        0xe0..=0xef => 3,
        0xf0..=0xf7 => 4,
        _ => 1,
    };
    let mut bytes = vec![first];
    for _ in 1..len {
        match input.read(&mut byte) {
            Ok(1) => bytes.push(byte[0]),
            _ => break,
        }
    }
    Some(String::from_utf8_lossy(&bytes).into_owned())
}

/// A plain-text description of an image.
fn describe(image: &Image, file_size: usize) -> String {
    let mut out = String::new();
    // Writing to a String cannot fail.
    let w = &mut out;

    let header = &image.header;
    let _ = writeln!(w, "format version   {}", header.version);
    let _ = writeln!(w, "created          {}", header.timestamp);
    let config = header.build_configuration;
    let _ = writeln!(
        w,
        "build config     {:02x}{:02x}{:02x}{:02x}",
        config[0], config[1], config[2], config[3]
    );
    let end = image.blocks.last().map_or(0, |b| b.offset + 10);
    let _ = writeln!(
        w,
        "image size       {end} bytes ({} after the image)",
        file_size - end
    );

    let entry = &image.entry_point;
    let _ = writeln!(w, "\nentry point      code offset {:#x}", entry.code_offset);
    let _ = writeln!(w, "method header    {} bytes", entry.method_header_size);
    let _ = writeln!(w, "exception entry  {} bytes", entry.exception_entry_size);
    let _ = writeln!(
        w,
        "debug records    version {}, line {} / table {} / local {} / frame {} bytes",
        entry.debug_version,
        entry.debug_line_entry_size,
        entry.debug_table_header_size,
        entry.debug_local_header_size,
        entry.debug_frame_header_size
    );

    let _ = writeln!(w, "\npools");
    pool(w, "code", &image.code_pool);
    pool(w, "constant", &image.constant_pool);

    let _ = writeln!(w, "\nmetaclasses ({})", image.metaclasses.len());
    for (index, metaclass) in image.metaclasses.iter().enumerate() {
        let objects: usize = image
            .object_blocks
            .iter()
            .filter(|b| b.metaclass_index as usize == index)
            .map(|b| b.objects.len())
            .sum();
        let _ = writeln!(
            w,
            "  {index:>3}  {:<34} {:>3} properties  {objects:>6} objects",
            metaclass.name,
            metaclass.properties.len()
        );
    }

    let _ = writeln!(w, "\nfunction sets ({})", image.function_sets.len());
    for (index, name) in image.function_sets.iter().enumerate() {
        let _ = writeln!(w, "  {index:>3}  {name}");
    }

    let transient: usize = image
        .object_blocks
        .iter()
        .filter(|b| b.transient)
        .map(|b| b.objects.len())
        .sum();
    let object_bytes: usize = image
        .object_blocks
        .iter()
        .flat_map(|b| &b.objects)
        .map(|o| o.data.len())
        .sum();
    let _ = writeln!(
        w,
        "\nstatic objects   {} in {} blocks ({} transient), {} bytes of data",
        image.object_count(),
        image.object_blocks.len(),
        transient,
        object_bytes
    );

    match &image.static_initializers {
        Some(list) => {
            let _ = writeln!(
                w,
                "static init      {} initializers, static code from {:#x}",
                list.initializers.len(),
                list.static_code_offset
            );
        }
        None => {
            let _ = writeln!(w, "static init      none (image is pre-initialized)");
        }
    }

    let _ = writeln!(w, "\nexported symbols ({})", image.symbols.len());
    for symbol in &image.symbols {
        let _ = writeln!(w, "  {:<28} {}", symbol.name, value(symbol.value));
    }

    if !image.resources.is_empty() {
        let _ = writeln!(w, "\nresources ({})", image.resources.len());
        for resource in &image.resources {
            let _ = writeln!(w, "  {:<40} {:>9} bytes", resource.name, resource.size);
        }
    }
    if !image.resource_links.is_empty() {
        let _ = writeln!(w, "\nresource links ({})", image.resource_links.len());
        for link in &image.resource_links {
            let _ = writeln!(w, "  {:<40} -> {}", link.name, link.file_name);
        }
    }

    let debug = &image.debug;
    if !debug.source_files.is_empty()
        || !debug.global_symbols.is_empty()
        || !debug.method_headers.is_empty()
        || !debug.macros.is_empty()
    {
        let lines: usize = debug.source_files.iter().map(|f| f.lines.len()).sum();
        let _ = writeln!(w, "\ndebug information");
        let _ = writeln!(
            w,
            "  source files    {} ({lines} line records)",
            debug.source_files.len()
        );
        let _ = writeln!(w, "  global symbols  {}", debug.global_symbols.len());
        let _ = writeln!(w, "  method headers  {}", debug.method_headers.len());
        let _ = writeln!(w, "  macros          {}", debug.macros.len());
    }

    let _ = writeln!(w, "\nblocks ({})", image.blocks.len());
    let _ = writeln!(w, "  type    offset       size  flags");
    for block in &image.blocks {
        let _ = writeln!(
            w,
            "  {}  {:>8}  {:>9}  {}",
            block.kind,
            block.offset,
            block.size,
            if block.is_mandatory() {
                "mandatory"
            } else {
                "optional"
            }
        );
    }
    out
}

fn pool(w: &mut String, name: &str, pool: &Pool) {
    let _ = writeln!(
        w,
        "  {name:<9} {:>4} pages of {:>5} bytes, {:>4} loaded, {:>9} bytes of data",
        pool.page_count(),
        pool.page_size(),
        pool.loaded_page_count(),
        pool.data_len()
    );
}

fn value(value: Value) -> String {
    match value {
        Value::Nil => "nil".into(),
        Value::True => "true".into(),
        Value::Empty => "empty".into(),
        Value::Object(id) => format!("object {id}"),
        Value::Property(id) => format!("property {id}"),
        Value::Int(n) => format!("integer {n}"),
        Value::Enum(id) => format!("enum {id}"),
        Value::String(offset) => format!("string at {offset:#x}"),
        Value::SelfPrintingString(offset) => format!("self-printing string at {offset:#x}"),
        Value::List(offset) => format!("list at {offset:#x}"),
        Value::CodeOffset(offset) => format!("code at {offset:#x}"),
        Value::FunctionPointer(offset) => format!("function at {offset:#x}"),
        Value::BuiltinFunction { set, index } => format!("built-in function {set}:{index}"),
        Value::Other { type_code, raw } => format!("type {type_code}, raw {raw:02x?}"),
    }
}

#[cfg(test)]
mod tests {
    use super::read_char;

    #[test]
    fn keys_from_a_stream_are_one_character_each() {
        let mut input: &[u8] = "ab\r\né\n".as_bytes();
        let keys: Vec<_> = std::iter::from_fn(|| read_char(&mut input)).collect();
        assert_eq!(keys, ["a", "b", "\n", "é", "\n"]);
    }

    #[test]
    fn a_clock_time_is_read_in_utc() {
        assert_eq!(super::unix_millis_of("1970-01-01T00:00:00"), Some(0));
        assert_eq!(
            super::unix_millis_of("2000-01-01T09:15:00"),
            Some(946_718_100_000)
        );
        assert_eq!(
            super::unix_millis_of("2024-02-29T23:59:59"),
            Some(1_709_251_199_000)
        );
        assert_eq!(super::unix_millis_of("2000-13-01T00:00:00"), None);
        assert_eq!(super::unix_millis_of("2000-01-01"), None);
    }

    /// One source file, held in memory.
    struct OneFile(&'static str);

    impl hexicon_compiler::pp::SourceFiles for OneFile {
        fn read(&mut self, name: &str) -> Option<Vec<u8>> {
            (name == "main.hxn").then(|| self.0.as_bytes().to_vec())
        }

        fn exists(&mut self, name: &str) -> bool {
            name == "main.hxn"
        }
    }

    /// What a program prints, compiled for debugging from `source`.
    fn printed(source: &'static str) -> String {
        let options = hexicon_compiler::CompileOptions {
            debug: true,
            ..hexicon_compiler::CompileOptions::default()
        };
        let compiled =
            hexicon_compiler::compile_program(&mut OneFile(source), &["main.hxn"], &options);
        assert!(
            compiled.diagnostics.is_empty(),
            "{:?}",
            compiled.diagnostics
        );
        let data = compiled.image.expect("an image");
        let image = hexicon_image::Image::parse(&data).expect("a readable image");
        let host = hexicon_host::BufferHost::new();
        let mut vm = hexicon_vm::Vm::new(&image, Box::new(host.clone())).expect("a VM");
        vm.run(&[]).expect("the program runs");
        vm.flush_output();
        host.output()
    }

    #[test]
    fn a_method_says_where_it_is_written() {
        let source = "builtin 'hexicon-vm/010007'\n\
            {\n    collectGarbage(); setSay(val); vmVersion(); vmId(); vmBanner();\n    \
            inPreinit(); debugTrace(mode, ...); globalSymbols(which?);\n    \
            newProperty(); stackTrace(level?, flags?); namedArg(name, defval?);\n    \
            namedArgList(); definitionPlace(obj, prop);\n}\n\
            builtin 'hexicon-io/030007' { print(val, ...); }\n\
            property nothing;\n\
            class Base: object\n    greet() { return 1; }\n;\n\
            thing: Base\n    count = 3\n    expect = (count > 2)\n;\n\
            show(place) { print(place == nil ? 'nil' : place, '\\n'); }\n\
            _main(args)\n{\n    \
            show(definitionPlace(thing, &expect));\n    \
            show(definitionPlace(thing, &greet));\n    \
            show(definitionPlace(thing, &count));\n    \
            show(definitionPlace(thing, &nothing));\n}\n";
        // A method of the object's own, one it inherits, a value, and
        // nothing: the first two are where they are written.
        assert_eq!(printed(source), "main.hxn:15\nmain.hxn:11\nnil\nnil\n");
    }

    #[test]
    fn without_entropy_every_random_seed_is_the_same() {
        use hexicon_host::Host;
        let console = |entropy| super::Console {
            file_base: Default::default(),
            sandbox: Default::default(),
            temp_count: 0,
            terminal: None,
            stall: false,
            stalled: false,
            entropy,
            clock: None,
            rich: None,
        };
        let seed = |entropy| {
            let mut bytes = [0u8; 64];
            console(entropy).random_bytes(&mut bytes);
            bytes
        };
        // As for --no-random: a program that reseeds at random still makes
        // the same choices on every run.
        assert_eq!(seed(false), seed(false));
        assert_ne!(seed(true), seed(true));
    }
}