nova-doc 0.3.0

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

use std::collections::{HashMap, HashSet};
use std::path::Path;

use nova_ast::item::{
    ConstDecl, ExternItem, ImplBlock, Record, TraitDecl, TraitItem, TypeDecl, TypeDef, Visibility,
    WhereBound,
};
use nova_ast::{Item as Ast, Type};
use nova_diagnostics::{Diagnostic, FileDb, FileId, Severity, Span, Spanned};
use nova_driver::{analyze_program, Analysis, DiskSources, Options, Program, Roots, Sources};
use nova_lexer::Token;
use nova_pm::PackageId;
use nova_resolver::index::rank;
use nova_resolver::{Builtin, DefKind, Definitions, ModuleId, Role, Target};

use crate::highlight::highlight;
use crate::markdown::{self, Docs};
use crate::signature::{self, FileText};

/// A program documented: its site, and the warnings its analysis found,
/// with the files they point into.
pub struct Documented {
    /// The site, for [`crate::write_site`].
    pub site: Site,
    /// The files the warnings point into.
    pub db: FileDb,
    /// The analysis's warnings, for the caller to print.
    pub warnings: Vec<Diagnostic>,
}

/// Why a program was not documented.
pub enum Failure {
    /// Its analysis found errors, for the caller to print.
    Diagnostics {
        /// The files the diagnostics point into.
        db: FileDb,
        /// Every diagnostic the analysis found, errors among them.
        diagnostics: Vec<Diagnostic>,
    },
    /// Anything else, in a sentence.
    Other(String),
}

/// A site: its packages, std last (spec ยง6.1).
pub struct Site {
    pub(crate) packages: Vec<Package>,
    /// The page `--open` opens, from the site's root.
    pub(crate) start: String,
}

/// A documented package.
pub(crate) struct Package {
    pub name: String,
    pub version: String,
    pub description: Option<String>,
    pub std: bool,
    /// The root module first, then the rest by name; std's all by name.
    pub modules: Vec<Module>,
    /// std's alone.
    pub primitives: Vec<Primitive>,
    /// std's alone.
    pub builtins: Vec<BuiltinDoc>,
}

/// A documented module, one page (spec ยง7.2, ยง7.3).
pub(crate) struct Module {
    pub name: String,
    /// `package`, or `package::module`: its title and its search path.
    pub qual: String,
    /// Its page, from the site's root.
    pub page: String,
    /// Whether it is its package's root module, whose page is the
    /// package's.
    pub root: bool,
    pub docs: Docs,
    /// In source order.
    pub items: Vec<Item>,
    pub other_impls: Vec<Impl>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ItemKind {
    Record,
    Sum,
    Trait,
    Function,
    Constant,
}

impl ItemKind {
    /// The word its heading and the search index show.
    pub fn word(self) -> &'static str {
        match self {
            ItemKind::Record => "record",
            ItemKind::Sum => "type",
            ItemKind::Trait => "trait",
            ItemKind::Function => "fn",
            ItemKind::Constant => "const",
        }
    }

    /// The section a module page lists it under, and that section's `id`.
    pub fn section(self) -> (&'static str, &'static str) {
        match self {
            ItemKind::Record => ("Records", "records"),
            ItemKind::Sum => ("Sum types", "sum-types"),
            ItemKind::Trait => ("Traits", "traits"),
            ItemKind::Function => ("Functions", "functions"),
            ItemKind::Constant => ("Constants", "constants"),
        }
    }
}

/// A documented item (spec ยง7.3).
pub(crate) struct Item {
    pub kind: ItemKind,
    pub name: String,
    pub anchor: String,
    /// Its signature's HTML (spec ยง8).
    pub signature: String,
    pub docs: Docs,
    /// Fields, variants, associated types and methods, as ยง7.3 orders them.
    pub members: Vec<Member>,
    /// Whether it is a record with fields that are not documented.
    pub hidden_fields: bool,
    /// A record's or sum type's impls; a trait's, by their headers.
    pub impls: Vec<Impl>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MemberKind {
    Field,
    Variant,
    AssocType,
    Method,
}

impl MemberKind {
    /// The word the search index shows.
    pub fn word(self) -> &'static str {
        match self {
            MemberKind::Field => "field",
            MemberKind::Variant => "variant",
            MemberKind::AssocType => "type",
            MemberKind::Method => "method",
        }
    }

    /// The heading a page groups them under.
    pub fn heading(self) -> &'static str {
        match self {
            MemberKind::Field => "Fields",
            MemberKind::Variant => "Variants",
            MemberKind::AssocType => "Associated types",
            MemberKind::Method => "Methods",
        }
    }
}

/// A documented member.
pub(crate) struct Member {
    pub kind: MemberKind,
    pub name: String,
    pub anchor: String,
    pub signature: String,
    pub docs: Docs,
}

/// An impl: its header, its docs and its documented methods (spec ยง5.2).
pub(crate) struct Impl {
    pub header: String,
    pub docs: Docs,
    pub methods: Vec<Member>,
    /// The type's name, for the search index's paths.
    pub on: String,
}

/// A primitive type's page (spec ยง7.4).
pub(crate) struct Primitive {
    pub name: &'static str,
    pub page: String,
    pub about: Docs,
    pub impls: Vec<Impl>,
}

/// A builtin function, on std's front page (spec ยง7.4).
pub(crate) struct BuiltinDoc {
    pub name: &'static str,
    pub signature: String,
    pub docs: Docs,
}

/// The primitive types, with what their pages say first (plan decision
/// 19).
const PRIMITIVES: [(&str, &str); 7] = [
    (
        "Int",
        "A 64-bit signed integer. `+`, `-` and `*` on `Int` wrap on overflow.",
    ),
    ("Float", "A 64-bit floating-point number."),
    ("Bool", "`true` or `false`."),
    ("Char", "A Unicode scalar value."),
    ("String", "A string of UTF-8 text."),
    ("Bytes", "A sequence of bytes."),
    (
        "Future",
        "The work an `async fn` call stands for, which `.await` runs to its value.",
    ),
];

/// The builtin functions every module sees, and their docs (plan decision
/// 19).
const BUILTINS: [(&str, &str); 5] = [
    (
        "println",
        "Writes its argument and a line break to standard output.",
    ),
    (
        "print",
        "Writes its argument to standard output, with no line break.",
    ),
    (
        "eprintln",
        "Writes its argument and a line break to standard error.",
    ),
    (
        "eprint",
        "Writes its argument to standard error, with no line break.",
    ),
    (
        "panic",
        "Stops the program at once: writes `nova: panic: ` and its argument to standard \
         error, and aborts. Under `nova test`, a test marked `@test(should_panic)` expects it.",
    ),
];

/// What std's front page says first.
const STD_ABOUT: &str = "Nova's standard library, which every module sees without an import.";

/// The entry of std's own analysis, which no file holds (plan decision
/// 8).
const STD_ENTRY: &str = "<nova doc>/main.nova";

/// Document the package whose `nova.toml` is in `root` (empty for the
/// current directory), its dependencies and std (spec ยง5.1).
pub fn document_package(root: &Path) -> Result<Documented, Failure> {
    let (analysis, library) = package_analysis(root, false)?;
    let std = std_analysis()?;
    let mut packages = Ctx::new(&analysis, false, !library)?.packages();
    packages.push(Ctx::new(&std, true, false)?.std_package());
    clash(&packages)?;
    let start = format!("{}/index.html", packages[0].name);
    let warnings = analysis.diagnostics.clone();
    Ok(Documented {
        site: Site { packages, start },
        db: analysis.db,
        warnings,
    })
}

/// A library's own package, as its site documents it, and the analysis it
/// came from; `None` for a package with no library (3.5b spec ยง4.1). The
/// analysis is a test build's, as `nova test` reads the library (3.5b
/// spec ยง6.1).
pub(crate) fn library_package(root: &Path) -> Result<Option<(Package, Analysis)>, Failure> {
    let (analysis, library) = package_analysis(root, true)?;
    if !library {
        return Ok(None);
    }
    let packages = Ctx::new(&analysis, false, false)?.packages();
    let name = analysis.graph.as_ref().map(|g| g.root().name.clone());
    let package = packages
        .into_iter()
        .find(|p| Some(&p.name) == name.as_ref());
    Ok(package.map(|p| (p, analysis)))
}

/// std's package, as its site documents it, and std's analysis.
pub(crate) fn std_package() -> Result<(Package, Analysis), Failure> {
    let std = std_analysis()?;
    let package = Ctx::new(&std, true, false)?.std_package();
    Ok((package, std))
}

/// The analysis a package's site reads, of its library when it has one,
/// else of its program (spec ยง5.1), and whether it is a library. Errors
/// are a failure. Under `tests`, `std/test` is in scope, as in a test
/// build.
fn package_analysis(root: &Path, tests: bool) -> Result<(Analysis, bool), Failure> {
    let mut program = Program::for_package(root, Roots::Check);
    let stem = |p: &Path| p.file_stem().and_then(|s| s.to_str()).map(str::to_string);
    let library = program
        .roots
        .iter()
        .any(|r| stem(&r.path).as_deref() == Some("lib"));
    let keep = if library { "lib" } else { "main" };
    program
        .roots
        .retain(|r| stem(&r.path).as_deref() == Some(keep));
    program.runs = false;
    let options = Options {
        tests,
        index: true,
        module_only: true,
        ..Options::default()
    };
    let analysis = analyze_program(program, &DiskSources, &options)
        .map_err(|e| Failure::Other(format!("cannot read the program: {e}")))?;
    if analysis
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error)
    {
        return Err(Failure::Diagnostics {
            db: analysis.db,
            diagnostics: analysis.diagnostics,
        });
    }
    Ok((analysis, library))
}

/// Document std alone (spec ยง4.1, `--std`).
pub fn document_std() -> Result<Documented, Failure> {
    let (package, _) = std_package()?;
    Ok(Documented {
        site: Site {
            packages: vec![package],
            start: "std/index.html".to_string(),
        },
        db: FileDb::new(),
        warnings: Vec::new(),
    })
}

/// Serves std's analysis its entry, which no file holds.
struct StdEntry;

impl Sources for StdEntry {
    fn read(&self, path: &Path) -> std::io::Result<String> {
        if path == Path::new(STD_ENTRY) {
            Ok("fn main() {}\n".to_string())
        } else {
            Err(std::io::Error::from(std::io::ErrorKind::NotFound))
        }
    }
}

/// An analysis of std alone, `std/test` included (plan decision 8).
fn std_analysis() -> Result<Analysis, Failure> {
    let options = Options {
        tests: true,
        index: true,
        module_only: true,
        ..Options::default()
    };
    let a = analyze_program(Program::loose(Path::new(STD_ENTRY)), &StdEntry, &options)
        .map_err(|e| Failure::Other(format!("cannot analyse std: {e}")))?;
    if a.diagnostics.iter().any(|d| d.severity == Severity::Error) {
        return Err(Failure::Diagnostics {
            db: a.db,
            diagnostics: a.diagnostics,
        });
    }
    Ok(a)
}

/// Spec ยง4.2: two packages, or two modules of one package, that would
/// share a directory, names that differ in ASCII case alone included.
fn clash(packages: &[Package]) -> Result<(), Failure> {
    for (k, p) in packages.iter().enumerate() {
        if !p.std && p.name.eq_ignore_ascii_case("std") {
            return Err(Failure::Other(format!(
                "the package `{}` would share std's pages in target/doc/std/, so nova doc \
                 cannot document it",
                p.name
            )));
        }
        if let Some(q) = packages[..k]
            .iter()
            .find(|q| q.name.eq_ignore_ascii_case(&p.name))
        {
            return Err(Failure::Other(format!(
                "the packages `{}` and `{}` would share one directory in target/doc/, so nova \
                 doc cannot document them",
                q.name, p.name
            )));
        }
        // The root module's page is the package's own.
        let modules: Vec<&Module> = p.modules.iter().filter(|m| !m.root).collect();
        for (j, m) in modules.iter().enumerate() {
            if let Some(n) = modules[..j]
                .iter()
                .find(|n| n.name.eq_ignore_ascii_case(&m.name))
            {
                return Err(Failure::Other(format!(
                    "the modules `{}` and `{}` would share one directory in target/doc/{}/, so \
                     nova doc cannot document them",
                    n.qual, m.qual, p.name
                )));
            }
        }
    }
    Ok(())
}

/// Which namespace an item is exported in.
#[derive(Clone, Copy)]
enum Ns {
    Value,
    Type,
    Trait,
}

/// An impl met while building modules, placed once all are built.
struct Pending<'a> {
    module: ModuleId,
    span: Span,
    block: &'a ImplBlock,
}

/// Where an impl goes (spec ยง5.2).
enum Dest {
    /// With its type: the type's page and anchor.
    Item(String, String),
    /// On a primitive's page.
    Primitive(&'static str),
    /// On its own module's page, under "Implementations on other types".
    Own,
}

/// One analysis, read for its site.
struct Ctx<'a> {
    a: &'a Analysis,
    defs: &'a Definitions,
    file: &'a nova_ast::File,
    /// The program's own modules, which come before std's.
    users: usize,
    /// Whether this is std's own analysis, whose entry has no page.
    std: bool,
    /// Whether the root package documents every item and member (spec
    /// ยง5.1; plan decision 7).
    program: bool,
    /// Each name's target, by its span (spec ยง6.3).
    uses: HashMap<Span, Target>,
    /// Each rendered module's file, lexed once.
    texts: HashMap<FileId, FileText<'a>>,
}

impl<'a> Ctx<'a> {
    fn new(a: &'a Analysis, std: bool, program: bool) -> Result<Ctx<'a>, Failure> {
        let incomplete =
            || Failure::Other("the analysis is incomplete; this is a nova doc bug".to_string());
        let defs = a.definitions.as_ref().ok_or_else(incomplete)?;
        let file = a.file.as_ref().ok_or_else(incomplete)?;
        let index = a.index.as_ref().ok_or_else(incomplete)?;
        let mut uses: HashMap<Span, Target> = HashMap::new();
        for o in index.occurrences.iter().filter(|o| o.role == Role::Use) {
            let keep = uses
                .get(&o.span)
                .map_or(true, |t| rank(defs, &o.target) < rank(defs, t));
            if keep {
                uses.insert(o.span, o.target);
            }
        }
        let mut ctx = Ctx {
            a,
            defs,
            file,
            users: a.modules.len(),
            std,
            program,
            uses,
            texts: HashMap::new(),
        };
        for m in 0..defs.module_count() {
            let m = ModuleId(m as u32);
            if !ctx.renders(m) {
                continue;
            }
            if let Some(id) = ctx.module_file(m) {
                if let Some(text) = a.db.get_source(id) {
                    ctx.texts.insert(id, FileText::new(text, id));
                }
            }
        }
        Ok(ctx)
    }

    /// Whether this analysis renders module `m`'s page: std's analysis its
    /// std modules, a project's analysis its own.
    fn renders(&self, m: ModuleId) -> bool {
        ((m.0 as usize) >= self.users) == self.std
    }

    fn std_name(&self, m: ModuleId) -> Option<&str> {
        self.defs.module_name(m).strip_prefix("$std.")
    }

    fn module_file(&self, m: ModuleId) -> Option<FileId> {
        let i = m.0 as usize;
        if i < self.users {
            self.a.modules.get(i).map(|(f, _)| *f)
        } else {
            self.a.db.id_of(&format!("<std/{}>", self.std_name(m)?))
        }
    }

    fn package_id(&self, m: ModuleId) -> Option<PackageId> {
        self.a.module_packages.get(m.0 as usize).copied().flatten()
    }

    fn package_name(&self, m: ModuleId) -> Option<&str> {
        Some(&self.a.graph.as_ref()?.package(self.package_id(m)?).name)
    }

    /// The stem of the root module of `m`'s package (plan decision 9).
    fn root_stem(&self, m: ModuleId) -> &'static str {
        if self.program && self.package_id(m) == Some(PackageId(0)) {
            "main"
        } else {
            "lib"
        }
    }

    /// Module `m`'s page, from the site's root (spec ยง6.1). Every std
    /// module has one, whichever analysis asks.
    fn page(&self, m: ModuleId) -> Option<String> {
        let i = m.0 as usize;
        if i >= self.users {
            return Some(format!("std/{}/index.html", self.std_name(m)?));
        }
        if self.std {
            return None;
        }
        let stem = self.a.modules.get(i)?.1.file_stem()?.to_str()?;
        let package = self.package_name(m)?;
        Some(if stem == self.root_stem(m) {
            format!("{package}/index.html")
        } else {
            format!("{package}/{stem}/index.html")
        })
    }

    /// Whether module `m` documents every item and member: it is the root
    /// package's, and that package is only a program.
    fn all(&self, m: ModuleId) -> bool {
        self.program && (m.0 as usize) < self.users && self.package_id(m) == Some(PackageId(0))
    }

    fn same_package(&self, a: ModuleId, b: ModuleId) -> bool {
        let std = |m: ModuleId| m.0 as usize >= self.users;
        if std(a) || std(b) {
            std(a) && std(b)
        } else {
            self.package_id(a) == self.package_id(b)
        }
    }

    /// Whether module `m` documents its item `name` (spec ยง5.1).
    fn shown(&self, m: ModuleId, ns: Ns, name: &str) -> bool {
        if self.all(m) {
            return true;
        }
        let e = self.defs.exported(m, name);
        match ns {
            Ns::Value => e.value.is_some(),
            Ns::Type => e.ty.is_some(),
            Ns::Trait => e.trait_def.is_some(),
        }
    }

    fn member_shown(&self, m: ModuleId, vis: Visibility) -> bool {
        self.all(m) || vis == Visibility::Pub
    }

    /// `target`'s page and anchor from the site's root, when the site
    /// documents it (spec ยง6.3).
    fn url(&self, target: &Target) -> Option<String> {
        match *target {
            Target::Primitive(p) => Some(format!("std/primitive.{p}.html")),
            Target::Def(id) => {
                let def = self.defs.def(id);
                let item = |item_index: usize, ns: Ns, prefix: &str| {
                    let m = self.defs.module_of(item_index);
                    if !self.shown(m, ns, &def.name) {
                        return None;
                    }
                    Some(format!("{}#{prefix}.{}", self.page(m)?, def.name))
                };
                match &def.kind {
                    DefKind::Fn { item_index } => item(*item_index, Ns::Value, "fn"),
                    DefKind::Const { item_index } => item(*item_index, Ns::Value, "const"),
                    DefKind::Record { item_index } => item(*item_index, Ns::Type, "record"),
                    DefKind::Sum { item_index, .. } => item(*item_index, Ns::Type, "type"),
                    DefKind::Trait { item_index } => item(*item_index, Ns::Trait, "trait"),
                    DefKind::ExternFn { item_index, .. } => {
                        let m = self.defs.module_of(*item_index);
                        if !self.all(m) {
                            return None;
                        }
                        Some(format!("{}#fn.{}", self.page(m)?, def.name))
                    }
                    DefKind::AssocType { trait_def } => {
                        let t = self.url(&Target::Def(*trait_def))?;
                        Some(format!("{t}.type.{}", def.name))
                    }
                    DefKind::Method { .. } => None,
                }
            }
            Target::Variant(sum, vi) => {
                let base = self.url(&Target::Def(sum))?;
                let DefKind::Sum { variants, .. } = &self.defs.def(sum).kind else {
                    return None;
                };
                Some(format!(
                    "{base}.variant.{}",
                    variants.get(vi as usize)?.name
                ))
            }
            Target::Field(rec, fi) => {
                let base = self.url(&Target::Def(rec))?;
                let DefKind::Record { item_index } = self.defs.def(rec).kind else {
                    return None;
                };
                let Ast::Record(r) = &self.file.items.get(item_index)?.value else {
                    return None;
                };
                let field = r.fields.get(fi as usize)?;
                if !self.member_shown(self.defs.module_of(item_index), field.vis) {
                    return None;
                }
                Some(format!("{base}.field.{}", field.name.value))
            }
            _ => None,
        }
    }

    /// `text[start..end]`'s signature for a page at `page` (spec ยง8).
    fn sig(
        &self,
        ft: &FileText,
        page: &str,
        start: usize,
        end: usize,
        own: Option<Span>,
    ) -> String {
        signature::render(ft, start, end, own, &|span| {
            self.uses
                .get(&span)
                .and_then(|t| self.url(t))
                .map(|url| relative(page, &url))
        })
    }
}

/// `url`, from the site's root, as seen from `page` (plan decision 13).
pub(crate) fn relative(page: &str, url: &str) -> String {
    format!("{}{url}", "../".repeat(page.matches('/').count()))
}

/// Doc lines rendered, their headings moved down `level` levels, keeping
/// their source (3.5b spec ยง11.1).
fn docs_of(lines: &[Spanned<String>], level: u8) -> Docs {
    markdown::render_source(markdown::join(lines), level)
}

/// The last segment of a path type: what an impl is on.
fn type_name(ty: &Type) -> Option<&Spanned<String>> {
    match ty {
        Type::Path { path, .. } => path.segments.last(),
        _ => None,
    }
}

/// `base`, or `base-2`, `base-3` and so on: the first not yet on its page
/// (spec ยง6.2).
fn unique(taken: &mut HashSet<String>, base: String) -> String {
    if taken.insert(base.clone()) {
        return base;
    }
    (2..)
        .map(|n| format!("{base}-{n}"))
        .find(|a| taken.insert(a.clone()))
        .expect("an unused id")
}

impl<'a> Ctx<'a> {
    /// Module `m` and its items; its impls go to `pending` (spec ยง7.3).
    fn module(&self, m: ModuleId, pending: &mut Vec<Pending<'a>>) -> Option<Module> {
        let page = self.page(m)?;
        let ft = self.texts.get(&self.module_file(m)?)?;
        let (name, qual, root) = if m.0 as usize >= self.users {
            let n = self.std_name(m)?.to_string();
            let qual = format!("std::{n}");
            (n, qual, false)
        } else {
            let stem = self
                .a
                .modules
                .get(m.0 as usize)?
                .1
                .file_stem()?
                .to_str()?
                .to_string();
            let package = self.package_name(m)?.to_string();
            let root = stem == self.root_stem(m);
            let qual = if root {
                package
            } else {
                format!("{package}::{stem}")
            };
            (stem, qual, root)
        };
        let mut items = Vec::new();
        for (i, item) in self.file.items.iter().enumerate() {
            if self.defs.module_of(i) != m {
                continue;
            }
            match &item.value {
                Ast::Function(f) if self.shown(m, Ns::Value, &f.name.value) => {
                    items.push(self.function(
                        ft,
                        &page,
                        &f.name,
                        &f.docs,
                        f.return_ty.as_ref(),
                        &f.where_clause,
                    ))
                }
                Ast::Extern(block) if self.all(m) => {
                    for e in &block.items {
                        let ExternItem::Fn(sig) = e;
                        items.push(self.function(
                            ft,
                            &page,
                            &sig.name,
                            &sig.docs,
                            sig.return_ty.as_ref(),
                            &sig.where_clause,
                        ));
                    }
                }
                Ast::Record(r) if self.shown(m, Ns::Type, &r.name.value) => {
                    items.push(self.record(ft, &page, m, r))
                }
                Ast::Type(t)
                    if matches!(t.def, TypeDef::Sum(_))
                        && self.shown(m, Ns::Type, &t.name.value) =>
                {
                    items.push(self.sum(ft, &page, t))
                }
                Ast::Trait(t) if self.shown(m, Ns::Trait, &t.name.value) => {
                    items.push(self.trait_item(ft, &page, t))
                }
                Ast::Const(c) if self.shown(m, Ns::Value, &c.name.value) => {
                    items.push(self.constant(ft, &page, c))
                }
                Ast::Impl(block) => pending.push(Pending {
                    module: m,
                    span: item.span,
                    block,
                }),
                _ => {}
            }
        }
        Some(Module {
            name,
            qual,
            page,
            root,
            docs: markdown::render_source(ft.module_docs(), 1),
            items,
            other_impls: Vec::new(),
        })
    }

    fn function(
        &self,
        ft: &FileText,
        page: &str,
        name: &Spanned<String>,
        docs: &[Spanned<String>],
        ret: Option<&Spanned<Type>>,
        wheres: &[WhereBound],
    ) -> Item {
        let start = signature::decl_start(ft.text, name.span.start as usize);
        let end = signature::fn_end(ft, name.span, ret, wheres);
        Item {
            kind: ItemKind::Function,
            name: name.value.clone(),
            anchor: format!("fn.{}", name.value),
            signature: self.sig(ft, page, start, end, Some(name.span)),
            docs: docs_of(docs, 3),
            members: Vec::new(),
            hidden_fields: false,
            impls: Vec::new(),
        }
    }

    fn record(&self, ft: &FileText, page: &str, m: ModuleId, r: &Record) -> Item {
        let start = signature::decl_start(ft.text, r.name.span.start as usize);
        let end = ft
            .next(r.name.span.end as usize, |t| *t == Token::LBrace)
            .unwrap_or(r.name.span.end as usize);
        let anchor = format!("record.{}", r.name.value);
        let mut members = Vec::new();
        let mut hidden = false;
        for f in &r.fields {
            if !self.member_shown(m, f.vis) {
                hidden = true;
                continue;
            }
            let start = signature::decl_start(ft.text, f.name.span.start as usize);
            members.push(Member {
                kind: MemberKind::Field,
                name: f.name.value.clone(),
                anchor: format!("{anchor}.field.{}", f.name.value),
                signature: self.sig(ft, page, start, f.ty.span.end as usize, Some(f.name.span)),
                docs: docs_of(&f.docs, 4),
            });
        }
        Item {
            kind: ItemKind::Record,
            name: r.name.value.clone(),
            signature: self.sig(ft, page, start, end, Some(r.name.span)),
            anchor,
            docs: docs_of(&r.docs, 3),
            members,
            hidden_fields: hidden,
            impls: Vec::new(),
        }
    }

    fn sum(&self, ft: &FileText, page: &str, t: &TypeDecl) -> Item {
        let start = signature::decl_start(ft.text, t.name.span.start as usize);
        let end = ft
            .next(t.name.span.end as usize, |t| *t == Token::Eq)
            .unwrap_or(t.name.span.end as usize);
        let anchor = format!("type.{}", t.name.value);
        let members = match &t.def {
            TypeDef::Sum(variants) => variants
                .iter()
                .map(|v| {
                    let end = if v.fields.is_empty() {
                        v.name.span.end as usize
                    } else {
                        ft.group_end(v.name.span.end as usize)
                            .unwrap_or(v.name.span.end as usize)
                    };
                    Member {
                        kind: MemberKind::Variant,
                        name: v.name.value.clone(),
                        anchor: format!("{anchor}.variant.{}", v.name.value),
                        signature: self.sig(
                            ft,
                            page,
                            v.name.span.start as usize,
                            end,
                            Some(v.name.span),
                        ),
                        docs: docs_of(&v.docs, 4),
                    }
                })
                .collect(),
            TypeDef::Alias(_) => Vec::new(),
        };
        Item {
            kind: ItemKind::Sum,
            name: t.name.value.clone(),
            signature: self.sig(ft, page, start, end, Some(t.name.span)),
            anchor,
            docs: docs_of(&t.docs, 3),
            members,
            hidden_fields: false,
            impls: Vec::new(),
        }
    }

    fn trait_item(&self, ft: &FileText, page: &str, t: &TraitDecl) -> Item {
        let start = signature::decl_start(ft.text, t.name.span.start as usize);
        let end = ft
            .next(t.name.span.end as usize, |t| *t == Token::LBrace)
            .unwrap_or(t.name.span.end as usize);
        let anchor = format!("trait.{}", t.name.value);
        let mut types = Vec::new();
        let mut methods = Vec::new();
        for item in &t.items {
            match item {
                TraitItem::AssocType { docs, name, bounds } => {
                    let end = bounds.last().map_or(name.span.end, |b| b.span.end) as usize;
                    let start = signature::decl_start(ft.text, name.span.start as usize);
                    types.push(Member {
                        kind: MemberKind::AssocType,
                        name: name.value.clone(),
                        anchor: format!("{anchor}.type.{}", name.value),
                        signature: self.sig(ft, page, start, end, Some(name.span)),
                        docs: docs_of(docs, 4),
                    });
                }
                TraitItem::Required(s) => methods.push(self.method(
                    ft,
                    page,
                    &format!("{anchor}.method"),
                    &s.name,
                    &s.docs,
                    s.return_ty.as_ref(),
                    &s.where_clause,
                )),
                TraitItem::Provided(f) => methods.push(self.method(
                    ft,
                    page,
                    &format!("{anchor}.method"),
                    &f.name,
                    &f.docs,
                    f.return_ty.as_ref(),
                    &f.where_clause,
                )),
            }
        }
        types.extend(methods);
        Item {
            kind: ItemKind::Trait,
            name: t.name.value.clone(),
            signature: self.sig(ft, page, start, end, Some(t.name.span)),
            anchor,
            docs: docs_of(&t.docs, 3),
            members: types,
            hidden_fields: false,
            impls: Vec::new(),
        }
    }

    /// A method, its anchor `<prefix>.<name>`.
    #[allow(clippy::too_many_arguments)]
    fn method(
        &self,
        ft: &FileText,
        page: &str,
        prefix: &str,
        name: &Spanned<String>,
        docs: &[Spanned<String>],
        ret: Option<&Spanned<Type>>,
        wheres: &[WhereBound],
    ) -> Member {
        let start = signature::decl_start(ft.text, name.span.start as usize);
        let end = signature::fn_end(ft, name.span, ret, wheres);
        Member {
            kind: MemberKind::Method,
            name: name.value.clone(),
            anchor: format!("{prefix}.{}", name.value),
            signature: self.sig(ft, page, start, end, Some(name.span)),
            docs: docs_of(docs, 4),
        }
    }

    fn constant(&self, ft: &FileText, page: &str, c: &ConstDecl) -> Item {
        let start = signature::decl_start(ft.text, c.name.span.start as usize);
        Item {
            kind: ItemKind::Constant,
            name: c.name.value.clone(),
            anchor: format!("const.{}", c.name.value),
            signature: self.sig(
                ft,
                page,
                start,
                c.value.span.end as usize,
                Some(c.name.span),
            ),
            docs: docs_of(&c.docs, 3),
            members: Vec::new(),
            hidden_fields: false,
            impls: Vec::new(),
        }
    }
}

impl<'a> Ctx<'a> {
    /// Each impl in `pending`, where spec ยง5.2 puts it.
    fn place(
        &self,
        modules: &mut [Module],
        primitives: &mut [Primitive],
        pending: Vec<Pending<'a>>,
    ) {
        let mut taken: HashMap<String, HashSet<String>> = HashMap::new();
        for m in modules.iter() {
            let set = taken.entry(m.page.clone()).or_default();
            for item in &m.items {
                set.insert(item.anchor.clone());
                for member in &item.members {
                    set.insert(member.anchor.clone());
                }
            }
        }
        for p in pending {
            let block = p.block;
            let Some(ft) = self.module_file(p.module).and_then(|f| self.texts.get(&f)) else {
                continue;
            };
            let Some(own_page) = self.page(p.module) else {
                continue;
            };
            let on = type_name(&block.ty.value);
            let on_name = on.map_or_else(|| "type".to_string(), |s| s.value.clone());
            let ty = on.and_then(|s| self.uses.get(&s.span)).copied();
            let dest = match ty {
                Some(Target::Def(id)) => {
                    let item_index = match self.defs.def(id).kind {
                        DefKind::Record { item_index } | DefKind::Sum { item_index, .. } => {
                            Some(item_index)
                        }
                        _ => None,
                    };
                    match item_index {
                        Some(ii) if self.same_package(self.defs.module_of(ii), p.module) => {
                            // A type of this package that is not documented
                            // takes its impls with it.
                            let Some(url) = self.url(&Target::Def(id)) else {
                                continue;
                            };
                            let (page, anchor) = url.split_once('#').unwrap_or((url.as_str(), ""));
                            Dest::Item(page.to_string(), anchor.to_string())
                        }
                        _ => Dest::Own,
                    }
                }
                Some(Target::Primitive(name)) if self.std => Dest::Primitive(name),
                _ => Dest::Own,
            };
            let page = match &dest {
                Dest::Item(page, _) => page.clone(),
                Dest::Primitive(name) => format!("std/primitive.{name}.html"),
                Dest::Own => own_page.clone(),
            };
            let header = self.impl_header(ft, &page, p.span, block);
            let mut methods = Vec::new();
            if block.trait_.is_none() {
                let prefix = match &dest {
                    Dest::Item(_, anchor) => format!("{anchor}.method"),
                    Dest::Primitive(_) => "method".to_string(),
                    Dest::Own => format!("impl.{on_name}.method"),
                };
                for f in block
                    .functions
                    .iter()
                    .filter(|f| self.member_shown(p.module, f.vis))
                {
                    let mut m = self.method(
                        ft,
                        &page,
                        &prefix,
                        &f.name,
                        &f.docs,
                        f.return_ty.as_ref(),
                        &f.where_clause,
                    );
                    m.anchor = unique(taken.entry(page.clone()).or_default(), m.anchor);
                    methods.push(m);
                }
            }
            let built = Impl {
                header,
                docs: docs_of(&block.docs, 4),
                methods,
                on: on_name.clone(),
            };
            match &dest {
                Dest::Item(page, anchor) => {
                    if let Some(item) = find_item(modules, page, anchor) {
                        item.impls.push(built);
                    }
                }
                Dest::Primitive(name) => {
                    if let Some(pr) = primitives.iter_mut().find(|pr| pr.name == *name) {
                        pr.impls.push(built);
                    }
                }
                Dest::Own => {
                    if let Some(m) = modules.iter_mut().find(|m| m.page == own_page) {
                        m.other_impls.push(built);
                    }
                }
            }
            // A trait of this package also lists the impl, by its header.
            let tr = block
                .trait_
                .as_ref()
                .and_then(|t| t.value.segments.last())
                .and_then(|s| self.uses.get(&s.span))
                .copied();
            if let Some(Target::Def(t)) = tr {
                if let DefKind::Trait { item_index } = self.defs.def(t).kind {
                    if self.same_package(self.defs.module_of(item_index), p.module) {
                        if let Some(url) = self.url(&Target::Def(t)) {
                            let (page, anchor) = url.split_once('#').unwrap_or((url.as_str(), ""));
                            let header = self.impl_header(ft, page, p.span, block);
                            if let Some(item) = find_item(modules, page, anchor) {
                                item.impls.push(Impl {
                                    header,
                                    docs: Docs::default(),
                                    methods: Vec::new(),
                                    on: on_name,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    /// An impl's header, `impl โ€ฆ {` without its brace (plan decision 10).
    fn impl_header(&self, ft: &FileText, page: &str, span: Span, block: &ImplBlock) -> String {
        let start = ft
            .next(span.start as usize, |t| *t == Token::Impl)
            .unwrap_or(span.start as usize);
        let end = ft
            .next(start, |t| *t == Token::LBrace)
            .unwrap_or(block.ty.span.end as usize);
        self.sig(ft, page, start, end, None)
    }

    /// A project's packages: the root first, then the rest by name (spec
    /// ยง7.1).
    fn packages(&self) -> Vec<Package> {
        let Some(graph) = self.a.graph.as_ref() else {
            return Vec::new();
        };
        let mut pending = Vec::new();
        let mut modules = Vec::new();
        let mut owners = Vec::new();
        for i in 0..self.users {
            let m = ModuleId(i as u32);
            let Some(pid) = self.package_id(m) else {
                continue;
            };
            if let Some(module) = self.module(m, &mut pending) {
                modules.push(module);
                owners.push(pid);
            }
        }
        self.place(&mut modules, &mut [], pending);
        let mut packages: Vec<Package> = Vec::new();
        for (module, pid) in modules.into_iter().zip(owners) {
            let gp = graph.package(pid);
            let at = match packages.iter().position(|p| p.name == gp.name) {
                Some(at) => at,
                None => {
                    packages.push(Package {
                        name: gp.name.clone(),
                        version: gp.manifest.package.version.to_string(),
                        description: gp.manifest.package.description.clone(),
                        std: false,
                        modules: Vec::new(),
                        primitives: Vec::new(),
                        builtins: Vec::new(),
                    });
                    packages.len() - 1
                }
            };
            packages[at].modules.push(module);
        }
        for p in &mut packages {
            p.modules
                .sort_by(|a, b| (!a.root, &a.name).cmp(&(!b.root, &b.name)));
        }
        let root = graph.root().name.clone();
        packages.sort_by(|a, b| (a.name != root, &a.name).cmp(&(b.name != root, &b.name)));
        packages
    }

    /// std's package, from std's own analysis (spec ยง5.3, ยง7.4).
    fn std_package(&self) -> Package {
        let mut pending = Vec::new();
        let mut modules: Vec<Module> = (self.users..self.defs.module_count())
            .filter_map(|i| self.module(ModuleId(i as u32), &mut pending))
            .collect();
        let mut primitives: Vec<Primitive> = PRIMITIVES
            .iter()
            .map(|&(name, about)| Primitive {
                name,
                page: format!("std/primitive.{name}.html"),
                about: markdown::render(about, 1),
                impls: Vec::new(),
            })
            .collect();
        self.place(&mut modules, &mut primitives, pending);
        modules.sort_by(|a, b| a.name.cmp(&b.name));
        let builtins = Builtin::ALL
            .iter()
            .filter(|b| !Builtin::STD_ONLY.contains(*b))
            .map(|b| BuiltinDoc {
                name: b.name(),
                signature: highlight(&nova_typeck::builtin_text(*b, self.defs)),
                docs: markdown::render(
                    BUILTINS
                        .iter()
                        .find(|(n, _)| *n == b.name())
                        .map_or("", |(_, d)| *d),
                    3,
                ),
            })
            .collect();
        Package {
            name: "std".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: Some(STD_ABOUT.to_string()),
            std: true,
            modules,
            primitives,
            builtins,
        }
    }
}

/// The item at `page`'s `anchor`.
fn find_item<'m>(modules: &'m mut [Module], page: &str, anchor: &str) -> Option<&'m mut Item> {
    modules
        .iter_mut()
        .find(|m| m.page == page)?
        .items
        .iter_mut()
        .find(|i| i.anchor == anchor)
}

/// A small site for the renderer's, the search index's and the writer's
/// tests.
#[cfg(test)]
pub(crate) fn sample_site() -> Site {
    let docs = |text: &str| markdown::render(text, 3);
    let point = Item {
        kind: ItemKind::Record,
        name: "Point".to_string(),
        anchor: "record.Point".to_string(),
        signature: "<span class=\"kw\">pub</span> <span class=\"kw\">record</span> \
                    <span class=\"name\">Point</span>"
            .to_string(),
        docs: docs("A point."),
        members: vec![Member {
            kind: MemberKind::Field,
            name: "x".to_string(),
            anchor: "record.Point.field.x".to_string(),
            signature: "<span class=\"kw\">pub</span> x: \
                        <a href=\"../std/primitive.Int.html\">Int</a>"
                .to_string(),
            docs: docs("Across \"x\"."),
        }],
        hidden_fields: true,
        impls: Vec::new(),
    };
    let module = |name: &str, qual: &str, page: &str, root: bool, items: Vec<Item>| Module {
        name: name.to_string(),
        qual: qual.to_string(),
        page: page.to_string(),
        root,
        docs: markdown::render("A module.", 1),
        items,
        other_impls: Vec::new(),
    };
    let app = Package {
        name: "app".to_string(),
        version: "0.1.0".to_string(),
        description: Some("An app.".to_string()),
        std: false,
        modules: vec![
            module("main", "app", "app/index.html", true, vec![point]),
            module(
                "util",
                "app::util",
                "app/util/index.html",
                false,
                Vec::new(),
            ),
        ],
        primitives: Vec::new(),
        builtins: Vec::new(),
    };
    let std = Package {
        name: "std".to_string(),
        version: "0.2.0".to_string(),
        description: Some(STD_ABOUT.to_string()),
        std: true,
        modules: vec![module(
            "core",
            "std::core",
            "std/core/index.html",
            false,
            Vec::new(),
        )],
        primitives: vec![Primitive {
            name: "Int",
            page: "std/primitive.Int.html".to_string(),
            about: markdown::render("An integer.", 1),
            impls: Vec::new(),
        }],
        builtins: vec![BuiltinDoc {
            name: "println",
            signature: "<span class=\"kw\">fn</span> println(String) -&gt; ()".to_string(),
            docs: markdown::render("Writes a line.", 3),
        }],
    };
    Site {
        packages: vec![app, std],
        start: "app/index.html".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    /// A fresh, empty directory with a fixed name, so each run replaces the
    /// last.
    fn fresh(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("nova-doc-model-{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn write(dir: &Path, files: &[(&str, &str)]) {
        for (path, text) in files {
            let path = dir.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
    }

    fn manifest(name: &str, extra: &str) -> String {
        format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2026\"\n{extra}")
    }

    fn documented(root: &Path) -> Documented {
        match document_package(root) {
            Ok(d) => d,
            Err(Failure::Diagnostics { db, diagnostics }) => panic!(
                "{}",
                nova_diagnostics::render::render_to_string(&db, &diagnostics)
            ),
            Err(Failure::Other(why)) => panic!("{why}"),
        }
    }

    fn module<'s>(site: &'s Site, page: &str) -> &'s Module {
        site.packages
            .iter()
            .flat_map(|p| &p.modules)
            .find(|m| m.page == page)
            .unwrap_or_else(|| panic!("no page {page}"))
    }

    fn item<'m>(m: &'m Module, anchor: &str) -> &'m Item {
        m.items
            .iter()
            .find(|i| i.anchor == anchor)
            .unwrap_or_else(|| panic!("no {anchor} on {}", m.page))
    }

    const GEOM_LIB: &str = "import utils\n\n/// A point.\npub record Point {\n    /// Across.\n    pub x: Int,\n    y: Int,\n}\n\n/// The area of a square of side `width()`.\npub fn area() -> Int { width() * width() }\n\nfn secret() -> Int { 1 }\n\nrecord Hidden {\n    n: Int,\n}\n\n/// Makes a thing of a private type.\npub fn make() -> Hidden { Hidden { n: 1 } }\n";
    const GEOM_UTILS: &str = "/// Three.\npub fn width() -> Int { 3 }\n";
    const APP_MAIN: &str = "import geom\n\n/// Shows `p`.\nfn show(p: Point) -> String { \"${p.x}\" }\n\n/// A record of the app's own.\nrecord Local {\n    hidden: Int,\n}\n\nfn main() {\n    println(show(Point { x: area(), y: 0 }))\n}\n";

    #[test]
    fn std_is_one_package_of_modules_primitives_and_builtins() {
        let Ok(d) = document_std() else {
            panic!("std is not documented")
        };
        assert_eq!(d.site.packages.len(), 1);
        assert_eq!(d.site.start, "std/index.html");
        let std = &d.site.packages[0];
        assert!(std.std);
        let names: Vec<&str> = std.modules.iter().map(|m| m.name.as_str()).collect();
        assert_eq!(
            names,
            [
                "bytes",
                "collections",
                "core",
                "crypto",
                "fmt",
                "fs",
                "http",
                "io",
                "json",
                "log",
                "net",
                "process",
                "strings",
                "sync",
                "task",
                "test",
                "time"
            ]
        );
        let core = module(&d.site, "std/core/index.html");
        let option = item(core, "type.Option");
        let variants: Vec<&str> = option.members.iter().map(|m| m.anchor.as_str()).collect();
        assert_eq!(
            variants,
            ["type.Option.variant.Some", "type.Option.variant.None"]
        );
        assert!(option.impls.iter().any(|i| i
            .methods
            .iter()
            .any(|m| m.anchor == "type.Option.method.unwrap")));
        let string = std
            .primitives
            .iter()
            .find(|p| p.name == "String")
            .expect("a String page");
        assert!(string.impls.iter().any(|i| !i.methods.is_empty()));
        let mut builtins: Vec<&str> = std.builtins.iter().map(|b| b.name).collect();
        builtins.sort_unstable();
        assert_eq!(
            builtins,
            ["eprint", "eprintln", "panic", "print", "println"]
        );
    }

    #[test]
    fn a_program_documents_every_item_and_its_library_only_its_exports() {
        let dir = fresh("program");
        write(
            &dir.join("geom"),
            &[
                ("nova.toml", &manifest("geom", "")),
                ("src/lib.nova", GEOM_LIB),
                ("src/utils.nova", GEOM_UTILS),
            ],
        );
        write(
            &dir.join("app"),
            &[
                (
                    "nova.toml",
                    &manifest("app", "\n[dependencies]\ngeom = { path = \"../geom\" }\n"),
                ),
                ("src/main.nova", APP_MAIN),
            ],
        );
        let d = documented(&dir.join("app"));
        let names: Vec<&str> = d.site.packages.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, ["app", "geom", "std"]);
        assert_eq!(d.site.start, "app/index.html");
        let app = module(&d.site, "app/index.html");
        assert!(app.root);
        let anchors: Vec<&str> = app.items.iter().map(|i| i.anchor.as_str()).collect();
        assert_eq!(anchors, ["fn.show", "record.Local", "fn.main"]);
        assert!(!item(app, "record.Local").hidden_fields);
        let show = item(app, "fn.show");
        assert!(
            show.signature
                .contains("<a href=\"../geom/index.html#record.Point\">Point</a>"),
            "{}",
            show.signature
        );
        assert!(
            show.signature
                .contains("<a href=\"../std/primitive.String.html\">String</a>"),
            "{}",
            show.signature
        );
        let geom = module(&d.site, "geom/index.html");
        let anchors: Vec<&str> = geom.items.iter().map(|i| i.anchor.as_str()).collect();
        assert_eq!(anchors, ["record.Point", "fn.area", "fn.make"]);
        // A private type in a public signature is plain text (mutant 1).
        let make = item(geom, "fn.make");
        assert!(!make.signature.contains("<a "), "{}", make.signature);
        let point = item(geom, "record.Point");
        assert!(point.hidden_fields);
        let fields: Vec<&str> = point.members.iter().map(|m| m.anchor.as_str()).collect();
        assert_eq!(fields, ["record.Point.field.x"]);
        module(&d.site, "geom/utils/index.html");
    }

    const IMPLS: &str = "/// A rectangle.\npub record Rect {\n    pub w: Int,\n    pub h: Int,\n}\n\nimpl Rect {\n    /// Its area.\n    pub fn area(self) -> Int { self.w * self.h }\n\n    fn hidden(self) -> Int { 0 }\n}\n\n/// What can be measured.\npub trait Measure {\n    /// The size.\n    fn size(self) -> Int\n}\n\nimpl Measure for Rect {\n    fn size(self) -> Int { self.area() }\n}\n\nimpl Int {\n    /// Twice it.\n    pub fn doubled(self) -> Int { self * 2 }\n}\n";

    #[test]
    fn an_impl_goes_with_its_type_and_a_trait_lists_its_impls() {
        let dir = fresh("impls");
        write(
            &dir,
            &[
                ("nova.toml", &manifest("shapes", "")),
                ("src/lib.nova", IMPLS),
            ],
        );
        let d = documented(&dir);
        let lib = module(&d.site, "shapes/index.html");
        let rect = item(lib, "record.Rect");
        assert_eq!(rect.impls.len(), 2, "the inherent impl and the trait impl");
        let methods: Vec<&str> = rect
            .impls
            .iter()
            .flat_map(|i| &i.methods)
            .map(|m| m.anchor.as_str())
            .collect();
        assert_eq!(methods, ["record.Rect.method.area"]);
        let measure = item(lib, "trait.Measure");
        assert_eq!(measure.impls.len(), 1);
        assert!(
            measure.impls[0]
                .header
                .contains("<a href=\"../shapes/index.html#record.Rect\">Rect</a>"),
            "{}",
            measure.impls[0].header
        );
        assert_eq!(lib.other_impls.len(), 1, "the impl on Int");
        let doubled: Vec<&str> = lib.other_impls[0]
            .methods
            .iter()
            .map(|m| m.anchor.as_str())
            .collect();
        assert_eq!(doubled, ["impl.Int.method.doubled"]);
    }

    const PAIRS: &str = "/// Two of a kind.\npub record Pair<T> {\n    pub a: T,\n    pub b: T,\n}\n\nimpl Pair<Int> {\n    /// Their sum.\n    pub fn total(self) -> Int { self.a + self.b }\n}\n\nimpl Pair<String> {\n    /// The two, joined.\n    pub fn total(self) -> String { \"${self.a}${self.b}\" }\n}\n";

    #[test]
    fn two_impls_of_one_type_number_a_method_they_share() {
        // Spec ยง6.2: both impls go on `Pair`'s anchor, so the later
        // `total` is numbered.
        let dir = fresh("pairs");
        write(
            &dir,
            &[
                ("nova.toml", &manifest("pairs", "")),
                ("src/lib.nova", PAIRS),
            ],
        );
        let d = documented(&dir);
        let lib = module(&d.site, "pairs/index.html");
        let methods: Vec<&str> = item(lib, "record.Pair")
            .impls
            .iter()
            .flat_map(|i| &i.methods)
            .map(|m| m.anchor.as_str())
            .collect();
        assert_eq!(
            methods,
            ["record.Pair.method.total", "record.Pair.method.total-2"]
        );
    }

    #[test]
    fn an_error_is_a_failure_that_carries_its_diagnostics() {
        let dir = fresh("error");
        write(
            &dir,
            &[
                ("nova.toml", &manifest("app", "")),
                ("src/main.nova", "fn main() {\n    let x: Int = \"s\"\n}\n"),
            ],
        );
        match document_package(&dir) {
            Err(Failure::Diagnostics { diagnostics, .. }) => {
                assert!(diagnostics.iter().any(|d| d.severity == Severity::Error))
            }
            _ => panic!("a program with an error was documented"),
        }
    }

    #[test]
    fn a_package_named_std_stops_it() {
        let dir = fresh("named-std");
        write(
            &dir,
            &[
                ("nova.toml", &manifest("std", "")),
                ("src/main.nova", "fn main() {}\n"),
            ],
        );
        match document_package(&dir) {
            Err(Failure::Other(why)) => assert!(why.contains("`std`"), "{why}"),
            _ => panic!("a package named std was documented"),
        }
    }

    #[test]
    fn two_modules_whose_names_differ_in_case_alone_stop_it() {
        // Their pages would share a directory on macOS's and Windows's
        // file systems, which ignore case.
        let mut site = sample_site();
        assert!(clash(&site.packages).is_ok());
        let mut util = sample_site().packages.remove(0).modules.remove(1);
        util.name = "Util".to_string();
        util.qual = "app::Util".to_string();
        util.page = "app/Util/index.html".to_string();
        site.packages[0].modules.insert(1, util);
        match clash(&site.packages) {
            Err(Failure::Other(why)) => assert_eq!(
                why,
                "the modules `app::Util` and `app::util` would share one directory in \
                 target/doc/app/, so nova doc cannot document them"
            ),
            _ => panic!("two modules that differ in case alone were documented"),
        }
    }

    #[test]
    fn a_clashing_id_gets_a_number() {
        // Spec ยง6.2: the later of two equal ids on one page.
        let mut taken = HashSet::new();
        assert_eq!(
            unique(&mut taken, "impl.Vec.method.a".to_string()),
            "impl.Vec.method.a"
        );
        assert_eq!(
            unique(&mut taken, "impl.Vec.method.a".to_string()),
            "impl.Vec.method.a-2"
        );
        assert_eq!(
            unique(&mut taken, "impl.Vec.method.a".to_string()),
            "impl.Vec.method.a-3"
        );
    }

    #[test]
    fn every_builtin_a_module_sees_has_docs() {
        for b in Builtin::ALL
            .iter()
            .filter(|b| !Builtin::STD_ONLY.contains(*b))
        {
            assert!(BUILTINS.iter().any(|(n, _)| *n == b.name()), "{}", b.name());
        }
    }
}