raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
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
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
// SPDX-FileCopyrightText: 2026 Blackcat Informatics® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! The symbol index: every named item of every module tree, the module graph
//! it lives in, and the scope tables the resolver reads.
//!
//! Building runs in four steps. The emit step turns the facts of each file,
//! once per module path the file is reached under, into items, module
//! contents, `use` declarations and impl blocks. It reads the files in the
//! order the module-tree walk reached them, so every module is created by the
//! `mod` declaration that names it, under its parent, before its own file is
//! read; the order of the file names plays no part. The scope step builds the
//! name tables of every module and settles them to a fixed point (see
//! [`crate::resolve`]). The impl step attaches the members of impl blocks to
//! the types they resolve to. The order step sorts the items.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::mem::size_of;
use std::sync::Arc;

use purrdf_lex::allocation::Memory;

use crate::cost::{btree_entry, btree_map, hash_entry, hash_map, shared_text, vec_first, vec_slot};
use crate::error::{LoadError, LoadErrorKind};
use crate::facts::{
    ConfigurationDependence, FieldShape, ImplFact, ItemFact, ItemKind, ModBody, ModFact, PathFact,
    SpanFact, TestRole, UseTree, Vis,
};
use crate::glob_scope::{GlobTables, ImportReach};
use crate::intern::Interner;
use crate::item::{
    DisabledSyntax, ImplBlock, ImplId, Item, ItemId, Namespace, SelfType, SharedStr, SymbolKind,
    TraitKey, Unexpanded, UnresolvedImpl,
};
use crate::manifest::DependencyKind;
use crate::meter::{ItemAdmission, LookupCount, Meter, NativeAdmission, Steps, push_item_work};
use crate::modtree::{TargetId, Visit};
use crate::path::RelPath;
use crate::settle::{Entry, ImportReadState, Origin, Scope};
use crate::target::{PackageId, Target, TargetKind};
use crate::workspace::SourceFile;
use purrdf_hash::fixed::FixedState;
use purrdf_lex::walk::WorkList;

/// What an item allocates at most in the index beyond its strings: its record
/// in the list of items, its place in the order and among the items of its
/// file, and its source group (the group's entry and first room).
const ITEM_BYTES: usize = vec_slot::<Item>()
    + 2 * vec_slot::<ItemId>()
    + btree_entry::<(RelPath, usize), Vec<ItemId>>()
    + vec_first::<ItemId>()
    + vec_slot::<ItemId>();

/// What a module allocates at most beyond its path: its record, its entry in
/// the table of module paths, its scope table and its slot among the scopes,
/// the first room of its definitions and of the copy the scopes are built from.
pub(crate) const MODULE_BYTES: usize = vec_slot::<Module>()
    + btree_entry::<(usize, SharedStr), usize>()
    + vec_slot::<Scope>()
    + btree_map::<String, Box<Entry>>()
    + 2 * vec_first::<ItemId>()
    + vec_slot::<(usize, Vec<ItemId>)>();

/// What a type's table of members allocates at most, once for the type.
pub(crate) const MEMBERS_BYTES: usize =
    btree_entry::<ItemId, BTreeMap<String, Vec<ItemId>>>() + btree_map::<String, Vec<ItemId>>();

/// What the tables and lists of one load allocate before their first entries:
/// every load-wide table and list at its first room.
pub(crate) const LOAD_BASE_BYTES: usize = size_of::<Vec<Option<(usize, &str)>>>()
    + btree_map::<String, Vec<usize>>()
    + btree_map::<(usize, SharedStr), usize>()
    + btree_map::<ItemId, usize>()
    + btree_map::<ItemId, usize>()
    + btree_map::<ItemId, Vec<usize>>()
    + btree_map::<ItemId, SharedStr>()
    + btree_map::<usize, ItemId>()
    + btree_map::<(RelPath, usize), Vec<ItemId>>()
    + btree_map::<ItemId, BTreeMap<String, Vec<ItemId>>>()
    + btree_map::<String, Vec<ItemId>>()
    + btree_map::<RelPath, Vec<ItemId>>()
    + btree_map::<ItemId, (usize, Arc<PathFact>)>()
    + btree_map::<RelPath, SourceFile>()
    + btree_map::<(RelPath, TargetId, SharedStr), ()>()
    + btree_map::<(TargetId, &str), Vec<&SourceFile>>()
    + hash_map::<(crate::tree::FileId, usize)>()
    + hash_map::<(RelPath, crate::tree::FileId)>()
    + 2 * hash_map::<SharedStr>()
    + hash_map::<(*const PathFact, Arc<PathFact>)>()
    + vec_first::<Item>()
    + vec_first::<Unexpanded>()
    + 3 * vec_first::<ItemId>()
    + vec_first::<Module>()
    + vec_first::<Scope>()
    + vec_first::<UseDecl>()
    + 4 * vec_first::<bool>()
    + 4 * vec_first::<[bool; 3]>()
    + vec_first::<[ImportReadState; 3]>()
    + vec_first::<BTreeSet<usize>>()
    + vec_first::<(usize, usize)>()
    + vec_first::<Visit>()
    + vec_first::<ImplDecl<'static>>()
    + vec_first::<UnresolvedImpl>()
    + vec_first::<ImplBlock>()
    + vec_first::<usize>()
    + vec_first::<BTreeMap<String, ExternName>>()
    + vec_first::<u16>()
    + vec_first::<bool>()
    + 2 * vec_first::<usize>()
    + vec_first::<(usize, u64)>();

/// The first eight bytes of `name`, big-endian, padded with zero bytes: two
/// names compare as their prefixes do whenever the prefixes differ, as a name
/// holds no zero byte.
fn name_prefix(name: &str) -> u64 {
    let mut bytes = [0; 8];
    let taken = name.len().min(8);
    bytes[..taken].copy_from_slice(&name.as_bytes()[..taken]);
    u64::from_be_bytes(bytes)
}

/// What a definition allocates at most in the scope tables: its place among its
/// module's definitions and in the copy the scopes are built from, the entry of
/// its name in its module's scope table (the name copied as the key), and in
/// each name space it is bound in, a binding and the visibility it copies.
fn scope_bytes(name: &str, vis: &Vis, namespaces: usize) -> usize {
    2 * vec_slot::<ItemId>()
        + (btree_entry::<String, Box<Entry>>() + size_of::<Entry>())
        + name.len()
        + namespaces * (vec_slot::<(ItemId, Origin)>() + vis_capacity(vis))
}

/// What an import that binds `name` allocates at most for one binding: the
/// scope entry of the name (copied as the key), the binding, the visibility it
/// copies and the route it records (the name and the name it came through).
pub(crate) fn binding_bytes(name: &str, vis: &Vis, source: usize) -> usize {
    (btree_entry::<String, Box<Entry>>() + size_of::<Entry>())
        + 2 * name.len()
        + vec_slot::<(ItemId, Origin)>()
        + vis_capacity(vis)
        + source
}

/// What a member allocates at most among the members of a type or under the
/// key of a trait: the entry of its name or key (copied) and its slot in the
/// entry's first room.
pub(crate) fn member_bytes(key: &str) -> usize {
    btree_entry::<String, Vec<ItemId>>() + key.len() + vec_first::<ItemId>() + vec_slot::<ItemId>()
}

/// The bytes a visibility holds beyond its size.
fn vis_capacity(vis: &Vis) -> usize {
    match vis {
        Vis::Restricted(text) => text.capacity(),
        Vis::Inherited | Vis::Public => 0,
    }
}

/// The bytes a list of strings owns.
fn strings_bytes(strings: &[String]) -> usize {
    size_of_val(strings) + strings.iter().map(String::capacity).sum::<usize>()
}

/// A `use` declaration after its tree is flattened.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum UseKind {
    /// `use path as name` (or `use path`, which binds the last segment).
    Named {
        name: String,
        segs: Vec<String>,
        namespaces: NamedNamespaces,
    },
    /// `use path::*`.
    Glob { segs: Vec<String> },
}

/// The terminal namespaces a named import can bind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NamedNamespaces {
    All,
    /// `use path::{self}` and `use path::{self as name}`.
    TypeOnly,
}

impl NamedNamespaces {
    pub(crate) fn spaces(self) -> &'static [Namespace] {
        match self {
            Self::All => &Namespace::ALL,
            Self::TypeOnly => &[Namespace::Type],
        }
    }
}

impl UseKind {
    pub(crate) fn terminal_namespaces(&self) -> &'static [Namespace] {
        match self {
            Self::Named { namespaces, .. } => namespaces.spaces(),
            Self::Glob { .. } => &[Namespace::Type],
        }
    }
}

/// One flattened `use` entry and where it was written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct UseDecl {
    pub(crate) module: usize,
    pub(crate) file: RelPath,
    pub(crate) line: usize,
    pub(crate) leading_colon: bool,
    pub(crate) vis: Vis,
    /// True for test code: the declaration or a module around it is guarded
    /// by a `test` predicate, or its file is reached only through test code.
    pub(crate) test: bool,
    /// True when the declaration has `#[doc(hidden)]`.
    pub(crate) doc_hidden: bool,
    pub(crate) configuration: ConfigurationDependence,
    pub(crate) kind: UseKind,
}

/// What the index knows of a package's manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PackageInfo {
    pub(crate) configured: bool,
    /// The edition year.
    pub(crate) edition: u16,
    /// Its dependencies, from every table.
    pub(crate) dependencies: Vec<DependencyInfo>,
}

/// A dependency of a package, as the extern prelude of its targets sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DependencyInfo {
    /// The table it is declared in.
    pub(crate) kind: DependencyKind,
    /// The name it is declared under, with `-` as `_`.
    pub(crate) name: String,
    /// True when the entry renames its package (`package = ".."`), so code
    /// names it by `name`.
    pub(crate) renamed: bool,
    /// The package its path or checked outgoing lock edge names, if admitted.
    pub(crate) package: Option<PackageId>,
    /// Exact eligible targets for a configured locked edge; absent structurally.
    pub(crate) active_targets: Option<Vec<TargetId>>,
}

/// A crate name in the extern prelude of a target.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ExternName {
    /// True when every code of the target can name it; false when only its
    /// test code can (a dev-dependency of a library or a binary).
    pub(crate) everywhere: bool,
    /// The library crate roots of the workspace that the name stands for,
    /// each with whether every code of the target names it (true) or only
    /// its test code (false); empty for a crate outside the workspace.
    pub(crate) roots: Vec<(usize, bool)>,
}

impl ExternName {
    /// The library crate roots the name stands for in test code (`test`) or
    /// in other code.
    pub(crate) fn roots(&self, test: bool) -> impl Iterator<Item = usize> + '_ {
        self.roots
            .iter()
            .filter(move |(_, everywhere)| *everywhere || test)
            .map(|(root, _)| *root)
    }
}

impl UseDecl {
    pub(crate) const fn heads(&self, position: usize) -> crate::resolve::Heads {
        crate::resolve::Heads::Use {
            test: self.test,
            own: Some(position),
        }
    }

    /// Owned strings and path-vector storage copied with one import.
    pub(crate) fn clone_bytes(&self) -> usize {
        let path = match &self.kind {
            UseKind::Named { name, segs, .. } => name.len() + strings_bytes(segs),
            UseKind::Glob { segs } => strings_bytes(segs),
        };
        path + self.file.as_str().len() + vis_capacity(&self.vis)
    }

    /// What the entry allocates at most: its slot in the list of imports, its
    /// four flags, its four sets of flags by name space, its set of modules
    /// reached (each module in it is charged when a settle ends), its place in the
    /// named or the glob imports in order and among the keys of the named
    /// imports, and the strings it owns. What a
    /// named import binds is charged when it binds it.
    fn bytes(&self) -> usize {
        let owned = match &self.kind {
            UseKind::Named { name, segs, .. } => name.capacity() + strings_bytes(segs),
            UseKind::Glob { segs } => strings_bytes(segs),
        };
        vec_slot::<Self>()
            + 4 * vec_slot::<bool>()
            + 4 * vec_slot::<[bool; 3]>()
            + vec_slot::<[ImportReadState; 3]>()
            + vec_slot::<BTreeSet<usize>>()
            + vec_slot::<usize>()
            + vec_slot::<(usize, u64)>()
            + owned
            + vis_capacity(&self.vis)
    }
}

/// An impl block waiting for its self type to resolve, once for each module
/// path its file is reached under. The fact is the file's own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ImplDecl<'f> {
    pub(crate) module: usize,
    pub(crate) file: RelPath,
    pub(crate) target: TargetId,
    pub(crate) reach_test: bool,
    pub(crate) fact: &'f ImplFact,
}

/// A module declared inside a block: the module, the module that holds the
/// block, and the declaration in its file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BlockModule {
    pub(crate) module: usize,
    pub(crate) parent: usize,
    pub(crate) file: RelPath,
    pub(crate) span: (usize, usize),
}

/// A module: all the declarations that define the module at one path of one
/// crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Module {
    pub(crate) path: SharedStr,
    pub(crate) parent: Option<usize>,
    pub(crate) root: usize,
    /// The target whose crate the module is in.
    pub(crate) target: TargetId,
    pub(crate) defs: Vec<ItemId>,
    pub(crate) configuration: ConfigurationDependence,
}

/// The index of a workspace.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Index {
    pub(crate) items: Vec<Item>,
    pub(crate) unexpanded: Vec<Unexpanded>,
    pub(crate) disabled_syntax: Vec<DisabledSyntax>,
    /// The items in the order of [`crate::Workspace::items`].
    pub(crate) order: Vec<ItemId>,
    pub(crate) modules: Vec<Module>,
    /// The module at each path of each crate, by the crate's root module.
    pub(crate) module_by_path: BTreeMap<(usize, SharedStr), usize>,
    /// The modules declared inside blocks, which have no `mod` item.
    pub(crate) block_modules: Vec<BlockModule>,
    /// The module that a `mod` item stands for.
    pub(crate) module_of: BTreeMap<ItemId, usize>,
    /// Lexical homes of exported macros placed in a different export module.
    pub(crate) macro_modules: BTreeMap<ItemId, usize>,
    /// The crate roots that an `extern crate` item stands for.
    pub(crate) crate_of: BTreeMap<ItemId, Vec<usize>>,
    /// The root modules of the targets of each crate path, in the order of
    /// the targets. Targets of different packages can share one.
    pub(crate) crate_roots: BTreeMap<String, Vec<usize>>,
    /// The root module of each target.
    pub(crate) target_roots: Vec<usize>,
    /// The crate names each target's code can name, by target: its package's
    /// library (for a target other than the library and the build script) and
    /// the dependencies of its kind.
    pub(crate) preludes: Vec<BTreeMap<String, ExternName>>,
    pub(crate) targets: Vec<Target>,
    /// The edition of each target's package, by target.
    pub(crate) target_editions: Vec<u16>,
    /// True for a target whose crate root has `#![no_std]`, by target.
    pub(crate) target_no_std: Vec<bool>,
    /// True once a `use` path whose first segment a module with globs does
    /// not bind may start at a crate of the extern prelude: the globs have
    /// brought in what they can without it.
    pub(crate) crates_open: bool,
    /// The inherent impls whose self type the index cannot see, sorted by
    /// path, file and position.
    pub(crate) unresolved: Vec<UnresolvedImpl>,
    /// Every impl block, once for each module path its file is reached
    /// under, sorted by file, position, module path and target; a block's
    /// [`ImplId`] is its place here.
    pub(crate) impl_blocks: Vec<ImplBlock>,
    pub(crate) scopes: Vec<Scope>,
    pub(crate) uses: Vec<UseDecl>,
    /// The positions of the named imports, sorted by module, bound name and
    /// position.
    pub(crate) named_imports: Vec<usize>,
    /// The module of each of `named_imports` and the first eight bytes of
    /// the name it binds ([`name_prefix`]), in its order, so that the imports
    /// of a name are found without reading most declarations.
    pub(crate) named_keys: Vec<(usize, u64)>,
    /// The positions of the glob imports, sorted by module and position.
    pub(crate) glob_imports: Vec<usize>,
    /// True for an import resolved by a named binding or a certified final
    /// rooted glob answer.
    pub(crate) use_resolved: Vec<bool>,
    /// True once an import is resolved, has failed or is held as ambiguous.
    /// The named imports of a cycle, and those that wait on one, never
    /// settle.
    pub(crate) use_settled: Vec<bool>,
    /// True for a named import whose first segment is ambiguous: it binds
    /// nothing, and keeps the name it binds from the globs of its module and
    /// the crates in every name space.
    pub(crate) use_ambiguous: Vec<bool>,
    /// For each import and name space, true once the import bound something
    /// there.
    pub(crate) use_bound: Vec<[bool; 3]>,
    /// For each import and name space, true once the import leaves its name
    /// there to the globs of its module: its path is empty, a cycle left it
    /// to a fallback, or a closed rooted answer was finalized on the globs.
    pub(crate) use_free: Vec<[bool; 3]>,
    /// For each import and name space, true once the import is decided
    /// there: it bound something, or the settling of the tables decided that
    /// it binds nothing there, or finalized a certified rooted glob answer
    /// without a named binding. An import of a cycle, and one that waits on a
    /// cycle, stays undecided in the name spaces the cycle holds.
    pub(crate) use_decided: Vec<[bool; 3]>,
    /// For each import and name space, true once the settling of the tables
    /// found that the import's path can bind nothing there whatever is left
    /// to settle. Such a name space is left to the globs
    /// ([`Index::use_free`]) once another namespace binds something or has a
    /// certified closed rooted glob answer.
    pub(crate) use_empty: Vec<[bool; 3]>,
    /// Each namespace's read finality: privacy refusals retain their initial
    /// decision, and delegated answers retain their closed rooted proof.
    pub(crate) use_read_state: Vec<[ImportReadState; 3]>,
    /// Whether final privacy classification found a late import namespace.
    pub(crate) has_late_imports: bool,
    /// True for a glob import whose path resolved and whose target modules'
    /// globs, those its module can name, are settled: what it brings in can
    /// then only grow by what its targets bind (see [`Index::pending_at`]).
    /// Until then no name of its module is decided to bind nothing.
    pub(crate) glob_closed: Vec<bool>,
    /// The modules the path of each glob import reached when the glob was
    /// last tried, by position; empty for a named import.
    pub(crate) glob_reach: Vec<BTreeSet<usize>>,
    /// What the globs of the settled tables reach and which of them name
    /// nothing, computed once the index is built.
    pub(crate) glob_facts: crate::resolve::GlobFactsCache,
    /// The lookup steps made since the last checkpoint of the load, drained
    /// into its work there; zero once the index is built.
    pub(crate) lookups: LookupCount,
    /// What the glob imports of each module bring in (see
    /// [`crate::glob_scope`]).
    pub(crate) globs: GlobTables,
    /// The modules whose globs reach a module with an explicit import.
    pub(crate) import_reach: ImportReach,
    /// The crate an `extern crate` item names, by item.
    pub(crate) extern_names: BTreeMap<ItemId, SharedStr>,
    /// Items grouped by file and the byte offset where their span starts.
    /// The item of each target's crate root, by the root module.
    pub(crate) root_items: BTreeMap<usize, ItemId>,
    pub(crate) by_source: BTreeMap<(RelPath, usize), Vec<ItemId>>,
    /// Members of a type or trait, by name.
    pub(crate) assoc: BTreeMap<ItemId, BTreeMap<String, Vec<ItemId>>>,
    /// Members of trait impls on types that are not local, by written path.
    pub(crate) foreign: BTreeMap<String, Vec<ItemId>>,
    pub(crate) by_file: BTreeMap<RelPath, Vec<ItemId>>,
    /// The aliased path of each type alias, with the module it is written in.
    /// The path of a file's alias is shared by every module path that reaches
    /// the file.
    pub(crate) aliases: BTreeMap<ItemId, (usize, Arc<PathFact>, ConfigurationDependence)>,
}

/// Where the index puts its strings while it is built, and what it charges.
pub(crate) struct Store<'m> {
    /// One copy of each path, name and written type the items hold.
    strings: Interner,
    meter: &'m Meter,
}

impl Store<'_> {
    /// The meter of the load.
    pub(crate) fn meter(&self) -> &Meter {
        self.meter
    }

    /// The shared copy of `text` and what it costs the first time.
    pub(crate) fn intern(&mut self, text: &str) -> (SharedStr, usize) {
        self.strings.intern(text)
    }

    /// Charge `bytes` of records built for `file` at `line`.
    pub(crate) fn charge(
        &self,
        bytes: usize,
        file: &RelPath,
        line: Option<usize>,
    ) -> Result<(), LoadError> {
        self.meter.items(bytes, file, line)
    }

    /// Grow retained index storage through its original cumulative item grant.
    pub(crate) fn reserve_items<T>(
        &self,
        values: &mut Vec<T>,
        required: usize,
        file: &RelPath,
        line: Option<usize>,
    ) -> Result<(), LoadError> {
        let bytes = values.capacity() * size_of::<T>();
        let mut admission = NativeAdmission::items(self.meter, file, line, bytes);
        let capacity = purrdf_lex::allocation::growth_capacity::<T>(values.capacity(), required)
            .map_err(|error| admission.graph_error(error.into()))?;
        Memory::resume(&mut admission, bytes)
            .reserve(values, capacity)
            .map_err(|error| admission.graph_error(error.into()))
    }
}

fn symbol_kind(kind: ItemKind) -> SymbolKind {
    match kind {
        ItemKind::Fn => SymbolKind::Fn,
        ItemKind::Struct => SymbolKind::Struct,
        ItemKind::Enum => SymbolKind::Enum,
        ItemKind::Union => SymbolKind::Union,
        ItemKind::Trait => SymbolKind::Trait,
        ItemKind::TypeAlias => SymbolKind::TypeAlias,
        ItemKind::Const | ItemKind::UnnamedConst => SymbolKind::Const,
        ItemKind::Static => SymbolKind::Static,
        ItemKind::MacroRules => SymbolKind::MacroRules,
        ItemKind::ExternCrate => SymbolKind::ExternCrate,
        ItemKind::ForeignFn => SymbolKind::ForeignFn,
        ItemKind::ForeignStatic => SymbolKind::ForeignStatic,
        ItemKind::ForeignType => SymbolKind::ForeignType,
    }
}

fn main_namespace(kind: SymbolKind) -> Namespace {
    match kind {
        SymbolKind::Fn
        | SymbolKind::Const
        | SymbolKind::Static
        | SymbolKind::ForeignFn
        | SymbolKind::ForeignStatic
        | SymbolKind::InherentMethod
        | SymbolKind::TraitImplMethod
        | SymbolKind::TraitDefaultMethod
        | SymbolKind::TraitRequiredMethod
        | SymbolKind::AssocConst => Namespace::Value,
        SymbolKind::MacroRules => Namespace::Macro,
        SymbolKind::Struct
        | SymbolKind::Enum
        | SymbolKind::Union
        | SymbolKind::Trait
        | SymbolKind::TypeAlias
        | SymbolKind::Mod
        | SymbolKind::ExternCrate
        | SymbolKind::ForeignType
        | SymbolKind::AssocType => Namespace::Type,
    }
}

/// The role an item has once its module tree's test flag is counted in.
pub(crate) fn combine(own: TestRole, reached_in_tests: bool) -> TestRole {
    if own == TestRole::None && reached_in_tests {
        TestRole::CfgTest
    } else {
        own
    }
}

/// Flatten a `use` tree into entries. A `self` that has no path before it
/// (`use {self};`) names nothing and is an error, as it is in rustc.
fn flatten(tree: &UseTree, prefix: &mut Vec<String>, out: &mut Vec<UseKind>) -> Result<(), String> {
    match tree {
        UseTree::Path { name, rest } => {
            prefix.push(name.clone());
            let result = flatten(rest, prefix, out);
            prefix.pop();
            result
        }
        UseTree::Name(name) if name == "self" => {
            let last = prefix
                .last()
                .ok_or_else(|| "`use {self}` has no path before `self`".to_owned())?;
            out.push(UseKind::Named {
                name: last.clone(),
                segs: prefix.clone(),
                namespaces: NamedNamespaces::TypeOnly,
            });
            Ok(())
        }
        UseTree::Name(name) => {
            let mut segs = prefix.clone();
            segs.push(name.clone());
            out.push(UseKind::Named {
                name: name.clone(),
                segs,
                namespaces: NamedNamespaces::All,
            });
            Ok(())
        }
        UseTree::Rename { name, alias } if name == "self" => {
            if prefix.is_empty() {
                return Err("`use {self as name}` has no path before `self`".to_owned());
            }
            // `use path as _` brings a trait into scope and binds no name.
            if alias != "_" {
                out.push(UseKind::Named {
                    name: alias.clone(),
                    segs: prefix.clone(),
                    namespaces: NamedNamespaces::TypeOnly,
                });
            }
            Ok(())
        }
        UseTree::Rename { name, alias } => {
            let mut segs = prefix.clone();
            segs.push(name.clone());
            if alias != "_" {
                out.push(UseKind::Named {
                    name: alias.clone(),
                    segs,
                    namespaces: NamedNamespaces::All,
                });
            }
            Ok(())
        }
        UseTree::Glob => {
            out.push(UseKind::Glob {
                segs: prefix.clone(),
            });
            Ok(())
        }
        UseTree::Group(items) => {
            for item in items {
                flatten(item, prefix, out)?;
            }
            Ok(())
        }
    }
}

/// Everything the emit step needs to know about the file it is reading.
struct Cx<'a> {
    file: &'a RelPath,
    target: TargetId,
    reach_test: bool,
}

struct Builder<'a> {
    targets: &'a [Target],
    files_at: BTreeMap<(TargetId, &'a str), Vec<&'a SourceFile>>,
    store: Store<'a>,
    impls: Vec<ImplDecl<'a>>,
    /// The shared aliased path of each alias fact, by the fact's address in
    /// its file's facts, which outlive the build.
    aliases: HashMap<*const PathFact, Arc<PathFact>, FixedState>,
    index: Index,
}

impl<'a> Builder<'a> {
    /// The module at `path`, which a `mod` declaration in `parent` names, at
    /// `line` of `file`. A module declared more than once (under exclusive
    /// `cfg`s) is one module.
    fn declare(
        &mut self,
        path: &str,
        parent: usize,
        file: &RelPath,
        line: usize,
    ) -> Result<usize, LoadError> {
        let (path, cost) = self.store.intern(path);
        let root = self.index.modules[parent].root;
        let key = (root, path);
        if let Some(&known) = self.index.module_by_path.get(&key) {
            return Ok(known);
        }
        self.store.charge(cost + MODULE_BYTES, file, Some(line))?;
        let idx = self.index.modules.len();
        self.index.modules.push(Module {
            path: key.1.clone(),
            parent: Some(parent),
            root,
            target: self.index.modules[parent].target,
            defs: Vec::new(),
            configuration: ConfigurationDependence::Unconditional,
        });
        self.index.module_by_path.insert(key, idx);
        Ok(idx)
    }

    fn push(
        &mut self,
        fact: &ItemFact,
        kind: SymbolKind,
        path: &str,
        module: usize,
        cx: &Cx<'_>,
        documented: bool,
    ) -> Result<ItemId, LoadError> {
        self.record(fact, kind, path, cx, documented, true)
            .inspect(|id| self.index.modules[module].defs.push(*id))
    }

    /// Record an item, charging it and, when `in_scope`, its definition in
    /// its module's scope table, or else its place among the members of its
    /// type.
    fn record(
        &mut self,
        fact: &ItemFact,
        kind: SymbolKind,
        path: &str,
        cx: &Cx<'_>,
        documented: bool,
        in_scope: bool,
    ) -> Result<ItemId, LoadError> {
        let (path, path_cost) = self.store.intern(path);
        let (name, name_cost) = self.store.intern(&fact.name);
        let namespaces = if kind == SymbolKind::Struct
            && matches!(fact.shape, Some(FieldShape::Unit | FieldShape::Tuple))
        {
            2
        } else {
            1
        };
        let place = if in_scope {
            scope_bytes(&fact.name, &fact.vis, namespaces)
        } else {
            member_bytes(&fact.name)
        };
        self.store.charge(
            ITEM_BYTES + path_cost + name_cost + vis_capacity(&fact.vis) + place,
            cx.file,
            Some(fact.name_line),
        )?;
        let id = ItemId(self.index.items.len());
        self.index.items.push(Item {
            id,
            path,
            name,
            kind,
            namespace: main_namespace(kind),
            file: cx.file.clone(),
            name_line: fact.name_line,
            span: fact.span.clone(),
            body: fact.body.clone(),
            detail: fact.detail.clone(),
            visibility: fact.vis.clone(),
            documented,
            doc_hidden: fact.doc_hidden,
            test: combine(fact.test, cx.reach_test),
            target: cx.target,
            self_type: None,
            trait_key: None,
            trait_definition_target: None,
            self_key: None,
            trait_path: None,
            shape: fact.shape,
            macro_export: fact.macro_export,
        });
        Ok(id)
    }

    /// The shared copy of the aliased path of `alias`, a fact of the file, made
    /// and charged the first time any module path of the file reaches it.
    fn shared_alias(
        &mut self,
        alias: &PathFact,
        cx: &Cx<'_>,
        line: usize,
    ) -> Result<Arc<PathFact>, LoadError> {
        if let Some(shared) = self.aliases.get(&std::ptr::from_ref(alias)) {
            return Ok(Arc::clone(shared));
        }
        self.store.charge(
            shared_text(size_of::<PathFact>())
                + strings_bytes(&alias.segments)
                + hash_entry::<(*const PathFact, Arc<PathFact>)>()
                + btree_entry::<ItemId, (usize, Arc<PathFact>)>(),
            cx.file,
            Some(line),
        )?;
        let shared = Arc::new(alias.clone());
        self.aliases
            .insert(std::ptr::from_ref(alias), Arc::clone(&shared));
        Ok(shared)
    }

    fn item(&mut self, fact: &ItemFact, module: usize, cx: &Cx<'_>) -> Result<(), LoadError> {
        if fact.kind == ItemKind::UnnamedConst {
            // `const _` defines no name: it is in the facts and not in a path.
            return Ok(());
        }
        let kind = symbol_kind(fact.kind);
        let (home, base) = if fact.macro_export {
            let root = self.index.modules[module].root;
            (root, self.index.modules[root].path.clone())
        } else {
            (module, self.index.modules[module].path.clone())
        };
        let path = format!("{base}::{}", fact.name);
        let id = self.push(fact, kind, &path, home, cx, fact.documented)?;
        if home != module {
            self.store.charge(
                btree_entry::<ItemId, usize>(),
                cx.file,
                Some(fact.name_line),
            )?;
            self.index.macro_modules.insert(id, module);
        }
        if let Some(alias) = &fact.alias {
            let shared = self.shared_alias(alias, cx, fact.name_line)?;
            self.store.charge(
                btree_entry::<ItemId, (usize, Arc<PathFact>, ConfigurationDependence)>(),
                cx.file,
                Some(fact.name_line),
            )?;
            let configuration = ConfigurationDependence::of(&fact.attrs);
            self.index.aliases.insert(id, (home, shared, configuration));
        }
        if fact.kind == ItemKind::ExternCrate {
            let crate_name = fact.renamed_from.as_deref().unwrap_or(&fact.name);
            let (shared, cost) = self.store.intern(crate_name);
            self.store.charge(
                cost + btree_entry::<ItemId, SharedStr>(),
                cx.file,
                Some(fact.name_line),
            )?;
            self.index.extern_names.insert(id, shared);
            // The crates the item names: the crate itself for `self`, or every
            // library of the workspace the target's extern prelude gives the
            // name, so a path through a name of several is told apart by what
            // each of them defines, as a path through the name itself is.
            let test = fact.test != TestRole::None || cx.reach_test;
            let roots: Vec<usize> = if crate_name == "self" {
                vec![self.index.modules[module].root]
            } else {
                self.index
                    .extern_name(module, crate_name, test)
                    .map_or_default(|name| name.roots(test).collect())
            };
            if !roots.is_empty() {
                self.store.charge(
                    btree_entry::<ItemId, Vec<usize>>() + roots.capacity() * size_of::<usize>(),
                    cx.file,
                    Some(fact.name_line),
                )?;
                self.index.crate_of.insert(id, roots);
            }
        }
        if !fact.members.is_empty() {
            self.store
                .charge(MEMBERS_BYTES, cx.file, Some(fact.name_line))?;
        }
        for member in &fact.members {
            let member_kind = match (member.kind, member.body.is_some()) {
                (ItemKind::Fn, true) => SymbolKind::TraitDefaultMethod,
                (ItemKind::Fn, false) => SymbolKind::TraitRequiredMethod,
                (ItemKind::TypeAlias, _) => SymbolKind::AssocType,
                _ => SymbolKind::AssocConst,
            };
            let member_path = format!("{path}::{}", member.name);
            let member_id = self.member(member, member_kind, &member_path, cx)?;
            self.index
                .assoc
                .entry(id)
                .or_default()
                .entry(member.name.clone())
                .or_default()
                .push(member_id);
        }
        Ok(())
    }

    /// A member of a type or trait: an item that no module scope names.
    fn member(
        &mut self,
        fact: &ItemFact,
        kind: SymbolKind,
        path: &str,
        cx: &Cx<'_>,
    ) -> Result<ItemId, LoadError> {
        self.record(fact, kind, path, cx, fact.documented, false)
    }

    /// Emit a module body and the inline modules inside it, depth first, on
    /// an explicit stack: the items, then each module declaration with the
    /// body of an inline one, then the `use` declarations and the impls.
    fn body(&mut self, root: &'a ModBody, module: usize, cx: &Cx<'_>) -> Result<(), LoadError> {
        let meter = self.store.meter;
        let push = |stack: &mut WorkList<_, 8>, value, line| {
            push_item_work(stack, value, meter, cx.file, Some(line))
        };
        let mut stack = WorkList::<_, 8>::new();
        push(&mut stack, Emit::Enter(root, module, 1), 1)?;
        while let Some(step) = stack.pop() {
            match step {
                Emit::Enter(body, module, line) => {
                    for fact in &body.items {
                        self.item(fact, module, cx)?;
                    }
                    for fact in &body.unexpanded {
                        let line = Some(fact.span.lines.start);
                        let (invoked, cost) = self.store.intern(&fact.invoked);
                        self.store.charge(cost, cx.file, line)?;
                        let mut identifiers = Vec::new();
                        self.store.reserve_items(
                            &mut identifiers,
                            fact.identifiers.len(),
                            cx.file,
                            line,
                        )?;
                        for name in &fact.identifiers {
                            let (name, cost) = self.store.intern(name);
                            self.store.charge(cost, cx.file, line)?;
                            identifiers.push(name);
                        }
                        self.store.charge(vec_slot::<Unexpanded>(), cx.file, line)?;
                        self.index.unexpanded.push(Unexpanded {
                            file: cx.file.clone(),
                            span: fact.span.clone(),
                            module: self.index.modules[module].path.clone(),
                            target: cx.target,
                            invoked,
                            test: combine(fact.test, cx.reach_test),
                            identifiers,
                        });
                    }
                    self.disabled_syntax(&body.disabled, module, cx)?;
                    push(&mut stack, Emit::Rest(body, module), line)?;
                    push(&mut stack, Emit::Mods(body, module, 0), line)?;
                }
                Emit::Mods(body, module, next) => {
                    let Some(decl) = body.declaration(next) else {
                        continue;
                    };
                    push(
                        &mut stack,
                        Emit::Mods(body, module, next + 1),
                        decl.name_line,
                    )?;
                    let child = if body.is_block_local(next) {
                        self.block_module(decl, module, cx)?
                    } else {
                        self.module_item(decl, module, cx)?
                    };
                    if let Some(inline) = &decl.inline {
                        push(
                            &mut stack,
                            Emit::Enter(inline, child, decl.name_line),
                            decl.name_line,
                        )?;
                    }
                }
                Emit::Rest(body, module) => self.uses_and_impls(body, module, cx)?,
            }
        }
        Ok(())
    }

    fn disabled_syntax(
        &mut self,
        spans: &[SpanFact],
        module: usize,
        cx: &Cx<'_>,
    ) -> Result<(), LoadError> {
        let Some(first) = spans.first() else {
            return Ok(());
        };
        let line = Some(first.lines.start);
        let records = &mut self.index.disabled_syntax;
        self.store.reserve_items(
            records,
            records.len().saturating_add(spans.len()),
            cx.file,
            line,
        )?;
        self.store.meter.work(spans.len(), cx.file, line)?;
        let module = &self.index.modules[module].path;
        records.extend(spans.iter().cloned().map(|span| DisabledSyntax {
            file: cx.file.clone(),
            span,
            module: module.clone(),
            target: cx.target,
        }));
        Ok(())
    }

    /// The module of a declaration inside a block. It has no item and no name
    /// in any module scope, because no path written in source reaches it: its
    /// items are indexed under the module path of [`ModFact::block_segment`].
    fn block_module(
        &mut self,
        decl: &ModFact,
        module: usize,
        cx: &Cx<'_>,
    ) -> Result<usize, LoadError> {
        let path = format!(
            "{}::{}",
            self.index.modules[module].path,
            decl.block_segment()
        );
        let child = self.declare(&path, module, cx.file, decl.name_line)?;
        self.note_module_configuration(child, ConfigurationDependence::of(&decl.attrs));
        // One record for each declaring file: files that one module path merges
        // (the alternatives of a `cfg_attr` path) can declare the same child
        // at the same offset, and each file's items need their own site.
        self.store
            .charge(size_of::<BlockModule>(), cx.file, Some(decl.name_line))?;
        self.index.block_modules.push(BlockModule {
            module: child,
            parent: module,
            file: cx.file.clone(),
            span: (decl.span.start_byte, decl.span.end_byte),
        });
        Ok(child)
    }

    /// The module a declaration names, and its item. Returns the module.
    fn module_item(
        &mut self,
        decl: &ModFact,
        module: usize,
        cx: &Cx<'_>,
    ) -> Result<usize, LoadError> {
        let path = format!("{}::{}", self.index.modules[module].path, decl.name);
        let child = self.declare(&path, module, cx.file, decl.name_line)?;
        self.note_module_configuration(child, ConfigurationDependence::of(&decl.attrs));
        let file_docs = self
            .files_at
            .get(&(cx.target, path.as_str()))
            .is_some_and(|files| files.iter().any(|file| file.facts.documented));
        let fact = ItemFact {
            name: decl.name.clone(),
            renamed_from: None,
            kind: ItemKind::Fn,
            name_line: decl.name_line,
            span: decl.span.clone(),
            body: decl.body_span.clone(),
            detail: None,
            vis: decl.vis.clone(),
            attrs: Vec::new(),
            documented: decl.documented,
            doc_hidden: decl.doc_hidden,
            test: decl.test,
            macro_export: false,
            members: Vec::new(),
            shape: None,
            alias: None,
        };
        let id = self.push(
            &fact,
            SymbolKind::Mod,
            &path,
            module,
            cx,
            decl.documented || file_docs,
        )?;
        self.store.charge(
            btree_entry::<ItemId, usize>(),
            cx.file,
            Some(decl.name_line),
        )?;
        self.index.module_of.insert(id, child);
        Ok(child)
    }

    fn note_module_configuration(&mut self, module: usize, configuration: ConfigurationDependence) {
        if configuration == ConfigurationDependence::Conditional {
            self.index.modules[module].configuration = configuration;
        }
    }

    /// The `use` declarations and the impl blocks of one body.
    fn uses_and_impls(
        &mut self,
        body: &'a ModBody,
        module: usize,
        cx: &Cx<'_>,
    ) -> Result<(), LoadError> {
        for decl in &body.uses {
            let mut kinds = Vec::new();
            flatten(&decl.tree, &mut Vec::new(), &mut kinds).map_err(|what| {
                LoadError::new(
                    cx.file,
                    Some(decl.line),
                    LoadErrorKind::UnsupportedItem { what },
                )
            })?;
            for kind in kinds {
                let entry = UseDecl {
                    module,
                    file: cx.file.clone(),
                    line: decl.line,
                    leading_colon: decl.leading_colon,
                    vis: decl.vis.clone(),
                    test: decl.test != TestRole::None || cx.reach_test,
                    doc_hidden: decl.doc_hidden,
                    configuration: decl.configuration,
                    kind,
                };
                self.store.charge(entry.bytes(), cx.file, Some(decl.line))?;
                self.index.uses.push(entry);
            }
        }
        for fact in &body.impls {
            self.store
                .charge(vec_slot::<ImplDecl<'_>>(), cx.file, Some(fact.line))?;
            self.impls.push(ImplDecl {
                module,
                file: cx.file.clone(),
                target: cx.target,
                reach_test: cx.reach_test,
                fact,
            });
        }
        Ok(())
    }
}

/// A step of emitting a module body: its items and module declarations, a
/// declaration from position `next` on, or its imports and impls.
enum Emit<'a> {
    Enter(&'a ModBody, usize, usize),
    Mods(&'a ModBody, usize, usize),
    Rest(&'a ModBody, usize),
}

type ObservationPosition<'a> = (&'a RelPath, &'a SpanFact, &'a SharedStr, TargetId);

fn sort_observations<T>(
    meter: &Meter,
    observations: &mut [T],
    position: impl Fn(&T) -> ObservationPosition<'_>,
) -> Result<(), LoadError> {
    purrdf_lex::walk::try_sort_unstable_by(observations, |left, right| {
        let (left_file, left_span, left_module, left_target) = position(left);
        let (right_file, right_span, right_module, right_target) = position(right);
        meter.work(
            left_file
                .as_str()
                .len()
                .saturating_add(right_file.as_str().len())
                .saturating_add(left_module.len())
                .saturating_add(right_module.len())
                .saturating_add(1),
            left_file,
            Some(left_span.lines.start),
        )?;
        Ok(
            (left_file, left_span.start_byte, left_module, left_target).cmp(&(
                right_file,
                right_span.start_byte,
                right_module,
                right_target,
            )),
        )
    })
}

impl Index {
    /// An index of `targets` that holds nothing yet.
    fn empty(targets: &[Target]) -> Self {
        Self {
            items: Vec::new(),
            unexpanded: Vec::new(),
            disabled_syntax: Vec::new(),
            order: Vec::new(),
            modules: Vec::new(),
            module_by_path: BTreeMap::new(),
            block_modules: Vec::new(),
            module_of: BTreeMap::new(),
            crate_of: BTreeMap::new(),
            crate_roots: BTreeMap::new(),
            target_roots: Vec::new(),
            preludes: Vec::new(),
            targets: targets.to_vec(),
            target_editions: Vec::new(),
            target_no_std: Vec::new(),
            crates_open: false,
            unresolved: Vec::new(),
            impl_blocks: Vec::new(),
            scopes: Vec::new(),
            uses: Vec::new(),
            named_imports: Vec::new(),
            named_keys: Vec::new(),
            glob_imports: Vec::new(),
            use_resolved: Vec::new(),
            use_settled: Vec::new(),
            use_ambiguous: Vec::new(),
            use_bound: Vec::new(),
            use_free: Vec::new(),
            use_decided: Vec::new(),
            use_empty: Vec::new(),
            use_read_state: Vec::new(),
            has_late_imports: false,
            glob_closed: Vec::new(),
            glob_reach: Vec::new(),
            glob_facts: crate::resolve::GlobFactsCache::default(),
            lookups: LookupCount::default(),
            globs: GlobTables::default(),
            import_reach: ImportReach::default(),
            extern_names: BTreeMap::new(),
            root_items: BTreeMap::new(),
            macro_modules: BTreeMap::new(),
            by_source: BTreeMap::new(),
            assoc: BTreeMap::new(),
            foreign: BTreeMap::new(),
            by_file: BTreeMap::new(),
            aliases: BTreeMap::new(),
        }
    }

    /// Build the index of the module trees held by `files`, reading the files
    /// in the order of `visits`, the arrivals of the module-tree walk.
    ///
    /// # Errors
    ///
    /// Returns a [`LoadError`] for a `super` path that climbs above the crate
    /// root, for the trait of an impl that cannot be named and for records
    /// that pass the item-bytes budget of `meter`, and an `Internal`
    /// one for a visit that names no loaded file or reach, or that reaches a
    /// module before the declaration that names it, which the walk rules out.
    /// `strings` holds the module paths the walk recorded.
    pub(crate) fn build(
        targets: &[Target],
        files: &BTreeMap<RelPath, SourceFile>,
        visits: &[Visit],
        infos: &[PackageInfo],
        strings: Interner,
        meter: &Meter,
    ) -> Result<Self, LoadError> {
        let mut files_at: BTreeMap<(TargetId, &str), Vec<&SourceFile>> = BTreeMap::new();
        for file in files.values() {
            for reach in &file.reached {
                files_at
                    .entry((reach.target, reach.module_path.as_str()))
                    .or_default()
                    .push(file);
            }
        }
        let mut builder = Builder {
            targets,
            files_at,
            store: Store { strings, meter },
            impls: Vec::new(),
            aliases: HashMap::with_hasher(FixedState::new()),
            index: Index::empty(targets),
        };
        for (position, target) in builder.targets.iter().enumerate() {
            builder.ensure_root(TargetId(position), target)?;
        }
        builder.preludes(infos)?;
        let mut seen: BTreeSet<(RelPath, TargetId, SharedStr)> = BTreeSet::new();
        for visit in visits {
            let internal =
                |what: String| LoadError::new(&visit.file, None, LoadErrorKind::Internal { what });
            let file = files
                .get(&visit.file)
                .ok_or_else(|| internal("a visited file was not loaded".to_owned()))?;
            let reach = file
                .reached
                .get(visit.reach)
                .ok_or_else(|| internal(format!("the file has no module path {}", visit.reach)))?;
            let key = (file.path.clone(), reach.target, reach.module_path.clone());
            // The same file, target and module path can be reached more than
            // once (a `cfg_attr` path alternative walks an inline body again);
            // the facts are the same, so they are indexed once.
            if !seen.insert(key) {
                continue;
            }
            // A crate root is created above, and every other module by the
            // declaration that names it, which the walk reached first.
            let root = *builder
                .index
                .target_roots
                .get(reach.target.index())
                .ok_or_else(|| {
                    internal(format!("the target {} has no root", reach.target.index()))
                })?;
            let module = *builder
                .index
                .module_by_path
                .get(&(root, reach.module_path.clone()))
                .ok_or_else(|| {
                    internal(format!(
                        "the module `{}` was reached before the declaration that names it",
                        reach.module_path
                    ))
                })?;
            builder
                .note_module_configuration(module, ConfigurationDependence::of(&file.facts.attrs));
            if reach.predicate.is_some() {
                builder.note_module_configuration(module, ConfigurationDependence::Conditional);
            }
            let cx = Cx {
                file: &file.path,
                target: reach.target,
                reach_test: reach.test,
            };
            builder.body(&file.facts.body, module, &cx)?;
        }
        let Builder {
            impls,
            mut index,
            mut store,
            ..
        } = builder;
        index.add_roots(files, infos, &mut store)?;
        index.order_imports();
        index.build_scopes();
        index.settle_agreed(store.meter)?;
        index.attach_impls(impls, &mut store)?;
        sort_observations(store.meter, &mut index.unexpanded, |row| {
            (&row.file, &row.span, &row.module, row.target)
        })?;
        sort_observations(store.meter, &mut index.disabled_syntax, |row| {
            (&row.file, &row.span, &row.module, row.target)
        })?;
        index.finish();
        index.settle_glob_facts(store.meter)?;
        index.lookups_charged()?;
        Ok(index)
    }

    /// One module item for each target: its crate root, at the crate path.
    /// The root is not named inside any module, so no scope binds it; a path
    /// that is exactly a crate path finds it.
    ///
    /// # Errors
    ///
    /// Returns an `Internal` [`LoadError`] if a target's root file was not
    /// loaded or its crate root has no module, which the walk guarantees.
    fn add_roots(
        &mut self,
        files: &BTreeMap<RelPath, SourceFile>,
        infos: &[PackageInfo],
        store: &mut Store<'_>,
    ) -> Result<(), LoadError> {
        for (position, target) in self.targets.clone().iter().enumerate() {
            let internal =
                |what: String| LoadError::new(&target.root, None, LoadErrorKind::Internal { what });
            let file = files.get(&target.root).ok_or_else(|| {
                internal(format!(
                    "the root file of `{}` was not loaded",
                    target.crate_path
                ))
            })?;
            let module = *self.target_roots.get(position).ok_or_else(|| {
                internal(format!("`{}` has no crate root module", target.crate_path))
            })?;
            let id = ItemId(self.items.len());
            let lines = file.text.lines().count().max(1);
            let name = target
                .crate_path
                .rsplit("::")
                .next()
                .unwrap_or(&target.crate_path);
            let (path, path_cost) = store.intern(&target.crate_path);
            let (name, name_cost) = store.intern(name);
            store.charge(
                ITEM_BYTES
                    + path_cost
                    + name_cost
                    + btree_entry::<ItemId, usize>()
                    + btree_entry::<usize, ItemId>()
                    + vec_slot::<bool>(),
                &target.root,
                None,
            )?;
            // `#![no_std]` takes `std` out of the extern prelude; under a
            // `cfg_attr` it applies only under its predicate, so `std` stays.
            self.target_no_std.push(
                file.facts
                    .attrs
                    .iter()
                    .any(|attr| attr.path == "no_std" && attr.args.is_empty()),
            );
            let test = if infos[target.package_id.index()].configured {
                store.meter.work(file.reached.len(), &target.root, None)?;
                if file
                    .reached
                    .iter()
                    .any(|reach| reach.target == TargetId(position) && reach.test)
                {
                    TestRole::CfgTest
                } else {
                    TestRole::None
                }
            } else {
                match target.kind {
                    TargetKind::Test | TargetKind::Bench => TestRole::CfgTest,
                    TargetKind::Lib
                    | TargetKind::Bin
                    | TargetKind::Example
                    | TargetKind::BuildScript => TestRole::None,
                }
            };
            self.items.push(Item {
                id,
                path,
                name,
                kind: SymbolKind::Mod,
                namespace: Namespace::Type,
                file: file.path.clone(),
                name_line: 1,
                span: SpanFact {
                    lines: 1..lines + 1,
                    start_byte: 0,
                    end_byte: file.text.len(),
                },
                body: None,
                detail: None,
                visibility: Vis::Public,
                documented: file.facts.documented,
                doc_hidden: file.facts.doc_hidden,
                test,
                target: TargetId(position),
                self_type: None,
                trait_key: None,
                trait_definition_target: None,
                self_key: None,
                trait_path: None,
                shape: None,
                macro_export: false,
            });
            self.module_of.insert(id, module);
            self.root_items.insert(module, id);
        }
        Ok(())
    }

    /// Sort the items, the unresolved impls and the impl blocks, number the
    /// blocks in their order, and file the items.
    fn finish(&mut self) {
        self.impl_blocks.sort_by(|a, b| {
            (&a.file, a.span.start_byte, &a.module, a.target).cmp(&(
                &b.file,
                b.span.start_byte,
                &b.module,
                b.target,
            ))
        });
        for (position, block) in self.impl_blocks.iter_mut().enumerate() {
            block.id = ImplId(position);
        }
        self.unresolved.sort_unstable_by(|a, b| {
            (&a.path, &a.file, a.span.start_byte, a.target).cmp(&(
                &b.path,
                &b.file,
                b.span.start_byte,
                b.target,
            ))
        });
        let mut order: Vec<ItemId> = self.items.iter().map(|item| item.id).collect();
        order.sort_by(|a, b| self.sort_key(*a).cmp(&self.sort_key(*b)));
        self.order = order;
        for item in &self.items {
            self.by_file
                .entry(item.file.clone())
                .or_default()
                .push(item.id);
        }
        let items = &self.items;
        for id in &self.order {
            // A crate root is a whole file, not a source item inside one.
            if self.is_root(*id) {
                continue;
            }
            let item = &items[id.0];
            self.by_source
                .entry((item.file.clone(), item.span.start_byte))
                .or_default()
                .push(*id);
        }
        for ids in self.by_file.values_mut() {
            ids.sort_by(|a, b| {
                let (a, b) = (&items[a.0], &items[b.0]);
                (a.span.start_byte, &a.path, a.id).cmp(&(b.span.start_byte, &b.path, b.id))
            });
        }
    }

    /// Whether `id` is the whole-file item for its target's crate root.
    pub(crate) fn is_root(&self, id: ItemId) -> bool {
        self.module_of
            .get(&id)
            .and_then(|module| self.root_items.get(module))
            == Some(&id)
    }

    pub(crate) fn sort_key(&self, id: ItemId) -> (&str, Namespace, &RelPath, usize, usize) {
        let item = &self.items[id.0];
        (
            item.path.as_str(),
            item.namespace,
            &item.file,
            item.span.start_byte,
            item.target.index(),
        )
    }

    /// The items of `ids`, sorted and without repeats.
    pub(crate) fn sorted(&self, ids: impl IntoIterator<Item = ItemId>) -> Vec<ItemId> {
        let mut ids: Vec<ItemId> = ids.into_iter().collect();
        ids.sort_by(|a, b| self.sort_key(*a).cmp(&self.sort_key(*b)));
        ids.dedup();
        ids
    }

    /// Record a member of an impl block.
    ///
    /// # Errors
    ///
    /// Returns a [`LoadError`] naming the member's file and line when the
    /// record passes the item-bytes budget.
    #[expect(
        clippy::too_many_arguments,
        reason = "a member is built from its impl, its fact and what the impl resolved to"
    )]
    pub(crate) fn push_member(
        &mut self,
        decl: &ImplDecl<'_>,
        member: &ItemFact,
        kind: SymbolKind,
        path: &str,
        self_type: &str,
        self_key: SelfType,
        trait_key: Option<Arc<TraitKey>>,
        trait_definition_target: Option<TargetId>,
        store: &mut Store<'_>,
    ) -> Result<ItemId, LoadError> {
        let (path, path_cost) = store.intern(path);
        let (name, name_cost) = store.intern(&member.name);
        let (self_type, self_cost) = store.intern(self_type);
        let written = decl
            .fact
            .trait_path
            .as_ref()
            .map(|text| text.split_whitespace().collect::<String>());
        let (trait_path, trait_cost) = match written {
            Some(text) => {
                let (shared, cost) = store.intern(&text);
                (Some(shared), cost)
            }
            None => (None, 0),
        };
        store.charge(
            ITEM_BYTES + path_cost + name_cost + self_cost + trait_cost + vis_capacity(&member.vis),
            &decl.file,
            Some(member.name_line),
        )?;
        let id = ItemId(self.items.len());
        self.items.push(Item {
            id,
            path,
            name,
            kind,
            namespace: main_namespace(kind),
            file: decl.file.clone(),
            name_line: member.name_line,
            span: member.span.clone(),
            body: member.body.clone(),
            detail: member.detail.clone(),
            visibility: member.vis.clone(),
            documented: member.documented,
            doc_hidden: member.doc_hidden,
            test: combine(member.test, decl.reach_test),
            target: decl.target,
            self_type: Some(self_type),
            trait_key,
            trait_definition_target,
            self_key: Some(self_key),
            trait_path,
            shape: None,
            macro_export: false,
        });
        Ok(id)
    }

    /// The crate name `name` in the extern prelude of the target of `module`,
    /// for its test code when `test`; `None` when that code cannot name it.
    pub(crate) fn extern_name(&self, module: usize, name: &str, test: bool) -> Option<&ExternName> {
        let target = self.modules[module].target;
        self.preludes
            .get(target.index())?
            .get(name)
            .filter(|entry| entry.everywhere || test)
    }

    /// The edition of the package whose crate `module` is in.
    pub(crate) fn edition(&self, module: usize) -> u16 {
        self.target_editions[self.modules[module].target.index()]
    }

    /// True when the crate `module` is in has `#![no_std]`.
    pub(crate) fn no_std(&self, module: usize) -> bool {
        self.target_no_std[self.modules[module].target.index()]
    }

    /// The sysroot crate the compiler puts at the crate root of `module`'s
    /// crate: `core` under `#![no_std]`, else `std`.
    pub(crate) fn injected_crate(&self, module: usize) -> &'static str {
        if self.no_std(module) { "core" } else { "std" }
    }

    /// Sort the positions of the named imports by module, bound name and
    /// position, and those of the glob imports by module and position. Each
    /// list takes exactly its room, which every import's charge covers.
    fn order_imports(&mut self) {
        let named = self
            .uses
            .iter()
            .filter(|decl| matches!(decl.kind, UseKind::Named { .. }))
            .count();
        let mut named_imports = Vec::with_capacity(named);
        let mut glob_imports = Vec::with_capacity(self.uses.len() - named);
        for (position, decl) in self.uses.iter().enumerate() {
            match decl.kind {
                UseKind::Named { .. } => named_imports.push(position),
                UseKind::Glob { .. } => glob_imports.push(position),
            }
        }
        named_imports.sort_by(|a, b| self.named_key(*a).cmp(&self.named_key(*b)));
        glob_imports.sort_by_key(|position| (self.uses[*position].module, *position));
        let mut named_keys = Vec::with_capacity(named);
        named_keys.extend(named_imports.iter().map(|position| {
            let (module, name, _) = self.named_key(*position);
            (module, name_prefix(name))
        }));
        self.named_keys = named_keys;
        self.named_imports = named_imports;
        self.glob_imports = glob_imports;
    }

    /// The module and the name a named import binds, and its position.
    fn named_key(&self, position: usize) -> (usize, &str, usize) {
        let decl = &self.uses[position];
        let name = match &decl.kind {
            UseKind::Named { name, .. } => name.as_str(),
            UseKind::Glob { .. } => "",
        };
        (decl.module, name, position)
    }

    /// The named imports of `module` that bind `name`, in order of position.
    pub(crate) fn imports_of(&self, module: usize, name: &str) -> &[usize] {
        if self.named_imports.is_empty() {
            return &self.named_imports;
        }
        // The names are sorted, so their prefixes are too: the imports of
        // `name` are among those of its module and prefix.
        let key = (module, name_prefix(name));
        let from = self.named_keys.partition_point(|at| *at < key);
        let to = from + self.named_keys[from..].partition_point(|at| *at == key);
        let here = &self.named_imports[from..to];
        let start = here.partition_point(|position| self.named_key(*position).1 < name);
        let end = here[start..].partition_point(|position| self.named_key(*position).1 == name);
        &here[start..start + end]
    }

    /// The first two named imports that can bind `name` in the requested namespace.
    pub(crate) fn first_imports_in(
        &self,
        module: usize,
        name: &str,
        namespace: Namespace,
        steps: Steps<'_>,
    ) -> Result<[Option<usize>; 2], LoadError> {
        let mut first = None;
        for &position in self.imports_of(module, name) {
            if self.uses[position]
                .kind
                .terminal_namespaces()
                .contains(&namespace)
            {
                if first.is_some() {
                    return Ok([first, Some(position)]);
                }
                first = Some(position);
            } else {
                // Looking for zero, one or several candidates visits at most
                // two matches. Charge each skipped candidate before continuing.
                steps.storage_work(1)?;
            }
        }
        Ok([first, None])
    }

    /// What settling the tables again allocates at most beyond the bindings
    /// its imports make: the scope tables built from the definitions, with
    /// the copy of each module's definitions they are built from, and the
    /// state of every import.
    pub(crate) fn settle_bytes(&self) -> usize {
        let definitions: usize = self
            .modules
            .iter()
            .flat_map(|module| &module.defs)
            .map(|id| {
                let item = &self.items[id.0];
                let namespaces = Namespace::ALL
                    .into_iter()
                    .filter(|ns| item.in_namespace(*ns))
                    .count();
                scope_bytes(&item.name, &item.visibility, namespaces)
            })
            .sum();
        definitions
            + self.modules.len()
                * (vec_slot::<Scope>()
                    + btree_map::<String, Box<Entry>>()
                    + 2 * vec_first::<ItemId>()
                    + vec_slot::<(usize, Vec<ItemId>)>())
            + vec_first::<Scope>()
            + self.uses.len()
                * (4 * vec_slot::<bool>()
                    + 4 * vec_slot::<[bool; 3]>()
                    + vec_slot::<[ImportReadState; 3]>()
                    + vec_slot::<BTreeSet<usize>>())
            + 4 * vec_first::<bool>()
            + 4 * vec_first::<[bool; 3]>()
            + vec_first::<[ImportReadState; 3]>()
            + vec_first::<BTreeSet<usize>>()
    }

    /// The named imports of `module`, sorted by bound name and position.
    pub(crate) fn named_of(&self, module: usize) -> &[usize] {
        let start = self
            .named_imports
            .partition_point(|position| self.uses[*position].module < module);
        let end = self.named_imports[start..]
            .partition_point(|position| self.uses[*position].module == module);
        &self.named_imports[start..start + end]
    }

    /// The glob imports of `module`, in order of position.
    pub(crate) fn globs_of(&self, module: usize) -> &[usize] {
        let start = self
            .glob_imports
            .partition_point(|position| self.uses[*position].module < module);
        let end = self.glob_imports[start..]
            .partition_point(|position| self.uses[*position].module == module);
        &self.glob_imports[start..start + end]
    }

    pub(crate) fn error(decl: &ImplDecl<'_>, kind: LoadErrorKind) -> LoadError {
        LoadError::new(&decl.file, Some(decl.fact.line), kind)
    }

    pub(crate) fn path_fact(fact: &ImplFact) -> Option<PathFact> {
        fact.self_path.as_ref().map(|segments| PathFact {
            segments: segments.clone(),
            leading_colon: fact.self_leading_colon,
        })
    }
}

/// The library of each exact package, borrowing target display names.
fn library_roots<'a>(
    targets: &'a [Target],
    roots: &[usize],
    packages: usize,
    meter: &Meter,
) -> Result<Vec<Option<(usize, &'a str)>>, LoadError> {
    let mut libraries = Vec::new();
    let root = RelPath::root();
    let mut admission = ItemAdmission::new(meter, &root);
    Memory::new(&mut admission)
        .reserve(&mut libraries, packages)
        .map_err(|error| admission.error(error))?;
    libraries.resize(packages, None);
    for (position, target) in targets.iter().enumerate() {
        if target.kind == TargetKind::Lib {
            let slot = libraries
                .get_mut(target.package_id.index())
                .ok_or_else(|| {
                    LoadError::new(
                        &target.root,
                        None,
                        LoadErrorKind::Internal {
                            what: format!("the package `{}` has no manifest facts", target.package),
                        },
                    )
                })?;
            *slot = Some((roots[position], target.crate_path.as_str()));
        }
    }
    Ok(libraries)
}

/// The edition of the package of `target`. A package without facts is an
/// internal error, which discovery rules out.
fn edition_of(target: &Target, infos: &[PackageInfo]) -> Result<u16, LoadError> {
    infos
        .get(target.package_id.index())
        .map(|info| info.edition)
        .ok_or_else(|| {
            LoadError::new(
                &target.root,
                None,
                LoadErrorKind::Internal {
                    what: format!("the package `{}` has no manifest facts", target.package),
                },
            )
        })
}

fn dependency_scope(target: &Target, dependency: &DependencyInfo, id: TargetId) -> Option<bool> {
    if let Some(active) = &dependency.active_targets {
        return active.contains(&id).then_some(true);
    }
    match (target.kind, dependency.kind) {
        (TargetKind::BuildScript, DependencyKind::Build)
        | (
            TargetKind::Test | TargetKind::Bench | TargetKind::Example,
            DependencyKind::Normal | DependencyKind::Dev,
        )
        | (TargetKind::Lib | TargetKind::Bin, DependencyKind::Normal) => Some(true),
        (TargetKind::Lib | TargetKind::Bin, DependencyKind::Dev) => Some(false),
        (TargetKind::BuildScript, DependencyKind::Normal | DependencyKind::Dev)
        | (_, DependencyKind::Build) => None,
    }
}

impl Builder<'_> {
    /// Create the module that is the root of a target's crate.
    fn ensure_root(&mut self, id: TargetId, target: &Target) -> Result<usize, LoadError> {
        let idx = self.index.modules.len();
        let path = target.crate_path.as_str();
        let (shared, cost) = self.store.intern(path);
        // Its module, its entry among the crate roots and its slot among the
        // roots of the targets.
        self.store.charge(
            cost + MODULE_BYTES
                + btree_entry::<String, Vec<usize>>()
                + path.len()
                + vec_first::<usize>()
                + 2 * vec_slot::<usize>(),
            &target.root,
            None,
        )?;
        self.index.modules.push(Module {
            path: shared.clone(),
            parent: None,
            root: idx,
            target: id,
            defs: Vec::new(),
            configuration: ConfigurationDependence::Unconditional,
        });
        self.index.module_by_path.insert((idx, shared), idx);
        self.index
            .crate_roots
            .entry(path.to_owned())
            .or_default()
            .push(idx);
        self.index.target_roots.push(idx);
        Ok(idx)
    }

    /// The extern prelude and the edition of every target, and the edition of
    /// every package. A target whose package has no facts is an internal
    /// error, which discovery rules out.
    ///
    /// A target other than the library and the build script names its
    /// package's library; each target names the dependencies of its kind: the
    /// build dependencies for the build script, the normal and dev
    /// dependencies for a test, bench or example, and the normal dependencies
    /// for a library or binary, whose test code also names the dev
    /// dependencies. A dependency on a package of the workspace stands for
    /// that package's library, under its library's crate name, or under the
    /// name it is declared under when it renames its package.
    fn preludes(&mut self, infos: &[PackageInfo]) -> Result<(), LoadError> {
        let libraries = library_roots(
            self.targets,
            &self.index.target_roots,
            infos.len(),
            self.store.meter,
        )?;
        for (target_index, target) in self.targets.iter().enumerate() {
            self.store.charge(vec_slot::<u16>(), &target.root, None)?;
            self.index.target_editions.push(edition_of(target, infos)?);
            let mut names: BTreeMap<String, ExternName> = BTreeMap::new();
            let mut offer =
                |store: &Store<'_>, name: &str, root: Option<usize>, everywhere: bool| {
                    let fresh = !names.contains_key(name);
                    let pushed = root.is_some();
                    store.charge(
                        if fresh {
                            btree_entry::<String, ExternName>() + name.len()
                        } else {
                            0
                        } + if pushed {
                            vec_first::<(usize, bool)>() + vec_slot::<(usize, bool)>()
                        } else {
                            0
                        },
                        &target.root,
                        None,
                    )?;
                    let entry = names.entry(name.to_owned()).or_default();
                    entry.everywhere |= everywhere;
                    if let Some(root) = root {
                        match entry.roots.iter_mut().find(|(known, _)| *known == root) {
                            Some((_, known)) => *known |= everywhere,
                            None => entry.roots.push((root, everywhere)),
                        }
                    }
                    Ok::<(), LoadError>(())
                };
            if !matches!(target.kind, TargetKind::Lib | TargetKind::BuildScript)
                && let Some(Some((root, name))) = libraries.get(target.package_id.index())
            {
                offer(&self.store, name, Some(*root), true)?;
            }
            let dependencies = infos
                .get(target.package_id.index())
                .map_or(&[][..], |info| info.dependencies.as_slice());
            for dependency in dependencies {
                self.store.meter.work(
                    dependency.active_targets.as_ref().map_or(0, Vec::len),
                    &target.root,
                    None,
                )?;
                let Some(everywhere) = dependency_scope(target, dependency, TargetId(target_index))
                else {
                    continue;
                };
                let library = match dependency.package {
                    None => None,
                    Some(package) => libraries
                        .get(package.index())
                        .ok_or_else(|| {
                            LoadError::new(
                                &target.root,
                                None,
                                LoadErrorKind::Internal {
                                    what: format!(
                                        "dependency `{}` of `{}` names unknown package identity {}",
                                        dependency.name,
                                        target.package,
                                        package.index(),
                                    ),
                                },
                            )
                        })?
                        .as_ref(),
                };
                let name = match library {
                    Some((_, crate_name)) if !dependency.renamed => crate_name,
                    _ => dependency.name.as_str(),
                };
                offer(
                    &self.store,
                    name,
                    library.map(|(root, _)| *root),
                    everywhere,
                )?;
            }
            self.store.charge(
                vec_slot::<BTreeMap<String, ExternName>>() + btree_map::<String, ExternName>(),
                &target.root,
                None,
            )?;
            self.index.preludes.push(names);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tree::MemoryTree;
    use crate::workspace::Workspace;

    /// The targets and files of a loaded workspace, as the index takes them.
    fn parts(ws: &Workspace) -> (Vec<Target>, BTreeMap<RelPath, SourceFile>) {
        let targets: Vec<Target> = ws.targets().cloned().collect();
        let files: BTreeMap<RelPath, SourceFile> = ws
            .files()
            .map(|file| {
                (
                    file.path.clone(),
                    SourceFile {
                        path: file.path.clone(),
                        package: file.package.clone(),
                        shipping: file.shipping,
                        test: file.test,
                        text: file.text.clone(),
                        facts: file.facts.clone(),
                        reached: file.reached.clone(),
                    },
                )
            })
            .collect();
        (targets, files)
    }

    /// Build an index with the default budgets.
    fn build_index(
        targets: &[Target],
        files: &BTreeMap<RelPath, SourceFile>,
        visits: &[Visit],
        infos: &[PackageInfo],
    ) -> Result<Index, LoadError> {
        let meter = Meter::new(&crate::options::LoadOptions::default());
        Index::build(targets, files, visits, infos, Interner::default(), &meter)
    }

    /// The facts of the one package `demo`, as the index takes them.
    fn demo_infos() -> Vec<PackageInfo> {
        vec![PackageInfo {
            configured: false,
            edition: 2021,
            dependencies: Vec::new(),
        }]
    }

    fn visit(file: &str) -> Visit {
        Visit {
            file: RelPath::new(file).expect("path"),
            reach: 0,
        }
    }

    #[test]
    fn a_target_whose_root_file_is_missing_is_a_typed_internal_error() {
        let tree = MemoryTree::from([
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            ("src/lib.rs", ""),
        ]);
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let (targets, files) = parts(&ws);
        let infos = demo_infos();
        assert!(build_index(&targets, &files, &[visit("src/lib.rs")], &infos).is_ok());
        // A target whose package has no facts is an internal error too.
        let error = build_index(&targets, &files, &[visit("src/lib.rs")], &[])
            .expect_err("no package facts");
        assert!(
            matches!(&error.kind, LoadErrorKind::Internal { what } if what.contains("`demo`")),
            "{error}"
        );
        let error = build_index(&targets, &BTreeMap::new(), &[], &infos).expect_err("no root file");
        assert!(
            matches!(error.kind, LoadErrorKind::Internal { .. }),
            "{error}"
        );
        assert_eq!(error.file.as_str(), "src/lib.rs");
    }

    #[test]
    fn an_unknown_dependency_identity_is_not_an_external_or_libraryless_package() {
        let tree = MemoryTree::from([
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            ("src/lib.rs", ""),
        ]);
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let (targets, files) = parts(&ws);
        let mut infos = demo_infos();
        infos[0].dependencies.push(DependencyInfo {
            kind: DependencyKind::Normal,
            name: "dep".into(),
            renamed: true,
            package: Some(PackageId(1)),
            active_targets: None,
        });
        let error = build_index(&targets, &files, &[visit("src/lib.rs")], &infos)
            .expect_err("invalid dependency identity");
        assert!(
            matches!(&error.kind, LoadErrorKind::Internal { what }
            if what.contains("unknown package identity 1")),
            "{error}"
        );
        infos[0].dependencies[0].package = Some(PackageId(0));
        assert!(build_index(&targets, &files, &[visit("src/lib.rs")], &infos).is_ok());
        // A known package without a library remains a valid unbound extern root.
        infos.push(PackageInfo {
            configured: false,
            edition: 2021,
            dependencies: Vec::new(),
        });
        infos[0].dependencies[0].package = Some(PackageId(1));
        assert!(build_index(&targets, &files, &[visit("src/lib.rs")], &infos).is_ok());
    }

    #[test]
    fn a_module_file_visited_before_the_declaration_that_names_it_is_an_internal_error() {
        let tree = MemoryTree::from([
            ("Cargo.toml", "[package]\nname = \"demo\"\n"),
            ("src/lib.rs", "pub mod a;\n"),
            ("src/a/mod.rs", "pub mod b;\n"),
            ("src/a/b.rs", "pub fn in_b() {}\n"),
        ]);
        let ws = Workspace::load(&tree, &["."]).expect("loads");
        let (targets, files) = parts(&ws);
        let infos = demo_infos();
        // The order of the walk builds the index.
        let walked = [
            visit("src/lib.rs"),
            visit("src/a/mod.rs"),
            visit("src/a/b.rs"),
        ];
        let index = build_index(&targets, &files, &walked, &infos).expect("walk order");
        let paths: Vec<&str> = index.items.iter().map(|item| item.path.as_str()).collect();
        assert!(paths.contains(&"demo::a::b::in_b"), "{paths:?}");
        // The order of the file names reaches `b` before `a` declares it.
        let sorted: Vec<Visit> = files.keys().map(|path| visit(path.as_str())).collect();
        let error = build_index(&targets, &files, &sorted, &infos).expect_err("name order");
        assert!(
            matches!(&error.kind, LoadErrorKind::Internal { what } if what.contains("`demo::a::b`")),
            "{error}"
        );
        assert_eq!(error.file.as_str(), "src/a/b.rs");
        // A visit must name a loaded file and one of its reaches.
        for stray in [
            visit("src/missing.rs"),
            Visit {
                file: RelPath::new("src/lib.rs").expect("path"),
                reach: 1,
            },
        ] {
            let error = build_index(&targets, &files, &[stray], &infos).expect_err("stray visit");
            assert!(
                matches!(error.kind, LoadErrorKind::Internal { .. }),
                "{error}"
            );
        }
    }
}