hexicon 0.1.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
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
//! `hexicon doc`: a game's reference, as pages of HTML. Every class and
//! named object its sources define, its libraries' included, with what
//! it is built on, what is built on it, where it is defined and
//! modified, its properties and methods, those it inherits, and the
//! comments written above each, as [`hexicon_compiler::document`] reads
//! them. With `--library`, a library's reference instead: the library,
//! all its extensions, and the libraries it is built on, with no game.
//!
//! The pages go in a folder of their own: `index.html`, the classes and
//! objects; `files.html`, `extensions.html`, `functions.html`,
//! `actions.html`, `messages.html`, and `macros.html`; `search.html`; a
//! page for each class and object in `objects/`, and
//! for each source file, its lines numbered, in `files/`; and the style
//! sheet. They are static, and need nothing but a browser.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use hexicon_compiler::pp::SourceFiles;
use hexicon_compiler::{
    DocObject, DocPlace, Documented, Project, ProjectError, document, read_project,
};

use crate::preprocess::DiskFiles;

/// The style sheet the pages share.
const STYLE: &str = include_str!("doc.css");

/// What the search page runs: it reads the index of names,
/// `search-index.js`, and lists those that match what is typed.
const SEARCH: &str = include_str!("doc-search.js");

pub(crate) fn run(args: &[&str], usage: &str) -> ExitCode {
    let mut project_args: Vec<String> = Vec::new();
    let mut out: Option<&str> = None;
    let mut library: Option<&str> = None;
    let mut defines: Vec<(String, String)> = Vec::new();
    let mut manifest_named = false;
    let mut rest = args;
    while let Some((first, tail)) = rest.split_first() {
        match (*first, tail) {
            ("-f" | "--library-path", [value, tail @ ..]) => {
                manifest_named |= *first == "-f";
                project_args.push((*first).to_owned());
                project_args.push((*value).to_owned());
                rest = tail;
            }
            ("-o", [dir, tail @ ..]) => {
                out = Some(dir);
                rest = tail;
            }
            ("--library", [name, tail @ ..]) => {
                library = Some(name);
                rest = tail;
            }
            ("-D", [define, tail @ ..]) => {
                let (name, value) = define.split_once('=').unwrap_or((define, "1"));
                defines.push((name.to_owned(), value.to_owned()));
                rest = tail;
            }
            _ => {
                eprint!("{usage}");
                return ExitCode::from(2);
            }
        }
    }
    // A library's reference is of the library alone; a game's, of the
    // game its manifest names.
    if library.is_some() && manifest_named {
        eprintln!(
            "hexicon doc: a reference is of a game (-f) or of a library (--library), not both"
        );
        eprint!("{usage}");
        return ExitCode::from(2);
    }
    let out = PathBuf::from(out.unwrap_or("reference"));
    let (title, documented, game) = match library {
        Some(name) => match library_reference(name, &project_args, &defines, usage) {
            Ok((title, documented)) => (title, documented, false),
            Err(code) => return code,
        },
        None => {
            for (name, value) in &defines {
                project_args.push("-D".to_owned());
                project_args.push(format!("{name}={value}"));
            }
            let project = match read(&mut DiskFiles, &project_args, usage) {
                Ok(project) => project,
                Err(code) => return code,
            };
            let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
            let documented = document(&mut DiskFiles, &sources, &project.options);
            (project_title(&project_args), documented, true)
        }
    };
    if !documented.diagnostics.is_empty() {
        for d in &documented.diagnostics {
            eprintln!("{}({}): {}", d.file, d.line, d.message);
        }
        eprintln!("hexicon doc: the sources could not be read");
        return ExitCode::from(2);
    }
    match write_pages(&out, &title, &documented, game) {
        Ok(count) => {
            println!("Wrote the reference, {count} pages, in {}.", out.display());
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("hexicon doc: {}: {error}", out.display());
            ExitCode::FAILURE
        }
    }
}

/// A project read, or what was wrong, said.
fn read(
    files: &mut dyn SourceFiles,
    project_args: &[String],
    usage: &str,
) -> Result<Project, ExitCode> {
    read_project(files, project_args, &crate::build::default_paths()).map_err(|e| said(e, usage))
}

/// What was wrong with a project, said, and the exit it comes to.
pub(crate) fn said(error: ProjectError, usage: &str) -> ExitCode {
    match error {
        ProjectError::Usage(problem) => {
            if !problem.is_empty() {
                eprintln!("hexicon: {problem}");
            }
            eprint!("{usage}");
            ExitCode::from(2)
        }
        ProjectError::Failed(lines) => {
            for line in lines {
                eprintln!("{line}");
            }
            ExitCode::FAILURE
        }
    }
}

/// Where the manifest of a library's reference is said to be: a folder
/// that no file system has, so the library is found as a game's would be,
/// along the library paths and then among the built-in ones.
const LIBRARY_DOC: &str = "<hexicon doc>";

/// The source the manifest names, since a game must have one; it is left
/// out of what is documented.
const LIBRARY_DOC_SOURCE: &str = "<hexicon doc>/library.hxn";

/// A library's reference: the library, with every one of its extensions,
/// and the libraries it is built on, read as a game with no sources of
/// its own would have them. `LANGUAGE` is `english` unless `-D` says.
fn library_reference(
    name: &str,
    project_args: &[String],
    defines: &[(String, String)],
    usage: &str,
) -> Result<(String, Documented), ExitCode> {
    let mut defines = defines.to_vec();
    if !defines.iter().any(|(n, _)| n == "LANGUAGE") {
        defines.push(("LANGUAGE".to_owned(), "english".to_owned()));
    }
    // Read once to find the library, and then again with its extensions.
    let project = read_library(name, &[], project_args, &defines, usage)?;
    let Some(manifest) = project.libraries.first() else {
        eprintln!("hexicon doc: no library \"{name}\" was found");
        return Err(ExitCode::FAILURE);
    };
    let folder = manifest
        .rfind(['/', '\\'])
        .map_or(String::new(), |at| manifest[..at].to_owned());
    let extensions = extensions_of(&folder);
    let mut project = read_library(name, &extensions, project_args, &defines, usage)?;
    // The stand-in source is the last, as a game's sources come after
    // its libraries'.
    if project
        .sources
        .last()
        .map(|s| s.replace('\\', "/"))
        .as_deref()
        == Some(LIBRARY_DOC_SOURCE)
    {
        project.sources.pop();
        project.options.module_names.pop();
        project.options.from_library.pop();
    }
    let title = read_file(manifest)
        .and_then(|text| manifest_name(&text))
        .unwrap_or_else(|| name.to_owned());
    let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
    let documented = document(&mut DiskFiles, &sources, &project.options);
    Ok((title, documented))
}

/// The project of a library's reference, its manifest made here.
fn read_library(
    name: &str,
    extensions: &[String],
    project_args: &[String],
    defines: &[(String, String)],
    usage: &str,
) -> Result<Project, ExitCode> {
    let toml = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
    let include: Vec<String> = extensions.iter().map(|e| toml(e)).collect();
    let mut manifest = format!(
        "[game]\nsources = [\"library\"]\nlibraries = [{{ name = {}, include = [{}] }}]\n\n[defines]\n",
        toml(name),
        include.join(", ")
    );
    for (name, value) in defines {
        let _ = writeln!(manifest, "{name} = {}", toml(value));
    }
    let mut files = WithManifest {
        manifest: manifest.into_bytes(),
    };
    let mut args = project_args.to_vec();
    args.push("-f".to_owned());
    args.push(format!("{LIBRARY_DOC}/hexicon.toml"));
    // A library not found is said so, not by the made manifest's path.
    match read_project(&mut files, &args, &crate::build::default_paths()) {
        Ok(project) => Ok(project),
        Err(ProjectError::Failed(lines)) if lines.iter().any(|l| l.contains(LIBRARY_DOC)) => {
            eprintln!(
                "hexicon doc: there is no library \"{name}\": a library is looked for along \
                 --library-path and HEXICON_LIB, and then among those built in"
            );
            Err(ExitCode::FAILURE)
        }
        Err(error) => Err(said(error, usage)),
    }
}

/// The files on disk, and the manifest and empty source of a library's
/// reference.
struct WithManifest {
    manifest: Vec<u8>,
}

impl SourceFiles for WithManifest {
    fn read(&mut self, name: &str) -> Option<Vec<u8>> {
        match name.replace('\\', "/").as_str() {
            n if n == format!("{LIBRARY_DOC}/hexicon.toml") => Some(self.manifest.clone()),
            n if n == LIBRARY_DOC_SOURCE => Some(Vec::new()),
            _ => DiskFiles.read(name),
        }
    }

    fn exists(&mut self, name: &str) -> bool {
        let n = name.replace('\\', "/");
        n == format!("{LIBRARY_DOC}/hexicon.toml")
            || n == LIBRARY_DOC_SOURCE
            || DiskFiles.exists(name)
    }

    fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
        DiskFiles.decode(charset, bytes)
    }
}

/// A library's extensions, as a manifest includes them
/// (`extensions/rules`): the sources in its folder `extensions`.
fn extensions_of(folder: &str) -> Vec<String> {
    let dir = format!("{folder}/extensions");
    let paths: Vec<String> = if folder.starts_with(hexicon_compiler::builtin::ROOT) {
        hexicon_compiler::builtin::files_in(&dir)
    } else {
        std::fs::read_dir(&dir)
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .map(|e| e.path().to_string_lossy().into_owned())
                    .collect()
            })
            .unwrap_or_default()
    };
    let mut names: Vec<String> = paths
        .iter()
        .filter_map(|path| {
            let file = path.rsplit(['/', '\\']).next()?;
            // A Hexicon source is named with no extension; a TADS 3 one
            // keeps its ".t".
            if let Some(stem) = file.strip_suffix(".hxn") {
                Some(format!("extensions/{stem}"))
            } else {
                file.ends_with(".t").then(|| format!("extensions/{file}"))
            }
        })
        .collect();
    names.sort();
    names
}

/// A file, built in or on disk.
fn read_file(path: &str) -> Option<String> {
    let bytes = match hexicon_compiler::builtin::file(path) {
        Some(bytes) => bytes.to_vec(),
        None => std::fs::read(path).ok()?,
    };
    String::from_utf8(bytes).ok()
}

/// The name a manifest gives, a game's or a library's.
fn manifest_name(text: &str) -> Option<String> {
    text.lines()
        .find_map(|line| line.trim().strip_prefix("name").map(str::trim))
        .and_then(|rest| rest.strip_prefix('='))
        .map(|value| value.trim().trim_matches('"').to_owned())
}

/// The game's name, from its manifest, for the pages' titles.
fn project_title(project_args: &[String]) -> String {
    let manifest = project_args
        .iter()
        .position(|a| a == "-f")
        .and_then(|at| project_args.get(at + 1))
        .map_or_else(|| PathBuf::from("hexicon.toml"), PathBuf::from);
    // A folder stands for the manifest in it.
    let manifest = if manifest.is_dir() {
        manifest.join("hexicon.toml")
    } else {
        manifest
    };
    std::fs::read_to_string(manifest)
        .ok()
        .and_then(|text| manifest_name(&text))
        .unwrap_or_else(|| "A game".to_owned())
}

/// The pages: what was written, counted.
/// `game` says the reference is a game's, not a library's alone.
fn write_pages(
    out: &Path,
    title: &str,
    documented: &Documented,
    game: bool,
) -> std::io::Result<usize> {
    std::fs::create_dir_all(out.join("objects"))?;
    std::fs::create_dir_all(out.join("files"))?;
    std::fs::write(out.join("reference.css"), STYLE)?;
    std::fs::write(out.join("search.js"), SEARCH)?;
    std::fs::write(
        out.join("search-index.js"),
        Site::new(documented, game).search_index(),
    )?;
    let site = Site::new(documented, game);
    let mut count = 0;
    for (name, page) in [
        ("index.html", site.index(title)),
        ("files.html", site.files_index(title)),
        ("extensions.html", site.extensions_index(title)),
        ("functions.html", site.functions_index(title)),
        ("actions.html", site.actions_index(title)),
        ("messages.html", site.messages_index(title)),
        ("macros.html", site.macros_index(title)),
        ("search.html", site.search_page(title)),
    ] {
        std::fs::write(out.join(name), page)?;
        count += 1;
    }
    if !site.moments.is_empty() {
        std::fs::write(out.join("choices.html"), site.choices_index(title))?;
        count += 1;
    }
    for object in &documented.objects {
        let page = site.object_page(title, object);
        std::fs::write(out.join("objects").join(&site.pages[&object.name]), page)?;
        count += 1;
    }
    for file in &documented.files {
        let page = site.file_page(title, file);
        std::fs::write(out.join("files").join(&site.file_pages[&file.name]), page)?;
        count += 1;
    }
    Ok(count)
}

/// What every page needs to know of the others.
struct Site<'a> {
    documented: &'a Documented,
    by_name: HashMap<&'a str, &'a DocObject>,
    /// Each source file's page, by the file's name as the build has it.
    file_pages: HashMap<String, String>,
    /// Each object's page, by its name: its name, unless another's
    /// differs from it only in case, which a file system may not tell
    /// apart.
    pages: HashMap<String, String>,
    /// What is built on each class, directly.
    children: HashMap<&'a str, Vec<&'a str>>,
    /// The reference is a game's, not a library's alone.
    game: bool,
    /// Whose each message is, by its place among the messages: the
    /// object it is written in, and the member, if it is in one.
    owners: Vec<Option<(&'a str, Option<&'a str>)>>,
    /// Each object's messages, by their places among the messages.
    messages_of: HashMap<&'a str, Vec<usize>>,
    /// The choice moments, in the order they are defined, each with its
    /// choices, in theirs (the choices extension's `ChoiceMoment` and
    /// `Choice`).
    moments: Vec<(&'a DocObject, Vec<&'a DocObject>)>,
    /// The things with choices of their own (a choice in a thing, which a
    /// room's moment lists where the thing can be acted on), each with its
    /// choices, in the order they are defined.
    thing_choices: Vec<(&'a DocObject, Vec<&'a DocObject>)>,
}

impl<'a> Site<'a> {
    fn new(documented: &'a Documented, game: bool) -> Self {
        let objects = &documented.objects;
        let mut by_name = HashMap::new();
        let mut pages = HashMap::new();
        let mut taken: HashSet<String> = HashSet::new();
        let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
        for object in objects {
            by_name.insert(object.name.as_str(), object);
            let mut page = format!("{}.html", object.name);
            let mut n = 2;
            while !taken.insert(page.to_lowercase()) {
                page = format!("{}~{n}.html", object.name);
                n += 1;
            }
            pages.insert(object.name.clone(), page);
            for parent in &object.superclasses {
                children
                    .entry(parent.as_str())
                    .or_default()
                    .push(object.name.as_str());
            }
        }
        for list in children.values_mut() {
            list.sort_by_key(|name| name.to_lowercase());
        }
        // A file's page is named for the file as a reader sees it, its
        // folders joined with hyphens.
        let mut file_pages = HashMap::new();
        let mut taken_files: HashSet<String> = HashSet::new();
        for file in &documented.files {
            let base: String = shown_file(&file.name)
                .chars()
                .map(|c| {
                    if c.is_ascii_alphanumeric() || c == '.' || c == '_' {
                        c
                    } else {
                        '-'
                    }
                })
                .collect();
            let mut page = format!("{base}.html");
            let mut n = 2;
            while !taken_files.insert(page.to_lowercase()) {
                page = format!("{base}~{n}.html");
                n += 1;
            }
            file_pages.insert(file.name.clone(), page);
        }
        let owners: Vec<_> = documented
            .messages
            .iter()
            .map(|m| owner(documented, &m.place))
            .collect();
        let mut messages_of: HashMap<&str, Vec<usize>> = HashMap::new();
        for (n, owner) in owners.iter().enumerate() {
            if let Some((object, _)) = owner {
                messages_of.entry(object).or_default().push(n);
            }
        }
        let is_kind = |object: &DocObject, kind: &str| {
            let mut seen = HashSet::new();
            let mut todo: Vec<&str> = object.superclasses.iter().map(String::as_str).collect();
            while let Some(name) = todo.pop() {
                if name == kind {
                    return true;
                }
                if seen.insert(name)
                    && let Some(parent) = by_name.get(name)
                {
                    todo.extend(parent.superclasses.iter().map(String::as_str));
                }
            }
            false
        };
        let choices: Vec<&DocObject> = documented
            .objects
            .iter()
            .chain(&documented.anonymous)
            .filter(|o| !o.is_class && is_kind(o, "Choice"))
            .collect();
        let mut thing_choices: Vec<(&DocObject, Vec<&DocObject>)> = Vec::new();
        for choice in &choices {
            let Some(owner) = choice
                .value("location")
                .and_then(|l| by_name.get(l).copied())
            else {
                continue;
            };
            if is_kind(owner, "ChoiceMoment") {
                continue;
            }
            match thing_choices.iter_mut().find(|(t, _)| t.name == owner.name) {
                Some((_, list)) => list.push(choice),
                None => thing_choices.push((owner, vec![choice])),
            }
        }
        let moments = documented
            .objects
            .iter()
            // A library's own (the conversation's) are not the game's.
            .filter(|o| !o.is_class && !o.from_library && is_kind(o, "ChoiceMoment"))
            .map(|moment| {
                let mut own: Vec<&DocObject> = choices
                    .iter()
                    .copied()
                    .filter(|c| c.value("location") == Some(moment.name.as_str()))
                    .collect();
                own.sort_by_key(|c| (c.place.file.clone(), c.place.line));
                (moment, own)
            })
            .collect();
        Self {
            documented,
            by_name,
            file_pages,
            pages,
            children,
            game,
            owners,
            messages_of,
            moments,
            thing_choices,
        }
    }

    /// A place, linked to its line on its file's page: from a page at
    /// `root` (`""` at the top, `"../"` in a folder).
    fn place(&self, at: &DocPlace, root: &str) -> String {
        let shown = format!(
            "<span class=\"file\">{}</span>, line {}",
            html(&shown_file(&at.file)),
            at.line
        );
        match self.file_pages.get(&at.file) {
            Some(page) => format!(
                "<a class=\"place\" href=\"{root}files/{}#L{}\">{shown}</a>",
                attr(page),
                at.line
            ),
            None => shown,
        }
    }

    /// Where an object is defined, and modified.
    fn where_defined(&self, object: &DocObject) -> String {
        let mut text = format!(
            "Defined in {}{}",
            self.place(&object.place, "../"),
            if object.from_library {
                ""
            } else {
                ", the game's own"
            }
        );
        if !object.modified_in.is_empty() {
            let places: Vec<String> = object
                .modified_in
                .iter()
                .map(|at| self.place(at, "../"))
                .collect();
            let _ = write!(text, "; modified in {}", places.join(", "));
        }
        text.push('.');
        text
    }

    /// The files, the game's first, each with what it defines.
    fn files_index(&self, title: &str) -> String {
        let mut body = String::new();
        let lede = if self.game {
            "The source files the game is built from, its own and its libraries', and what each defines."
        } else {
            "The source files of the library, its extensions among them, and of the libraries it is built on, and what each defines."
        };
        let _ = write!(body, "<h1>Files</h1>\n<p class=\"lede\">{lede}</p>\n");
        for (heading, library) in [("The game's", false), ("The libraries'", true)] {
            let files: Vec<_> = self
                .documented
                .files
                .iter()
                .filter(|f| f.from_library == library)
                .collect();
            if files.is_empty() {
                continue;
            }
            let _ = writeln!(body, "<h2>{heading}</h2>\n<dl class=\"index\">");
            for file in files {
                let mut defined: Vec<&str> = self
                    .documented
                    .objects
                    .iter()
                    .filter(|o| o.place.file == file.name)
                    .map(|o| o.name.as_str())
                    .collect();
                defined.sort_by_key(|n| n.to_lowercase());
                let links: Vec<String> = defined.iter().map(|n| self.link(n, true)).collect();
                let functions = self
                    .documented
                    .functions
                    .iter()
                    .filter(|f| f.place.file == file.name)
                    .count();
                let mut what = links.join(", ");
                if functions > 0 {
                    if !what.is_empty() {
                        what.push_str("; ");
                    }
                    let _ = write!(
                        what,
                        "{functions} function{}",
                        if functions == 1 { "" } else { "s" }
                    );
                }
                let _ = writeln!(
                    body,
                    "<dt><a href=\"files/{}\">{}</a> <span class=\"from\">{} lines</span></dt><dd>{}</dd>",
                    attr(&self.file_pages[&file.name]),
                    html(&shown_file(&file.name)),
                    file.lines.len(),
                    what
                );
            }
            body.push_str("</dl>\n");
        }
        self.page(&format!("Files: {title}"), "", &body)
    }

    /// The functions, each with its declaration, its place, and its
    /// comment.
    fn functions_index(&self, title: &str) -> String {
        let mut functions: Vec<_> = self.documented.functions.iter().collect();
        functions.sort_by_key(|f| (f.name.to_lowercase(), f.name.clone()));
        let mut body = String::from("<h1>Functions</h1>\n");
        for function in functions {
            let _ = write!(
                body,
                "<div class=\"member\" id=\"{}\">\n<h3><code>{}</code></h3>\n\
                 <p class=\"where\">{}{}</p>\n{}</div>\n",
                attr(&function.name),
                html(&function.declaration),
                self.place(&function.place, ""),
                if function.from_library {
                    ""
                } else {
                    ", the game's own"
                },
                paragraphs(&function.comment)
            );
        }
        self.page(&format!("Functions: {title}"), "", &body)
    }

    /// The actions, each with the words that mean it: every object built
    /// on Action, and the grammar's rules for it.
    fn actions_index(&self, title: &str) -> String {
        let mut actions: Vec<&DocObject> = self
            .documented
            .objects
            .iter()
            .filter(|o| o.name != "Action" && self.ancestors(o).iter().any(|(_, a)| a == "Action"))
            .collect();
        actions.sort_by_key(|o| (o.name.to_lowercase(), o.name.clone()));
        let mut body = String::from(
            "<h1>Actions</h1>\n<p class=\"lede\">Every action, and the rules of the \
             grammar that say the words for it.</p>\n<dl class=\"index\">\n",
        );
        for action in actions {
            let verbs: Vec<String> = self
                .documented
                .verbs
                .iter()
                .filter(|v| v.action == action.name)
                .map(|v| {
                    format!(
                        "<code>{}</code> <span class=\"from\">({})</span>",
                        html(&v.words),
                        self.place(&v.place, "")
                    )
                })
                .collect();
            let _ = writeln!(
                body,
                "<dt>{}</dt><dd>{}{}</dd>",
                self.link(&action.name, true),
                html(&summary(&action.comment)),
                if verbs.is_empty() {
                    String::new()
                } else {
                    format!("<br>{}", verbs.join("<br>"))
                }
            );
        }
        body.push_str("</dl>\n");
        self.page(&format!("Actions: {title}"), "", &body)
    }

    /// The messages a game can give text of its own for, by their ids.
    /// The messages, in the order their page lists them: by id.
    fn sorted_messages(&self) -> Vec<&'a hexicon_compiler::DocMessage> {
        let mut messages: Vec<_> = self.documented.messages.iter().collect();
        messages.sort_by_key(|m| (m.id.to_lowercase(), m.place.file.clone(), m.place.line));
        messages
    }

    fn messages_index(&self, title: &str) -> String {
        let messages = self.sorted_messages();
        let mut body = format!(
            "<h1>Messages</h1>\n<p class=\"lede\">{}</p>\n\
             <table class=\"messages\">\n<tr><th>Id</th><th>Text</th><th>Of</th><th>Where</th></tr>\n",
            if self.game {
                "The messages Hexad and the game show by an id, which a game can give text of \
                 its own for, with the text they have."
            } else {
                "The messages the library shows by an id, which a game can give text of its \
                 own for, with the text they have."
            }
        );
        for (n, message) in messages.iter().enumerate() {
            let _ = writeln!(
                body,
                "<tr id=\"m{n}\"><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
                html(&message.id),
                message_text(message),
                self.owner_link(message, "objects/"),
                self.place(&message.place, "")
            );
        }
        body.push_str("</table>\n");
        self.page(&format!("Messages: {title}"), "", &body)
    }

    /// A whole page, with the bar every page has.
    fn page(&self, title: &str, root: &str, body: &str) -> String {
        page(title, root, body, !self.moments.is_empty())
    }

    /// What is wrong with the game's choices, as far as reading them can
    /// tell: a choice that leads to what is no moment; a moment that
    /// nothing leads to and the game's code does not name, which never
    /// begins; and a moment with no way out, which allows no commands and
    /// that no choices end, however they are chosen. The conditions on
    /// choices (`isAvailable`) are not read, so a way out may yet be one
    /// a condition shuts.
    fn choice_problems(&self) -> Vec<String> {
        let is_moment = |name: &str| self.moments.iter().any(|(m, _)| m.name == name);
        let mut problems = Vec::new();
        for (moment, choices) in &self.moments {
            for choice in choices {
                if let Some(to) = choice.value("leadsTo")
                    && to != "nil"
                    && !is_moment(to)
                {
                    problems.push(format!(
                        "{}: the choice \"{}\" leads to {to}, which is no choice moment",
                        moment.name,
                        label_of(choice)
                    ));
                }
            }
        }
        // A room's moment is begun by being there, and left by its exits:
        // neither check is for it.
        let in_room = |moment: &DocObject| self.is_room_moment(moment);
        // Begun by a choice, or by the game's code.
        for (moment, _) in self.moments.iter().filter(|(m, _)| !in_room(m)) {
            let led_to = self.moments.iter().any(|(_, choices)| {
                choices
                    .iter()
                    .any(|c| c.value("leadsTo") == Some(moment.name.as_str()))
            });
            if !led_to && !self.named_in_code(moment) {
                problems.push(format!(
                    "{}: no choice leads to it, and the game's code does not name it, so it \
                     never begins",
                    moment.name
                ));
            }
        }
        // A way out: a choice that ends it, or leads to a moment with a way
        // out; or choices all chosen once and leading back, which run out,
        // and end it; or commands, which end a moment that allows them.
        let mut ends: HashSet<&str> = HashSet::new();
        loop {
            let before = ends.len();
            for (moment, choices) in &self.moments {
                if ends.contains(moment.name.as_str()) {
                    continue;
                }
                let way_out = in_room(moment)
                    || moment.value("allowCommands") == Some("true")
                    || choices
                        .iter()
                        .all(|c| c.value("leadsTo").is_none() && c.value("isOnce") != Some("nil"))
                    || choices.iter().any(|c| match c.value("leadsTo") {
                        Some("nil") => true,
                        Some(to) => ends.contains(to),
                        None => false,
                    });
                if way_out {
                    ends.insert(moment.name.as_str());
                }
            }
            if ends.len() == before {
                break;
            }
        }
        problems.extend(self.dead_ends());
        for (moment, _) in self.moments.iter().filter(|(m, _)| !in_room(m)) {
            if !ends.contains(moment.name.as_str()) {
                problems.push(format!(
                    "{}: it has no way out: no choice ends it or leads to a moment that ends, \
                     and it allows no commands",
                    moment.name
                ));
            }
        }
        problems
    }

    /// In a choice game (its story's `choiceGame` or `choicesOnly`), the
    /// game's rooms with nothing to choose: no exit given as an object
    /// (an exit that is code is not read), no moment of their own with
    /// choices, and nothing in them with choices of its own. A player
    /// who reaches one has nothing to choose, unless the game ends there.
    fn dead_ends(&self) -> Vec<String> {
        const EXITS: [&str; 16] = [
            "north",
            "south",
            "east",
            "west",
            "northeast",
            "northwest",
            "southeast",
            "southwest",
            "up",
            "down",
            "in",
            "out",
            "port",
            "starboard",
            "fore",
            "aft",
        ];
        let objects = &self.documented.objects;
        let choice_game = objects.iter().any(|o| {
            !o.is_class
                && self.is_a(o, "Story")
                && (o.value("choiceGame") == Some("true") || o.value("choicesOnly") == Some("true"))
        });
        if !choice_game {
            return Vec::new();
        }
        let mut out = Vec::new();
        for room in objects
            .iter()
            .filter(|o| !o.is_class && !o.from_library && self.is_a(o, "Room"))
        {
            // A string, single-quoted or double, is what the player is
            // told: no way out.
            let exits = EXITS.iter().any(|d| {
                room.value(d)
                    .is_some_and(|v| v != "nil" && !v.starts_with(['\'', '"']))
            });
            let moment = self.moments.iter().any(|(m, choices)| {
                !choices.is_empty() && m.value("location") == Some(room.name.as_str())
            });
            let things = self
                .thing_choices
                .iter()
                .any(|(thing, _)| thing.value("location") == Some(room.name.as_str()));
            if !exits && !moment && !things {
                out.push(format!(
                    "{}: in a choice game, a room with no exits and no choices: a player who \
                     reaches it has nothing to choose, unless the game ends there (an exit \
                     that is code is not seen)",
                    room.name
                ));
            }
        }
        out
    }

    /// Whether a moment is a room's (the choices extension's
    /// `RoomMoment`).
    fn is_room_moment(&self, moment: &DocObject) -> bool {
        self.is_a(moment, "RoomMoment")
    }

    /// Whether an object is built on a class, however far up.
    fn is_a(&self, object: &DocObject, class: &str) -> bool {
        let mut todo: Vec<&str> = object.superclasses.iter().map(String::as_str).collect();
        let mut seen = HashSet::new();
        while let Some(name) = todo.pop() {
            if name == class {
                return true;
            }
            if seen.insert(name)
                && let Some(parent) = self.by_name.get(name)
            {
                todo.extend(parent.superclasses.iter().map(String::as_str));
            }
        }
        false
    }

    /// Whether the game's code names a moment, as it does to begin it
    /// (`plankSnaps.begin()`): anywhere in a source but its own
    /// definition, a choice's `->`, and comments.
    fn named_in_code(&self, moment: &DocObject) -> bool {
        self.documented.files.iter().any(|file| {
            file.lines.iter().enumerate().any(|(i, line)| {
                let trimmed = line.trim_start();
                if trimmed.starts_with("//")
                    || trimmed.starts_with('*')
                    || trimmed.starts_with("/*")
                    || trimmed.starts_with(&format!("{}:", moment.name))
                    || (file.name == moment.place.file && i + 1 == moment.place.line as usize)
                {
                    return false;
                }
                has_name(line, &moment.name) && !line.contains(&format!("->{}", moment.name))
            })
        })
    }

    /// The choice moments, as a map: each with its choices, where each
    /// leads, what it asks to be in the list, and what leads to each
    /// moment.
    fn choices_index(&self, title: &str) -> String {
        let mut body = String::from(
            "<h1>Choices</h1>\n<p class=\"lede\">The game's choice moments, each with its \
             choices, where each leads, and what leads to it: a map of its choices, read \
             without playing them.</p>\n",
        );
        let problems = self.choice_problems();
        if !problems.is_empty() {
            body.push_str("<h2>Problems</h2>\n<ul>\n");
            for problem in &problems {
                let _ = writeln!(body, "<li>{}</li>", html(problem));
            }
            body.push_str("</ul>\n");
        }
        // What leads to each moment: each choice, by its moment and label.
        let mut led_from: HashMap<&str, Vec<String>> = HashMap::new();
        for (moment, choices) in &self.moments {
            for choice in choices {
                if let Some(to) = choice.value("leadsTo").filter(|v| *v != "nil") {
                    led_from.entry(to).or_default().push(format!(
                        "<a href=\"#{}\">{}</a>: {}",
                        attr(&moment.name),
                        html(&moment.name),
                        html(&label_of(choice))
                    ));
                }
            }
        }
        for (moment, choices) in &self.moments {
            let _ = writeln!(
                body,
                "<div class=\"moment\" id=\"{}\">\n<h2>{}</h2>\n<p class=\"where\">{}</p>",
                attr(&moment.name),
                self.link(&moment.name, true),
                self.place(&moment.place, "")
            );
            let about = summary(&moment.comment);
            if !about.is_empty() {
                let _ = writeln!(body, "<p>{}</p>", html(&about));
            }
            let mut notes = Vec::new();
            let room_note;
            if self.is_room_moment(moment) {
                room_note = format!(
                    "the moment of {}, with its exits as choices after these",
                    moment.value("location").unwrap_or("its room")
                );
                notes.push(room_note.as_str());
            }
            if moment.value("allowCommands") == Some("true") {
                notes.push("a command ends it");
            }
            if moment.value("takesTurn") == Some("nil") {
                notes.push("choosing takes no turn");
            }
            if !notes.is_empty() {
                let _ = writeln!(body, "<p class=\"from\">In it, {}.</p>", notes.join("; "));
            }
            let from = led_from.get(moment.name.as_str());
            let begun = if self.is_room_moment(moment) {
                "being there begins it."
            } else {
                "nothing here; the game's code begins it."
            };
            let _ = writeln!(
                body,
                "<p class=\"from\">Led to from: {}</p>",
                from.map_or_else(|| begun.to_owned(), |f| format!("{}.", f.join("; ")))
            );
            if choices.is_empty() {
                body.push_str("<p>It has no choices.</p>\n</div>\n");
                continue;
            }
            body.push_str(
                "<table class=\"messages\">\n<tr><th>Choice</th><th>Leads to</th>\
                 <th>When</th><th>Where</th></tr>\n",
            );
            for choice in choices {
                let command = self.is_a(choice, "ActionChoice").then(|| {
                    ["action", "dobj", "iobj"]
                        .iter()
                        .filter_map(|p| choice.value(p))
                        .collect::<Vec<_>>()
                        .join(" ")
                });
                let leads = match choice.value("leadsTo") {
                    _ if command.is_some() => format!(
                        "<span class=\"from\">the command</span> <code>{}</code>",
                        html(command.as_deref().unwrap_or_default())
                    ),
                    Some("nil") => "<span class=\"from\">ends the moment</span>".to_owned(),
                    Some(to) if self.moments.iter().any(|(m, _)| m.name == to) => {
                        format!("<a href=\"#{}\">{}</a>", attr(to), html(to))
                    }
                    Some(to) => self.link(to, true),
                    None => "<span class=\"from\">back to this moment</span>".to_owned(),
                };
                let mut when: Vec<String> = Vec::new();
                if let Some(m) = choice.members.iter().find(|m| m.name == "isAvailable") {
                    when.push(format!("<code>{}</code>", html(&m.declaration)));
                }
                if command.is_some() {
                    when.push(
                        "<span class=\"from\">while the command would be allowed</span>".to_owned(),
                    );
                } else if choice.value("isOnce") == Some("nil") {
                    when.push("<span class=\"from\">as often as chosen</span>".to_owned());
                }
                let _ = writeln!(
                    body,
                    "<tr><td>{}</td><td>{leads}</td><td>{}</td><td>{}</td></tr>",
                    html(&label_of(choice)),
                    when.join("<br>"),
                    self.place(&choice.place, "")
                );
            }
            body.push_str("</table>\n</div>\n");
        }
        if !self.thing_choices.is_empty() {
            body.push_str(
                "<h2>Things' choices</h2>
<p>Listed by a room's moment, after its own,                  where the thing can be acted on.</p>
<table class=\"messages\">
                 <tr><th>Thing</th><th>Choice</th><th>Does</th><th>Where</th></tr>
",
            );
            for (thing, choices) in &self.thing_choices {
                for choice in choices {
                    let does = if self.is_a(choice, "ActionChoice") {
                        let mut words: Vec<&str> = choice.value("action").into_iter().collect();
                        words.push(choice.value("dobj").unwrap_or(thing.name.as_str()));
                        words.extend(choice.value("iobj"));
                        format!(
                            "<span class=\"from\">the command</span> <code>{}</code>",
                            html(&words.join(" "))
                        )
                    } else {
                        String::new()
                    };
                    let _ = writeln!(
                        body,
                        "<tr><td>{}</td><td>{}</td><td>{does}</td><td>{}</td></tr>",
                        self.link(&thing.name, true),
                        html(&label_of(choice)),
                        self.place(&choice.place, "")
                    );
                }
            }
            body.push_str(
                "</table>
",
            );
        }
        self.page(&format!("Choices: {title}"), "", &body)
    }

    /// The extensions: the sources in a library's folder `extensions`,
    /// each with what its first comment says and what it defines.
    fn extensions_index(&self, title: &str) -> String {
        let mut body = String::from("<h1>Extensions</h1>\n");
        let extensions: Vec<_> = self
            .documented
            .files
            .iter()
            .filter(|f| f.from_library && extension_name(&f.name).is_some())
            .collect();
        let lede = if self.game {
            "The extensions of its libraries the game is built with: sources a game adds by \
             naming them in its manifest, after its library's name."
        } else {
            "The library's extensions: sources a game adds by naming them in its manifest, \
             as <code>libraries = [{ name = \"hexad\", include = [\"extensions/rules\"] }]</code> \
             adds the rules extension."
        };
        let _ = writeln!(body, "<p class=\"lede\">{lede}</p>");
        if extensions.is_empty() {
            body.push_str("<p>The game is built with none.</p>\n");
            return self.page(&format!("Extensions: {title}"), "", &body);
        }
        body.push_str("<dl class=\"index\">\n");
        for file in extensions {
            let name = extension_name(&file.name).unwrap_or_default();
            let mut defined: Vec<&str> = self
                .documented
                .objects
                .iter()
                .filter(|o| o.place.file == file.name)
                .map(|o| o.name.as_str())
                .collect();
            defined.sort_by_key(|n| n.to_lowercase());
            let links: Vec<String> = defined.iter().map(|n| self.link(n, true)).collect();
            let about = summary(&file_comment(&file.lines));
            let mut what = html(&about);
            if !links.is_empty() {
                if !what.is_empty() {
                    what.push(' ');
                }
                let _ = write!(what, "Defines {}.", links.join(", "));
            }
            let _ = writeln!(
                body,
                "<dt><a href=\"files/{}\"><code>{}</code></a></dt><dd>{what}</dd>",
                attr(&self.file_pages[&file.name]),
                html(&name)
            );
        }
        body.push_str("</dl>\n");
        self.page(&format!("Extensions: {title}"), "", &body)
    }

    /// The macros, and the enumerations.
    fn macros_index(&self, title: &str) -> String {
        let mut macros: Vec<_> = self.documented.macros.iter().collect();
        macros.sort_by_key(|m| (m.name.to_lowercase(), m.name.clone()));
        let mut body = String::from(
            "<h1>Macros and enumerations</h1>\n<p class=\"lede\">The macros the sources \
             define, and the values of their enumerations.</p>\n<h2>Macros</h2>\n",
        );
        let mut seen: HashSet<&str> = HashSet::new();
        for m in macros {
            // A macro defined in several places, as a header's guard or
            // for each language, has its anchor at the first.
            let id = if seen.insert(m.name.as_str()) {
                format!(" id=\"{}\"", attr(&m.name))
            } else {
                String::new()
            };
            let _ = write!(
                body,
                "<div class=\"member\"{id}>\n<h3><code>{}{}</code></h3>\n\
                 <p class=\"where\">{}</p>\n<p><code>{}</code></p>\n{}</div>\n",
                html(&m.name),
                html(&m.params),
                self.place(&m.place, ""),
                html(&m.expansion),
                paragraphs(&m.comment)
            );
        }
        body.push_str("<h2>Enumerations</h2>\n");
        for e in &self.documented.enums {
            let ids: String = e
                .names
                .iter()
                .map(|n| format!("<code id=\"e-{}\">{}</code>", attr(n), html(n)))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = write!(
                body,
                "<div class=\"member\">\n<p>{}{ids}</p>\n<p class=\"where\">{}</p>\n{}</div>\n",
                if e.is_token { "Kinds of token: " } else { "" },
                self.place(&e.place, ""),
                paragraphs(&e.comment)
            );
        }
        self.page(&format!("Macros: {title}"), "", &body)
    }

    /// The search page: a box, and what matches it, from the index.
    fn search_page(&self, title: &str) -> String {
        let body = "<h1>Search</h1>\n<p><input id=\"query\" type=\"search\" \
                    placeholder=\"A name: Thing, isLit, dobj Take, cannot take\" \
                    autofocus></p>\n<p id=\"count\" class=\"where\"></p>\n\
                    <ul id=\"results\" class=\"results\"></ul>\n\
                    <script src=\"search-index.js\"></script>\n<script src=\"search.js\"></script>\n";
        self.page(&format!("Search: {title}"), "", body)
    }

    /// The index the search page searches: every name, its kind, what
    /// it is part of, and its page, as a script that sets `SEARCH`.
    fn search_index(&self) -> String {
        let mut entries: Vec<[String; 4]> = Vec::new();
        for object in &self.documented.objects {
            let page = format!("objects/{}", self.pages[&object.name]);
            entries.push([
                object.name.clone(),
                if object.is_class { "class" } else { "object" }.to_owned(),
                summary(&object.comment),
                page.clone(),
            ]);
            for member in &object.members {
                let kind = match Kind::of(member) {
                    Kind::Property => "property",
                    Kind::Method => "method",
                    Kind::Handler => "handler",
                };
                entries.push([
                    member.name.clone(),
                    kind.to_owned(),
                    object.name.clone(),
                    format!("{page}#{}", anchor(&member.name)),
                ]);
            }
        }
        for function in &self.documented.functions {
            entries.push([
                function.name.clone(),
                "function".to_owned(),
                summary(&function.comment),
                format!("functions.html#{}", function.name),
            ]);
        }
        for (n, message) in self.sorted_messages().iter().enumerate() {
            entries.push([
                message.id.clone(),
                "message".to_owned(),
                message.text.chars().take(80).collect(),
                format!("messages.html#m{n}"),
            ]);
        }
        let mut seen: HashSet<&str> = HashSet::new();
        for m in &self.documented.macros {
            if seen.insert(m.name.as_str()) {
                entries.push([
                    m.name.clone(),
                    "macro".to_owned(),
                    summary(&m.comment),
                    format!("macros.html#{}", m.name),
                ]);
            }
        }
        for e in &self.documented.enums {
            for name in &e.names {
                entries.push([
                    name.clone(),
                    "enum".to_owned(),
                    String::new(),
                    format!("macros.html#e-{name}"),
                ]);
            }
        }
        for file in &self.documented.files {
            entries.push([
                shown_file(&file.name),
                "file".to_owned(),
                String::new(),
                format!("files/{}", self.file_pages[&file.name]),
            ]);
        }
        let mut out = String::from("var SEARCH = [\n");
        for entry in entries {
            let fields: Vec<String> = entry.iter().map(|f| js_string(f)).collect();
            let _ = writeln!(out, "[{}],", fields.join(","));
        }
        out.push_str("];\n");
        out
    }

    /// A source file, its lines numbered, each line an anchor.
    fn file_page(&self, title: &str, file: &hexicon_compiler::DocFile) -> String {
        let mut body = String::new();
        let _ = writeln!(
            body,
            "<h1><span class=\"file\">{}</span></h1>\n<p class=\"where\">{} lines, {}.</p>",
            html(&shown_file(&file.name)),
            file.lines.len(),
            if file.from_library {
                "a library's"
            } else {
                "the game's own"
            }
        );
        body.push_str("<pre class=\"source\">");
        for (index, line) in file.lines.iter().enumerate() {
            let n = index + 1;
            let _ = writeln!(
                body,
                "<span class=\"line\" id=\"L{n}\"><a class=\"n\" href=\"#L{n}\">{n}</a>{}</span>",
                html(line)
            );
        }
        body.push_str("</pre>\n");
        self.page(
            &format!("{}: {title}", shown_file(&file.name)),
            "../",
            &body,
        )
    }

    /// A link to an object's page, from a page in `objects/` (or, with
    /// `from_index`, from the index); its name alone if it has none.
    fn link(&self, name: &str, from_index: bool) -> String {
        match self.pages.get(name) {
            Some(page) => {
                let prefix = if from_index { "objects/" } else { "" };
                format!("<a href=\"{prefix}{}\">{}</a>", attr(page), html(name))
            }
            None => html(name),
        }
    }

    fn index(&self, title: &str) -> String {
        let mut objects: Vec<&&DocObject> = self.by_name.values().collect();
        objects.sort_by_key(|o| (o.name.to_lowercase(), o.name.clone()));
        let mut body = String::new();
        let lede = if self.game {
            "The reference: every class and object the game's sources define, its libraries' \
             among them."
        } else {
            "The reference: every class and object the library defines, its extensions' and \
             the libraries' it is built on among them."
        };
        let _ = write!(
            body,
            "<h1>{}</h1>\n<p class=\"lede\">{lede}</p>\n",
            html(title)
        );
        for (heading, classes) in [("Classes", true), ("Objects", false)] {
            let _ = write!(body, "<h2>{heading}</h2>\n<dl class=\"index\">\n");
            for object in objects.iter().filter(|o| o.is_class == classes) {
                let _ = writeln!(
                    body,
                    "<dt>{}</dt><dd>{}</dd>",
                    self.link(&object.name, true),
                    html(&summary(&object.comment))
                );
            }
            body.push_str("</dl>\n");
        }
        self.page(&format!("{title}: reference"), "", &body)
    }

    fn object_page(&self, title: &str, object: &DocObject) -> String {
        let mut body = String::new();
        let kind = if object.is_class { "class" } else { "object" };
        let _ = writeln!(
            body,
            "<p class=\"crumbs\"><a href=\"../index.html\">{}</a></p>",
            html(title)
        );
        let _ = writeln!(
            body,
            "<h1>{} <span class=\"kind\">{kind}</span></h1>",
            html(&object.name)
        );

        // What it is built on.
        let supers: Vec<String> = object
            .superclasses
            .iter()
            .map(|s| self.link(s, false))
            .collect();
        let _ = writeln!(
            body,
            "<p class=\"decl\"><code>{}{}: {}</code></p>",
            if object.is_class { "class " } else { "" },
            html(&object.name),
            if supers.is_empty() {
                "object".to_owned()
            } else {
                supers.join(", ")
            }
        );
        let _ = writeln!(
            body,
            "<p class=\"where\">{}</p>",
            self.where_defined(object)
        );
        body.push_str(&paragraphs(&object.comment));
        let templates: Vec<String> = self
            .documented
            .templates
            .iter()
            .filter(|t| t.class == object.name)
            .map(|t| {
                format!(
                    "<li><code>{}</code> <span class=\"from\">({})</span></li>",
                    html(&t.text),
                    self.place(&t.place, "../")
                )
            })
            .collect();
        if !templates.is_empty() {
            let _ = write!(
                body,
                "<h2>Templates</h2>\n<p>What values written without names stand for, in an \
                 object of the class:</p>\n<ul>\n{}</ul>\n",
                templates.join("\n")
            );
        }

        // Its lineage, and what comes of it.
        let ancestors = self.ancestors(object);
        if !ancestors.is_empty() {
            body.push_str("<h2>Built on</h2>\n<ul class=\"tree\">\n");
            for (depth, name) in &ancestors {
                let _ = writeln!(
                    body,
                    "<li style=\"margin-left: {}em\">{}</li>",
                    *depth as f64 * 1.5,
                    self.link(name, false)
                );
            }
            body.push_str("</ul>\n");
        }
        if let Some(kids) = self.children.get(object.name.as_str()) {
            body.push_str("<h2>Built on it</h2>\n");
            for (label, classes) in [("Classes", true), ("Objects", false)] {
                let links: Vec<String> = kids
                    .iter()
                    .filter(|k| self.by_name.get(**k).is_some_and(|o| o.is_class == classes))
                    .map(|k| self.link(k, false))
                    .collect();
                if !links.is_empty() {
                    let _ = writeln!(
                        body,
                        "<p class=\"kids\"><span class=\"from\">{label}:</span> {}</p>",
                        links.join(", ")
                    );
                }
            }
        }

        // Its own.
        for (heading, kind) in [
            ("Properties", Kind::Property),
            ("Methods", Kind::Method),
            ("Handlers", Kind::Handler),
        ] {
            let mut members: Vec<_> = object
                .members
                .iter()
                .filter(|m| Kind::of(m) == kind)
                .collect();
            if members.is_empty() {
                continue;
            }
            members.sort_by_key(|m| m.name.to_lowercase());
            let _ = writeln!(body, "<h2>{heading}</h2>");
            for member in members {
                body.push_str(&self.member(member));
            }
        }

        // The messages written in it.
        if let Some(own) = self.messages_of.get(object.name.as_str()) {
            let mut own: Vec<&hexicon_compiler::DocMessage> =
                own.iter().map(|&n| &self.documented.messages[n]).collect();
            own.sort_by_key(|m| (m.id.to_lowercase(), m.place.line));
            let _ = write!(
                body,
                "<h2>Messages</h2>\n<p>The messages it shows by an id, which a game can give \
                 text of its own for:</p>\n<table class=\"messages\">\n<tr><th>Id</th>\
                 <th>Text</th><th>In</th><th>Where</th></tr>\n"
            );
            for message in own {
                let member = self
                    .owner_of(message)
                    .and_then(|(_, member)| member)
                    .map_or_else(String::new, |m| {
                        format!(
                            "<a href=\"#{}\"><code>{}</code></a>",
                            attr(&anchor(m)),
                            html(m)
                        )
                    });
                let _ = writeln!(
                    body,
                    "<tr><td><code>{}</code></td><td>{}</td><td>{member}</td><td>{}</td></tr>",
                    html(&message.id),
                    message_text(message),
                    self.place(&message.place, "../")
                );
            }
            body.push_str("</table>\n");
        }

        // What it inherits, from where: properties and methods, and
        // handlers, apart.
        let mut seen: HashSet<&str> = object.members.iter().map(|m| m.name.as_str()).collect();
        let mut inherited = String::new();
        for (_, name) in &ancestors {
            let Some(ancestor) = self.by_name.get(name.as_str()) else {
                continue;
            };
            let page = &self.pages[&ancestor.name];
            // A class's page has them in full, each class's apart and
            // closed until opened; an object's, by name.
            if object.is_class {
                let mut members: Vec<_> = ancestor
                    .members
                    .iter()
                    .filter(|m| seen.insert(m.name.as_str()))
                    .collect();
                if members.is_empty() {
                    continue;
                }
                members.sort_by_key(|m| (Kind::of(m) == Kind::Handler, m.name.to_lowercase()));
                let _ = writeln!(
                    inherited,
                    "<details class=\"inherited\">\n<summary>From {} <span class=\"from\">({} {})</span></summary>",
                    self.link(&ancestor.name, false),
                    members.len(),
                    if members.len() == 1 {
                        "member"
                    } else {
                        "members"
                    }
                );
                for member in members {
                    inherited.push_str(&self.member(member));
                }
                inherited.push_str("</details>\n");
                continue;
            }
            let mut lines: Vec<String> = Vec::new();
            for handlers in [false, true] {
                let mut names: Vec<&str> = ancestor
                    .members
                    .iter()
                    .filter(|m| (Kind::of(m) == Kind::Handler) == handlers)
                    .map(|m| m.name.as_str())
                    .filter(|n| seen.insert(n))
                    .collect();
                if names.is_empty() {
                    continue;
                }
                names.sort_by_key(|n| n.to_lowercase());
                let links: Vec<String> = names
                    .iter()
                    .map(|n| {
                        format!(
                            "<a href=\"{}#{}\">{}</a>",
                            attr(page),
                            attr(&anchor(n)),
                            html(n)
                        )
                    })
                    .collect();
                lines.push(format!(
                    "<span class=\"from\">{}</span> {}",
                    if handlers {
                        "Handlers:"
                    } else {
                        "Properties and methods:"
                    },
                    links.join(", ")
                ));
            }
            if lines.is_empty() {
                continue;
            }
            let _ = writeln!(
                inherited,
                "<h3>From {}</h3>\n<p class=\"inherited\">{}</p>",
                self.link(&ancestor.name, false),
                lines.join("<br>\n")
            );
        }
        if !inherited.is_empty() {
            body.push_str("<h2>Inherited</h2>\n");
            body.push_str(&inherited);
        }
        self.page(&format!("{}: {title}", object.name), "../", &body)
    }

    /// Whose a message is, the object and the member.
    fn owner_of(
        &self,
        message: &hexicon_compiler::DocMessage,
    ) -> Option<(&'a str, Option<&'a str>)> {
        let at = self
            .documented
            .messages
            .iter()
            .position(|m| std::ptr::eq(m, message))?;
        self.owners[at]
    }

    /// A link to the object a message is written in, and to its member,
    /// from a page at the top with `objects/`, or from one in it with
    /// `""`; nothing if it is in none (a function, the grammar).
    fn owner_link(&self, message: &hexicon_compiler::DocMessage, prefix: &str) -> String {
        let Some((object, member)) = self.owner_of(message) else {
            return String::new();
        };
        let Some(page) = self.pages.get(object) else {
            return html(object);
        };
        match member {
            Some(member) => format!(
                "<a href=\"{prefix}{}#{}\">{}.{}</a>",
                attr(page),
                attr(&anchor(member)),
                html(object),
                html(member)
            ),
            None => format!("<a href=\"{prefix}{}\">{}</a>", attr(page), html(object)),
        }
    }

    /// A member, in full: its declaration, where it is defined, its
    /// stages if it is a handler, and its comment; an anchor of its name.
    fn member(&self, member: &hexicon_compiler::DocMember) -> String {
        let stages = if member.stages.is_empty() {
            String::new()
        } else {
            format!(
                "<p class=\"stages\">Stages: {}</p>\n",
                html(&member.stages.join(", "))
            )
        };
        format!(
            "<div class=\"member\" id=\"{}\">\n<h3><code>{}</code></h3>\n\
             <p class=\"where\">{}</p>\n{stages}{}</div>\n",
            attr(&anchor(&member.name)),
            html(&member.declaration),
            self.place(&member.place, "../"),
            paragraphs(&member.comment)
        )
    }

    /// What an object is built on, however far up, each once, in the
    /// order its definition looks for what it inherits: the first
    /// superclass and all of its, then the next.
    fn ancestors(&self, object: &DocObject) -> Vec<(usize, String)> {
        let mut out = Vec::new();
        let mut seen = HashSet::new();
        self.walk(object, 0, &mut seen, &mut out);
        out
    }

    fn walk(
        &self,
        object: &DocObject,
        depth: usize,
        seen: &mut HashSet<String>,
        out: &mut Vec<(usize, String)>,
    ) {
        for parent in &object.superclasses {
            if !seen.insert(parent.clone()) {
                continue;
            }
            out.push((depth, parent.clone()));
            if let Some(next) = self.by_name.get(parent.as_str()) {
                self.walk(next, depth + 1, seen, out);
            }
        }
    }
}

/// What kind of member: a property, a method, or a handler.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Property,
    Method,
    Handler,
}

impl Kind {
    fn of(member: &hexicon_compiler::DocMember) -> Self {
        if !member.stages.is_empty() {
            Self::Handler
        } else if member.is_method {
            Self::Method
        } else {
            Self::Property
        }
    }
}

/// A member's anchor on its page: its name, with the space in a
/// handler's (`dobj Take`) made a hyphen.
fn anchor(name: &str) -> String {
    name.replace(' ', "-")
}

/// A file as a reader wants it: a built-in library's as the library names
/// it (`hexad/thing.hxn`); one in the game's folder as the game does; and
/// one in a library folder elsewhere from the library's own folder on.
fn shown_file(file: &str) -> String {
    let file = file.replace('\\', "/");
    if let Some(rest) = file.strip_prefix("<hexicon>/") {
        return rest.to_owned();
    }
    if let Ok(here) = std::env::current_dir() {
        let here = here.to_string_lossy().replace('\\', "/");
        let here = here.trim_end_matches('/');
        if let Some(rest) = file.strip_prefix(&format!("{here}/")) {
            return rest.to_owned();
        }
    }
    match file.rfind("/lib/") {
        Some(at) => file[at + 5..].to_owned(),
        None => file,
    }
}

/// What is wrong with a game's choices, as [`Site::choice_problems`]
/// tells, for `hexicon test`: nothing for a game without the choices
/// extension, or whose sources cannot be read.
pub(crate) fn choice_problems(project_args: &[String]) -> Vec<String> {
    let Ok(project) = read_project(&mut DiskFiles, project_args, &crate::build::default_paths())
    else {
        return Vec::new();
    };
    let has_choices = project.sources.iter().any(|s| {
        let s = s.replace('\\', "/");
        s.ends_with("/extensions/choices.hxn")
    });
    if !has_choices {
        return Vec::new();
    }
    let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
    let documented = document(&mut DiskFiles, &sources, &project.options);
    if !documented.diagnostics.is_empty() {
        return Vec::new();
    }
    Site::new(&documented, true).choice_problems()
}

/// Where what `hexicon test --report` reports on is written, as reading
/// the game's sources finds it.
#[derive(Default)]
pub(crate) struct TestPlaces {
    /// The scenarios and walkthroughs, by their names (`scenarioName`,
    /// `walkthroughName`), and a scenario's steps, in order.
    pub(crate) scenarios: Vec<(String, DocPlace, Vec<DocPlace>)>,
    /// The named objects, by their names in the program.
    pub(crate) objects: HashMap<String, DocPlace>,
    /// The choices, by the name of the moment or thing they are in, and
    /// their labels.
    pub(crate) choices: Vec<(String, String, DocPlace)>,
    /// What is wrong with the game's choices, as [`choice_problems`]
    /// says, each with where the moment or room it is about is written.
    pub(crate) problems: Vec<(String, Option<DocPlace>)>,
}

/// Where a game's scenarios, moments, and choices are written, and what
/// is wrong with its choices; nothing, if its sources could not be read.
pub(crate) fn test_places(project_args: &[String]) -> TestPlaces {
    let Ok(project) = read_project(&mut DiskFiles, project_args, &crate::build::default_paths())
    else {
        return TestPlaces::default();
    };
    let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
    let documented = document(&mut DiskFiles, &sources, &project.options);
    if !documented.diagnostics.is_empty() {
        return TestPlaces::default();
    }
    let site = Site::new(&documented, true);
    let all = || documented.objects.iter().chain(&documented.anonymous);
    let unquoted = |value: &str| {
        let value = value.trim();
        let inner = value
            .strip_prefix('\'')
            .and_then(|v| v.strip_suffix('\''))
            .or_else(|| value.strip_prefix('"').and_then(|v| v.strip_suffix('"')))
            .unwrap_or(value);
        inner.replace("\\'", "'").replace("\\\"", "\"")
    };
    let mut places = TestPlaces::default();
    for object in all().filter(|o| !o.is_class) {
        let name = if site.is_a(object, "Walkthrough") {
            object.value("walkthroughName")
        } else if site.is_a(object, "Scenario") {
            object.value("scenarioName")
        } else {
            None
        };
        if let Some(name) = name {
            // Its steps are the objects in it (`+ Step`), as the game
            // plays them: in the order they are written.
            let mut steps: Vec<DocPlace> = if object.name.is_empty() {
                Vec::new()
            } else {
                all()
                    .filter(|o| {
                        !o.is_class
                            && site.is_a(o, "ScenarioStep")
                            && o.value("location") == Some(object.name.as_str())
                    })
                    .map(|o| o.place.clone())
                    .collect()
            };
            steps.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
            places
                .scenarios
                .push((unquoted(name), object.place.clone(), steps));
        }
    }
    for object in documented.objects.iter().filter(|o| !o.is_class) {
        places
            .objects
            .entry(object.name.clone())
            .or_insert_with(|| object.place.clone());
    }
    for (owner, choices) in site.moments.iter().chain(&site.thing_choices) {
        for choice in choices {
            places
                .choices
                .push((owner.name.clone(), label_of(choice), choice.place.clone()));
        }
    }
    let has_choices = project
        .sources
        .iter()
        .any(|s| s.replace('\\', "/").ends_with("/extensions/choices.hxn"));
    if has_choices {
        places.problems = site
            .choice_problems()
            .into_iter()
            .map(|problem| {
                let place = problem
                    .split_once(':')
                    .and_then(|(name, _)| places.objects.get(name))
                    .cloned();
                (problem, place)
            })
            .collect();
    }
    places
}

/// Whether a line has a name as a whole word.
fn has_name(line: &str, name: &str) -> bool {
    let is_word = |c: char| c.is_alphanumeric() || c == '_';
    line.match_indices(name).any(|(at, _)| {
        !line[..at].chars().next_back().is_some_and(is_word)
            && !line[at + name.len()..].chars().next().is_some_and(is_word)
    })
}

/// A choice's label, as its list shows it.
fn label_of(choice: &DocObject) -> String {
    choice
        .value("label")
        .map(|l| l.trim_matches('\'').to_owned())
        .unwrap_or_default()
}

/// A message's text, or that the code makes it.
fn message_text(message: &hexicon_compiler::DocMessage) -> String {
    if message.text.is_empty() {
        "<span class=\"from\">(made by the code)</span>".to_owned()
    } else {
        html(&message.text)
    }
}

/// Whose what is at a place is: the object whose definition, or `modify`,
/// the place is in, and its member that starts nearest above it there;
/// none if it is in something else (a function, a rule of the grammar, a
/// debugging action a build not for debugging leaves out).
///
/// A definition is told by its text: it starts at the line above that
/// begins at the margin with a name or a `+`, as its members, and
/// what is in them, do not. An object's place may be a line or two
/// into its definition (a `modify`'s is its first member's), so each is
/// taken back to the start of the definition it is in.
fn owner<'a>(documented: &'a Documented, at: &DocPlace) -> Option<(&'a str, Option<&'a str>)> {
    let lines = &documented.files.iter().find(|f| f.name == at.file)?.lines;
    let start_of = |line: u32| {
        (1..=line).rev().find(|&n| {
            lines
                .get(n as usize - 1)
                .and_then(|l| l.chars().next())
                .is_some_and(|c| c.is_alphabetic() || c == '+' || c == '_')
        })
    };
    let start = start_of(at.line)?;
    let object = documented.objects.iter().find(|object| {
        std::iter::once(&object.place)
            .chain(&object.modified_in)
            .any(|p| p.file == at.file && start_of(p.line) == Some(start))
    })?;
    let member = object
        .members
        .iter()
        .filter(|m| m.place.file == at.file && m.place.line >= start && m.place.line <= at.line)
        .max_by_key(|m| m.place.line)
        .map(|m| m.name.as_str());
    Some((object.name.as_str(), member))
}

/// An extension's name as a manifest includes it (`extensions/rules`),
/// for a source in a library's folder `extensions`.
fn extension_name(file: &str) -> Option<String> {
    let shown = shown_file(file);
    let at = shown.find("extensions/")?;
    if at > 0 && !shown[..at].ends_with('/') {
        return None;
    }
    let name = &shown[at..];
    Some(name.strip_suffix(".hxn").unwrap_or(name).to_owned())
}

/// What a source's first comment of more than one line says, its title
/// and version lines left out (`RULES EXTENSION`, `Version 1.0`).
fn file_comment(lines: &[String]) -> String {
    let mut text: Vec<String> = Vec::new();
    let mut inside = false;
    let mut title = String::new();
    for line in lines.iter().take(60) {
        let trimmed = line.trim();
        if !inside {
            // A comment of one line (`/* include the library header */`)
            // is not what the file is about.
            if trimmed.starts_with("/*") && !trimmed.contains("*/") {
                inside = true;
            }
            continue;
        }
        if trimmed.starts_with("*/") || trimmed.ends_with("*/") && !trimmed.starts_with('*') {
            break;
        }
        // The line's words, after the comment's margin of stars, and any
        // row of stars or dashes before them.
        let words = trimmed
            .trim_start_matches(['*', '.', '-', ' ', '\t'])
            .trim();
        let lower = words.to_lowercase();
        let count = words.split_whitespace().count();
        let sentence = words.ends_with('.');
        let is_title = (lower.contains("extension") && count <= 6 && !sentence)
            || (lower.contains("version") && count <= 6 && !sentence)
            || (lower.ends_with("module") && count <= 4)
            || lower.starts_with("revised:")
            || lower.starts_with("hexad - ")
            // A file's own name (`thoughtsuggs.hxn`).
            || (count == 1 && (lower.ends_with(".hxn") || lower.ends_with(".t")));
        // A line of nothing but stars is a margin, not a paragraph's end.
        if words.is_empty()
            && trimmed.trim_matches(['*', '-', '.', ' ']).is_empty()
            && trimmed.len() > 2
        {
            continue;
        }
        if is_title {
            if title.is_empty() && lower.contains("extension") {
                title = words.to_owned();
            }
            continue;
        }
        text.push(words.to_owned());
    }
    let joined: Vec<String> = text
        .split(String::is_empty)
        .filter(|p| !p.is_empty())
        .map(|p| p.join(" "))
        .collect();
    if joined.is_empty() {
        title
    } else {
        joined.join("\n\n")
    }
}

/// A comment's paragraphs, as HTML.
fn paragraphs(comment: &str) -> String {
    comment
        .split("\n\n")
        .filter(|p| !p.trim().is_empty())
        .map(|p| format!("<p>{}</p>\n", html(p)))
        .collect()
}

/// A comment's first sentence, for the index.
fn summary(comment: &str) -> String {
    let first = comment.split("\n\n").next().unwrap_or_default();
    let end = first
        .match_indices(". ")
        .map(|(at, _)| at + 1)
        .next()
        .unwrap_or(first.len());
    let mut text: String = first[..end].to_owned();
    if text.chars().count() > 200 {
        text = text.chars().take(197).collect::<String>() + "...";
    }
    text
}

/// A whole page.
/// `choices` says the reference has a page of its choice moments.
fn page(title: &str, root: &str, body: &str, choices: bool) -> String {
    let choices = if choices {
        format!("<a href=\"{root}choices.html\">Choices</a> ")
    } else {
        String::new()
    };
    format!(
        "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
         <title>{}</title>\n<link rel=\"stylesheet\" href=\"{root}reference.css\">\n\
         </head>\n<body>\n<nav class=\"bar\"><a href=\"{root}index.html\">Classes and \
         objects</a> <a href=\"{root}files.html\">Files</a> <a href=\"{root}extensions.html\">\
         Extensions</a> <a href=\"{root}functions.html\">\
         Functions</a> <a href=\"{root}actions.html\">Actions</a> <a \
         href=\"{root}messages.html\">Messages</a> <a href=\"{root}macros.html\">Macros</a> {choices}\
         <form class=\"search\" action=\"{root}search.html\"><input name=\"q\" \
         type=\"search\" placeholder=\"Search\" aria-label=\"Search\"></form></nav>\n\
         <main>\n{body}</main>\n</body>\n</html>\n",
        html(title)
    )
}

/// A string as JavaScript writes one, in double quotes.
fn js_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '<' => out.push_str("\\u003c"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Text made safe for HTML.
fn html(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(c),
        }
    }
    out
}

/// Text made safe for an attribute, or a link's address.
fn attr(text: &str) -> String {
    html(text).replace(' ', "%20")
}

#[cfg(test)]
mod tests {
    use super::{Site, extension_name, file_comment, library_reference};

    #[test]
    fn a_library_is_documented_with_its_extensions_and_no_game() {
        let (title, documented) =
            library_reference("hexad", &[], &[], "").unwrap_or_else(|_| panic!("no reference"));
        assert_eq!(title, "Hexad");
        assert!(
            documented.diagnostics.is_empty(),
            "{:?}",
            documented.diagnostics
        );
        let names: Vec<&str> = documented.objects.iter().map(|o| o.name.as_str()).collect();
        // Hexad's, an extension's, and the system library's.
        for name in ["Thing", "RuleBook", "Exception"] {
            assert!(names.contains(&name), "{name}");
        }
        // Everything is a library's: the source a game must have is left out.
        assert!(documented.files.iter().all(|f| f.from_library));
        assert!(
            !documented
                .files
                .iter()
                .any(|f| f.name.contains("<hexicon doc>"))
        );
        let site = Site::new(&documented, false);
        let extensions = site.extensions_index(&title);
        assert!(extensions.contains("<code>extensions/rules</code>"));
        assert!(
            site.index(&title)
                .contains("every class and object the library defines")
        );
    }

    #[test]
    fn a_class_has_what_it_inherits_in_full_and_an_object_by_name() {
        use hexicon_compiler::{DocMember, DocObject, DocPlace};
        let place = |line| DocPlace {
            file: "lib.hxn".to_owned(),
            line,
        };
        let member = |name: &str, comment: &str, line| DocMember {
            name: name.to_owned(),
            declaration: format!("{name} = nil"),
            comment: comment.to_owned(),
            place: place(line),
            is_method: false,
            stages: Vec::new(),
        };
        let object = |name: &str, is_class, superclasses: &[&str], members| DocObject {
            name: name.to_owned(),
            is_class,
            superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
            place: place(1),
            comment: String::new(),
            modified_in: Vec::new(),
            members,
            from_library: true,
            values: Vec::new(),
        };
        let documented = hexicon_compiler::Documented {
            objects: vec![
                object(
                    "Base",
                    true,
                    &[],
                    vec![
                        member("isLit", "Whether it gives light.", 2),
                        member("weight", "How heavy it is.", 3),
                    ],
                ),
                // Its own weight takes the place of Base's.
                object(
                    "Lamp",
                    true,
                    &["Base"],
                    vec![member("weight", "A lamp's.", 9)],
                ),
                object("lamp", false, &["Lamp"], Vec::new()),
            ],
            ..Default::default()
        };
        let site = Site::new(&documented, true);
        let class = site.object_page("A game", &documented.objects[1]);
        assert!(class.contains("<details class=\"inherited\">"));
        assert!(class.contains("(1 member)"));
        assert!(class.contains("Whether it gives light."));
        // What it defines itself is not inherited.
        assert!(!class.contains("How heavy it is."));
        let instance = site.object_page("A game", &documented.objects[2]);
        assert!(!instance.contains("<details"));
        assert!(!instance.contains("Whether it gives light."));
        assert!(instance.contains("Base.html#isLit"));
    }

    #[test]
    fn a_message_is_on_the_page_of_the_object_it_is_written_in() {
        use hexicon_compiler::{DocFile, DocMember, DocMessage, DocObject, DocPlace};
        let text = [
            "class Lamp: object",                                   // 1
            "    lit = nil",                                        // 2
            "    dimMsg = msgText(lamp dim, 'The lamp dims. ')",    // 3
            ";",                                                    // 4
            "modify Lamp",                                          // 5
            "    // A comment, at the members' margin.",            // 6
            "    brightMsg = msgText(lamp bright, 'It shines. ')",  // 7
            ";",                                                    // 8
            "lampHelp()",                                           // 9
            "{",                                                    // 10
            "    showMsg(lamp help, 'Rub it. ');",                  // 11
            "}",                                                    // 12
            "action Polish: IAction",                               // 13
            "    execAction(cmd) { showMsg(polished, 'Done. '); }", // 14
            ";",                                                    // 15
        ];
        let place = |line| DocPlace {
            file: "lamp.hxn".to_owned(),
            line,
        };
        let member = |name: &str, line| DocMember {
            name: name.to_owned(),
            declaration: name.to_owned(),
            comment: String::new(),
            place: place(line),
            is_method: false,
            stages: Vec::new(),
        };
        let message = |id: &str, line| DocMessage {
            id: id.to_owned(),
            text: "text".to_owned(),
            place: place(line),
        };
        let documented = hexicon_compiler::Documented {
            // Polish is left out, as a debugging action is from a build
            // not for debugging; the modify's place is its first member's.
            objects: vec![DocObject {
                name: "Lamp".to_owned(),
                is_class: true,
                superclasses: Vec::new(),
                place: place(1),
                comment: String::new(),
                modified_in: vec![place(7)],
                members: vec![
                    member("lit", 2),
                    member("dimMsg", 3),
                    member("brightMsg", 7),
                ],
                from_library: true,
                values: Vec::new(),
            }],
            messages: vec![
                message("lamp dim", 3),
                message("lamp bright", 7),
                message("lamp help", 11),
                message("polished", 14),
            ],
            files: vec![DocFile {
                name: "lamp.hxn".to_owned(),
                lines: text.iter().map(|s| (*s).to_owned()).collect(),
                from_library: true,
            }],
            ..Default::default()
        };
        let owners: Vec<_> = documented
            .messages
            .iter()
            .map(|m| super::owner(&documented, &m.place))
            .collect();
        assert_eq!(
            owners,
            [
                Some(("Lamp", Some("dimMsg"))),
                Some(("Lamp", Some("brightMsg"))),
                None,
                None
            ]
        );
        let site = Site::new(&documented, true);
        let page = site.object_page("A game", &documented.objects[0]);
        assert!(page.contains("<h2>Messages</h2>"));
        assert!(page.contains("<code>lamp bright</code>"));
        assert!(page.contains("href=\"#brightMsg\""));
        assert!(!page.contains("lamp help"));
        let index = site.messages_index("A game");
        assert!(index.contains("objects/Lamp.html#dimMsg\">Lamp.dimMsg</a>"));
    }

    #[test]
    fn what_is_wrong_with_the_choices_is_found_by_reading_them() {
        use hexicon_compiler::{DocFile, DocObject, DocPlace};
        let object = |name: &str, superclasses: &[&str], line, values: &[(&str, &str)]| DocObject {
            name: name.to_owned(),
            is_class: matches!(name, "ChoiceMoment" | "Choice" | "RoomMoment"),
            superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
            place: DocPlace {
                file: "game.hxn".to_owned(),
                line,
            },
            comment: String::new(),
            modified_in: Vec::new(),
            members: Vec::new(),
            from_library: false,
            values: values
                .iter()
                .map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
                .collect(),
        };
        let lines = [
            "snap: ChoiceMoment",            // 1
            "+ Choice 'Grab it' ->sway;",    // 2
            "sway: ChoiceMoment",            // 3
            "+ Choice 'Crawl' ->nil;",       // 4
            "trap: ChoiceMoment",            // 5
            "+ Choice 'Pace' isOnce = nil;", // 6
            "// trap is never begun.",       // 7
            "+ Choice 'Leave' ->hall;",      // 8
            "bell() { snap.begin(); }",      // 9
        ];
        let documented = hexicon_compiler::Documented {
            objects: vec![
                object("ChoiceMoment", &["object"], 1, &[]),
                object("Choice", &["object"], 1, &[]),
                object("snap", &["ChoiceMoment"], 1, &[]),
                object("sway", &["ChoiceMoment"], 3, &[]),
                object("trap", &["ChoiceMoment"], 5, &[]),
                // A room's moment is begun by being there and left by its
                // exits: no choice leads to it, and none of its own ends it.
                object("RoomMoment", &["ChoiceMoment"], 1, &[]),
                object("hallMoment", &["RoomMoment"], 9, &[("location", "hall")]),
            ],
            anonymous: vec![
                object(
                    "",
                    &["Choice"],
                    2,
                    &[
                        ("label", "'Grab it'"),
                        ("leadsTo", "sway"),
                        ("location", "snap"),
                    ],
                ),
                object(
                    "",
                    &["Choice"],
                    4,
                    &[
                        ("label", "'Crawl'"),
                        ("leadsTo", "nil"),
                        ("location", "sway"),
                    ],
                ),
                object(
                    "",
                    &["Choice"],
                    6,
                    &[("label", "'Pace'"), ("isOnce", "nil"), ("location", "trap")],
                ),
                object(
                    "",
                    &["Choice"],
                    8,
                    &[
                        ("label", "'Leave'"),
                        ("leadsTo", "hall"),
                        ("location", "sway"),
                    ],
                ),
            ],
            files: vec![DocFile {
                name: "game.hxn".to_owned(),
                lines: lines.iter().map(|s| (*s).to_owned()).collect(),
                from_library: false,
            }],
            ..Default::default()
        };
        let problems = Site::new(&documented, true).choice_problems();
        assert_eq!(
            problems,
            [
                "sway: the choice \"Leave\" leads to hall, which is no choice moment",
                "trap: no choice leads to it, and the game's code does not name it, so it never \
                 begins",
                "trap: it has no way out: no choice ends it or leads to a moment that ends, and it \
                 allows no commands",
            ]
        );
    }

    #[test]
    fn a_room_with_nothing_to_choose_in_a_choice_game_is_found() {
        use hexicon_compiler::{DocObject, DocPlace};
        let object =
            |name: &str, is_class, superclasses: &[&str], values: &[(&str, &str)]| DocObject {
                name: name.to_owned(),
                is_class,
                superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
                place: DocPlace {
                    file: "game.hxn".to_owned(),
                    line: 1,
                },
                comment: String::new(),
                modified_in: Vec::new(),
                members: Vec::new(),
                from_library: false,
                values: values
                    .iter()
                    .map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
                    .collect(),
            };
        let rooms = |choice_game: &str| hexicon_compiler::Documented {
            objects: vec![
                object("Story", true, &["object"], &[]),
                object("Room", true, &["object"], &[]),
                object("ChoiceMoment", true, &["object"], &[]),
                object("RoomMoment", true, &["ChoiceMoment"], &[]),
                object("Choice", true, &["object"], &[]),
                object("story", false, &["Story"], &[("choiceGame", choice_game)]),
                // Its exit is a door: there is a way on.
                object("hall", false, &["Room"], &[("north", "frontDoor")]),
                // No exit, but a moment of its own with a choice.
                object(
                    "study",
                    false,
                    &["Room"],
                    &[("north", "'The wall is solid.'")],
                ),
                object(
                    "studyMoment",
                    false,
                    &["RoomMoment"],
                    &[("location", "study")],
                ),
                // Nothing.
                object("cellar", false, &["Room"], &[]),
            ],
            anonymous: vec![object(
                "",
                false,
                &["Choice"],
                &[("label", "'Read'"), ("location", "studyMoment")],
            )],
            ..Default::default()
        };
        let found = rooms("true");
        let problems = Site::new(&found, true).choice_problems();
        assert_eq!(problems.len(), 1, "{problems:?}");
        assert!(problems[0].starts_with("cellar: in a choice game, a room with no exits"));
        // In a parser game, a room is left by what is typed.
        let parser = rooms("nil");
        assert!(Site::new(&parser, true).choice_problems().is_empty());
    }

    #[test]
    fn the_choices_page_maps_each_moment_and_where_its_choices_lead() {
        use hexicon_compiler::{DocObject, DocPlace};
        let object =
            |name: &str, is_class, superclasses: &[&str], line, values: &[(&str, &str)]| {
                DocObject {
                    name: name.to_owned(),
                    is_class,
                    superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
                    place: DocPlace {
                        file: "gorge.hxn".to_owned(),
                        line,
                    },
                    comment: String::new(),
                    modified_in: Vec::new(),
                    members: Vec::new(),
                    from_library: !name.is_empty() && is_class,
                    values: values
                        .iter()
                        .map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
                        .collect(),
                }
            };
        let documented = hexicon_compiler::Documented {
            objects: vec![
                object("ChoiceMoment", true, &["object"], 1, &[]),
                object("Choice", true, &["object"], 2, &[]),
                object("snap", false, &["ChoiceMoment"], 10, &[]),
                object(
                    "sway",
                    false,
                    &["ChoiceMoment"],
                    20,
                    &[("allowCommands", "true")],
                ),
                object("ActionChoice", true, &["Choice"], 3, &[]),
                object("lamp", false, &["Thing"], 30, &[]),
            ],
            anonymous: vec![
                // A thing's own choice, done to it.
                object(
                    "",
                    false,
                    &["ActionChoice"],
                    31,
                    &[
                        ("label", "'Light it'"),
                        ("action", "Light"),
                        ("location", "lamp"),
                    ],
                ),
                object(
                    "",
                    false,
                    &["Choice"],
                    11,
                    &[
                        ("label", "'Grab it'"),
                        ("leadsTo", "sway"),
                        ("location", "snap"),
                    ],
                ),
                object(
                    "",
                    false,
                    &["Choice"],
                    12,
                    &[
                        ("label", "'Shout'"),
                        ("isOnce", "nil"),
                        ("location", "snap"),
                    ],
                ),
                object(
                    "",
                    false,
                    &["Choice"],
                    21,
                    &[
                        ("label", "'Crawl on'"),
                        ("leadsTo", "nil"),
                        ("location", "sway"),
                    ],
                ),
            ],
            ..Default::default()
        };
        let site = Site::new(&documented, true);
        let map = site.choices_index("A game");
        // Each moment, with its choices in order, and where each leads.
        assert!(map.contains("id=\"snap\"") && map.contains("id=\"sway\""));
        assert!(map.find("Grab it") < map.find("Shout"));
        assert!(map.contains("<td>Grab it</td><td><a href=\"#sway\">sway</a></td>"));
        assert!(map.contains("<td>Shout</td><td><span class=\"from\">back to this moment</span>"));
        assert!(map.contains("as often as chosen"));
        assert!(map.contains("<td>Crawl on</td><td><span class=\"from\">ends the moment</span>"));
        // What leads to each, and what the game's code begins.
        assert!(map.contains("Led to from: <a href=\"#snap\">snap</a>: Grab it."));
        assert!(map.contains("nothing here; the game's code begins it."));
        assert!(map.contains("a command ends it"));
        // A thing's choices are apart from the moments', with the command.
        assert!(map.contains("<h2>Things' choices</h2>"));
        assert!(map.contains(
            "<td>Light it</td><td><span class=\"from\">the command</span> <code>Light lamp</code>"
        ));
        // Every page's bar has the map, when there is one; not otherwise.
        assert!(site.index("A game").contains("choices.html"));
        let none = hexicon_compiler::Documented::default();
        assert!(
            !Site::new(&none, true)
                .index("A game")
                .contains("choices.html")
        );
    }

    #[test]
    fn an_unknown_library_is_said_to_be_unknown() {
        assert!(library_reference("no-such-library", &[], &[], "").is_err());
    }

    #[test]
    fn an_extension_is_named_as_a_manifest_includes_it() {
        assert_eq!(
            extension_name("<hexicon>/hexad/extensions/rules.hxn").as_deref(),
            Some("extensions/rules")
        );
        assert_eq!(extension_name("<hexicon>/hexad/thing.hxn"), None);
        assert_eq!(extension_name("<hexicon>/hexad/myextensions/x.hxn"), None);
    }

    #[test]
    fn a_files_first_comment_is_what_it_is_about() {
        let lines: Vec<String> = [
            "import hexad;",
            "/* include the library header */",
            "/*",
            " *   ************************ rules.hxn",
            " *   RULES EXTENSION",
            " *.  Version 1.0 23-Apr-24",
            " *",
            " *   Rules and rulebooks, as a",
            " *   game defines them.",
            " *",
            " *   A second paragraph.",
            " */",
            "class RuleBook: object;",
        ]
        .iter()
        .map(|s| (*s).to_owned())
        .collect();
        assert_eq!(
            file_comment(&lines),
            "Rules and rulebooks, as a game defines them.\n\nA second paragraph."
        );
        // A comment that is only a title is its title.
        let lines: Vec<String> = ["/*", " *   COLLECTIVE EXTENSION", " */"]
            .iter()
            .map(|s| (*s).to_owned())
            .collect();
        assert_eq!(file_comment(&lines), "COLLECTIVE EXTENSION");
    }
}