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
// SPDX-FileCopyrightText: 2026 Blackcat Informatics® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! Impl blocks: the members of an impl are recorded under the type the impl is
//! for, under the canonical path of its trait when the type is not local, or,
//! for an inherent impl whose type the index cannot see, under the self path
//! written in its module.

#[cfg(test)]
mod tests;

use std::collections::BTreeSet;
use std::convert::Infallible;
use std::mem::size_of;
use std::sync::Arc;

use purrdf_lex::walk::{WorkList, try_dedup_by, try_sort_unstable_by};

use crate::cost::{shared_text, vec_first, vec_slot};
use crate::error::{LoadError, LoadErrorKind};
use crate::facts::{ItemKind, PathFact, TestRole};
use crate::glob_scope::push_work;
use crate::index::{
    ImplDecl, Index, MEMBERS_BYTES, Store, UseDecl, UseKind, combine, member_bytes,
};
use crate::item::{
    ImplBlock, ImplId, ItemId, Namespace, SelfType, SharedStr, SymbolKind, TraitKey, UnresolvedImpl,
};
use crate::meter::{Steps, Transient};
use crate::modtree::TargetId;
use crate::path::RelPath;
use crate::resolve::{Fail, Heads, LOAD_WALK, Walked};

/// The crates every package can name without declaring them.
const SYSROOT: [&str; 5] = ["std", "core", "alloc", "proc_macro", "test"];

/// Canonicalize candidate spellings through the native in-place operations.
fn sort_unique<T: Ord>(values: &mut Vec<T>) {
    try_sort_unstable_by(values, |left, right| Ok::<_, Infallible>(left.cmp(right)))
        .unwrap_or_else(|never| match never {});
    try_dedup_by(values, |left, right| Ok::<_, Infallible>(left == right))
        .unwrap_or_else(|never| match never {});
}

/// The traits of the standard prelude, the path they are defined at and the
/// first edition whose prelude has them. Paths are written with `std`, the
/// crate that re-exports every one of them, so `core::` and `alloc::` spellings
/// of a trait and the prelude spelling are one key.
const PRELUDE_TRAITS: [(&str, &str, u16); 31] = [
    ("AsMut", "std::convert::AsMut", 2015),
    ("AsRef", "std::convert::AsRef", 2015),
    ("Clone", "std::clone::Clone", 2015),
    ("Copy", "std::marker::Copy", 2015),
    ("Default", "std::default::Default", 2015),
    (
        "DoubleEndedIterator",
        "std::iter::DoubleEndedIterator",
        2015,
    ),
    ("Drop", "std::ops::Drop", 2015),
    ("Eq", "std::cmp::Eq", 2015),
    ("ExactSizeIterator", "std::iter::ExactSizeIterator", 2015),
    ("Extend", "std::iter::Extend", 2015),
    ("Fn", "std::ops::Fn", 2015),
    ("FnMut", "std::ops::FnMut", 2015),
    ("FnOnce", "std::ops::FnOnce", 2015),
    ("From", "std::convert::From", 2015),
    ("Into", "std::convert::Into", 2015),
    ("IntoIterator", "std::iter::IntoIterator", 2015),
    ("Iterator", "std::iter::Iterator", 2015),
    ("Ord", "std::cmp::Ord", 2015),
    ("PartialEq", "std::cmp::PartialEq", 2015),
    ("PartialOrd", "std::cmp::PartialOrd", 2015),
    ("Send", "std::marker::Send", 2015),
    ("Sized", "std::marker::Sized", 2015),
    ("Sync", "std::marker::Sync", 2015),
    ("ToOwned", "std::borrow::ToOwned", 2015),
    ("ToString", "std::string::ToString", 2015),
    ("Unpin", "std::marker::Unpin", 2015),
    ("FromIterator", "std::iter::FromIterator", 2021),
    ("TryFrom", "std::convert::TryFrom", 2021),
    ("TryInto", "std::convert::TryInto", 2021),
    ("Future", "std::future::Future", 2024),
    ("IntoFuture", "std::future::IntoFuture", 2024),
];

/// Why a trait path has no absolute form: `None` for the path itself, or the
/// glob whose crate is not one the package can name.
type Unknown = Option<Box<UseDecl>>;

/// How a path that a trait key follows is read.
#[derive(Debug, Clone, Copy)]
enum Reading {
    /// The trait path of an impl, written in code.
    Code,
    /// The path of a `use` declaration; `own` is the named import whose path
    /// it is.
    Use { own: Option<usize> },
}

impl Reading {
    /// What the first segment may name, for test code (`test`) or other code.
    fn heads(self, test: bool) -> Heads {
        match self {
            Self::Code => Heads::Code { test },
            Self::Use { own } => Heads::Use { test, own },
        }
    }

    /// The named import whose path this is.
    fn own(self) -> Option<usize> {
        match self {
            Self::Code => None,
            Self::Use { own } => own,
        }
    }
}

/// A name the search looks up in a module that does not bind it to a local
/// item.
#[derive(Debug)]
struct Prefixes {
    module: usize,
    name: String,
    /// True when the name is a whole path, so a prelude trait can stand for
    /// it.
    prelude: bool,
    /// The named import whose own path looks the name up: it is not a way
    /// the name goes.
    skip: Option<usize>,
    /// The scope of the search through globs this lookup belongs to.
    visited: usize,
    /// True for a name read from the crate root in edition 2015, which names
    /// a crate only through an `extern crate` item or as the crate the
    /// compiler puts at the root.
    root_only: bool,
}

/// What the search tracks across its frames.
struct Search<'m> {
    /// The original load admission shared by nested trait-path frames.
    steps: Steps<'m>,
    /// For each name a path looks up, the modules and names its search
    /// through globs has looked into, innermost last.
    visited: Vec<BTreeSet<(usize, String)>>,
    /// The globs whose own paths are being made absolute.
    globs: BTreeSet<usize>,
    /// The named imports whose own paths are being made absolute.
    named: BTreeSet<usize>,
    /// The globs met that are neither a local path nor a crate the impl's
    /// code can name, by written path, file and line.
    failed: BTreeSet<(String, RelPath, usize, usize)>,
}

/// A call the search makes on its explicit stack.
#[derive(Debug)]
enum Call {
    /// Make a path, written in a module, absolute.
    Absolute {
        module: usize,
        segs: Vec<String>,
        leading_colon: bool,
        reading: Reading,
    },
    /// Find what a name stands for in a module that does not bind it.
    Prefixes(Prefixes),
}

/// What a frame waits for the result of its call to go on with.
#[derive(Debug)]
enum Frame {
    /// A path whose segment looked up gives prefixes, to be followed by
    /// `tail`.
    Tail { tail: Vec<String> },
    /// A path that can go on in several modules: the paths found so far and
    /// the modules still to go through, each with `from_self`.
    Inner {
        out: Vec<Vec<String>>,
        inner: Vec<usize>,
        from_self: Vec<String>,
        reading: Reading,
    },
    /// The explicit imports of a name: what they gave so far, those still to
    /// follow and the one being followed.
    Named {
        at: Prefixes,
        named: Vec<usize>,
        out: Vec<Vec<String>>,
        position: usize,
    },
    /// A glob of local modules: what the globs gave so far, the globs and
    /// the modules of this glob still to look into.
    Target {
        at: Prefixes,
        globs: Vec<usize>,
        out: Vec<Vec<String>>,
        targets: Vec<usize>,
    },
    /// A glob of something else, whose own path is being made absolute.
    Glob {
        at: Prefixes,
        globs: Vec<usize>,
        out: Vec<Vec<String>>,
        position: usize,
    },
}

/// The next move of the search: make a call and wait in a frame, or return.
#[derive(Debug)]
enum Step {
    Call(Call, Frame),
    Return(Result<Vec<Vec<String>>, Unknown>),
    Storage(LoadError),
}

impl Index {
    /// The local structs, enums and unions that a self type path names,
    /// following type aliases.
    fn nominal_types(
        &self,
        module: usize,
        segs: &[String],
        leading_colon: bool,
        heads: Heads,
        steps: Steps<'_>,
    ) -> Result<Vec<ItemId>, LoadError> {
        let mut pending = WorkList::<_, 8>::new();
        let push = |pending: &mut WorkList<_, 8>, module, path: &[String], colon| {
            let text = path.iter().map(String::len).sum::<usize>();
            steps.reserve(vec_first::<String>() + path.len() * vec_slot::<String>() + text)?;
            steps.storage_work(path.len() + text)?;
            push_work(pending, (module, path.to_vec(), colon), steps)
        };
        push(&mut pending, module, segs, leading_colon)?;
        // Aliases can point at each other. A path that has been walked once
        // adds nothing the first walk did not, so the guard ends the cycle
        // and the caller reports a self type that names no type.
        let mut visited: BTreeSet<(usize, Vec<String>)> = BTreeSet::new();
        let mut found = BTreeSet::new();
        while let Some((at, path, colon)) = pending.pop() {
            if !visited.insert((at, path.clone())) {
                continue;
            }
            let walked = match self.walk(at, &path, colon, Namespace::Type, heads, steps) {
                Ok(walked) => walked,
                // A path that names nothing names no type.
                Err(
                    Fail::Missing(_)
                    | Fail::SuperAboveRoot
                    | Fail::SeveralCrates { .. }
                    | Fail::Ambiguous(_),
                ) => {
                    continue;
                }
                Err(Fail::Budget(_)) => unreachable!("{LOAD_WALK}"),
                Err(Fail::Storage(error)) => return Err(error),
            };
            for id in walked.items.keys() {
                match self.items[id.0].kind {
                    SymbolKind::Struct | SymbolKind::Enum | SymbolKind::Union => {
                        found.insert(*id);
                    }
                    SymbolKind::TypeAlias => {
                        if let Some((home, alias, _)) = self.aliases.get(id) {
                            push(&mut pending, *home, &alias.segments, alias.leading_colon)?;
                        }
                    }
                    // These name something, but not a type an impl can add
                    // members to.
                    SymbolKind::Fn
                    | SymbolKind::Trait
                    | SymbolKind::Const
                    | SymbolKind::Static
                    | SymbolKind::Mod
                    | SymbolKind::MacroRules
                    | SymbolKind::ExternCrate
                    | SymbolKind::ForeignFn
                    | SymbolKind::ForeignStatic
                    | SymbolKind::ForeignType
                    | SymbolKind::InherentMethod
                    | SymbolKind::TraitImplMethod
                    | SymbolKind::TraitDefaultMethod
                    | SymbolKind::TraitRequiredMethod
                    | SymbolKind::AssocConst
                    | SymbolKind::AssocType => {}
                }
            }
        }
        Ok(self.sorted(found))
    }

    /// True when the impl is test code.
    fn test_code(decl: &ImplDecl<'_>) -> bool {
        decl.reach_test || decl.fact.test != TestRole::None
    }

    /// True when `name` is a crate the impl's code can name: a sysroot crate
    /// or a crate of its target's extern prelude.
    fn crate_known(&self, decl: &ImplDecl<'_>, name: &str) -> bool {
        SYSROOT.contains(&name)
            || self
                .extern_name(decl.module, name, Self::test_code(decl))
                .is_some()
    }

    /// The readings of an explicit import's path, written in `module`, whose
    /// first segment a glob of the module brings in from an import outside
    /// the index and that is also a crate of the extern prelude: rustc's
    /// E0659, so the path through the crate and the path through each such
    /// import are candidates. `None` when the first segment is not such.
    fn carried_readings(
        &self,
        decl: &ImplDecl<'_>,
        module: usize,
        segs: &[String],
        steps: Steps<'_>,
    ) -> Result<Option<Vec<Vec<String>>>, LoadError> {
        let Some((head, rest)) = segs.split_first() else {
            return Ok(None);
        };
        if self.edition(module) == 2015 || !self.in_use_prelude(module, head, Self::test_code(decl))
        {
            return Ok(None);
        }
        let carried = self.globbed_outside(module, head, steps)?;
        if carried.is_empty() {
            return Ok(None);
        }
        let mut out: Vec<Vec<String>> = Vec::new();
        if let Some(real) = self.crate_reading(decl, module, head) {
            let mut path = vec![real];
            path.extend(rest.iter().cloned());
            out.push(path);
        }
        for position in carried {
            let (Some(real), UseKind::Named { segs: through, .. }) = (
                self.read_outside_crate(position, steps)
                    .map_err(crate::settle::storage_failure)?,
                &self.uses[position].kind,
            ) else {
                continue;
            };
            let mut path = vec![real];
            path.extend(through.iter().skip(1).cloned());
            path.extend(rest.iter().cloned());
            out.push(path);
        }
        Ok(Some(out))
    }

    /// The key a walk to local items gives: their path when they are at one
    /// (`cfg` alternatives are one trait), every path as a candidate when
    /// they are at several, never the first of them; `None` for no item.
    fn walked_key(
        &self,
        walked: &Walked,
        written: impl Fn() -> String,
    ) -> Option<(TraitKey, Option<TargetId>)> {
        let first_target = walked.items.keys().next().map(|id| self.items[id.0].target);
        let one_target = walked
            .items
            .keys()
            .all(|id| Some(self.items[id.0].target) == first_target);
        let definition_target = first_target.filter(|_| {
            walked
                .items
                .keys()
                .all(|id| self.items[id.0].kind == SymbolKind::Trait)
        });
        let mut paths: Vec<String> = self
            .sorted(walked.items.keys().copied())
            .iter()
            .map(|id| self.items[id.0].path.to_string())
            .collect();
        sort_unique(&mut paths);
        match (paths.len(), one_target) {
            (0, _) => None,
            (1, true) => Some((TraitKey::Canonical(paths.remove(0)), definition_target)),
            _ => Some((
                TraitKey::Unresolved {
                    written: written(),
                    candidates: paths,
                },
                None,
            )),
        }
    }

    /// The crate that `name`, the first segment of a `use` path in `module`,
    /// stands for as a crate of the extern prelude: a crate the impl's code
    /// can name, or the crate an `extern crate` item at the crate root names.
    fn crate_reading(&self, decl: &ImplDecl<'_>, module: usize, name: &str) -> Option<String> {
        if self.crate_known(decl, name) {
            return Some(name.to_owned());
        }
        let root = self.modules[module].root;
        self.modules[root]
            .defs
            .iter()
            .filter(|id| {
                self.items[id.0].kind == SymbolKind::ExternCrate && self.items[id.0].name == name
            })
            .filter_map(|id| self.extern_names.get(id))
            .find(|real| self.crate_known(decl, real))
            .map(ToString::to_string)
    }

    /// The path of the standard prelude trait `name` for the edition of the
    /// impl's package; `None` if the name is not in that edition's prelude.
    fn prelude_trait(&self, decl: &ImplDecl<'_>, name: &str) -> Option<&'static str> {
        let edition = self.target_editions[decl.target.index()];
        PRELUDE_TRAITS
            .iter()
            .find(|(trait_name, _, first)| *trait_name == name && *first <= edition)
            .map(|(_, path, _)| *path)
    }

    /// Every absolute path that `segs`, written in `module` and read as
    /// `reading` says, could stand for. The head of each is a crate the
    /// impl's code can name, or the path is in the impl's own crate where the
    /// index cannot see; a path that has neither is an error.
    ///
    /// The search follows explicit imports, `extern crate` items and globs
    /// from module to module. It runs on an explicit stack of [`Frame`]s, so
    /// its depth on the caller's stack does not grow with the input. An
    /// import never resolves through its own binding, a glob whose own path
    /// is being made absolute provides nothing to that path, and an explicit
    /// import met again while its own path is being made absolute is a cycle,
    /// which is an error.
    fn absolute(
        &self,
        decl: &ImplDecl<'_>,
        module: usize,
        segs: &[String],
        leading_colon: bool,
        reading: Reading,
        steps: Steps<'_>,
    ) -> Result<Result<Vec<Vec<String>>, Unknown>, LoadError> {
        let mut search = Search {
            steps,
            visited: Vec::new(),
            globs: BTreeSet::new(),
            named: BTreeSet::new(),
            failed: BTreeSet::new(),
        };
        let mut stack = WorkList::<Frame, 8>::new();
        let mut step = self.enter_absolute(
            decl,
            &mut search,
            module,
            segs.to_vec(),
            leading_colon,
            reading,
        );
        loop {
            step = match step {
                Step::Call(call, frame) => {
                    push_work(&mut stack, frame, steps)?;
                    match call {
                        Call::Absolute {
                            module,
                            segs,
                            leading_colon,
                            reading,
                        } => self.enter_absolute(
                            decl,
                            &mut search,
                            module,
                            segs,
                            leading_colon,
                            reading,
                        ),
                        Call::Prefixes(prefixes) => {
                            self.enter_prefixes(decl, &mut search, prefixes)
                        }
                    }
                }
                Step::Return(result) => match stack.pop() {
                    // A glob that names nothing fails the path: the error
                    // names the first such glob by written path, file and
                    // line, whatever order the search met them in.
                    None => {
                        return Ok(match search.failed.first() {
                            Some((.., position)) if !matches!(result, Err(Some(_))) => {
                                Err(Some(Box::new(self.uses[*position].clone())))
                            }
                            _ => result,
                        });
                    }
                    Some(frame) => self.resume(decl, &mut search, frame, result),
                },
                Step::Storage(error) => return Err(error),
            };
        }
    }

    /// The module a path written in `module` is read from, and the index of
    /// its first segment to look up there: the crate root for a path read
    /// from it (`crate_relative`) or one that starts with `crate`, the module
    /// itself after `self` or for a plain name, and the module above for each
    /// `super`; `None` for `super` above the crate root.
    fn path_start(
        &self,
        module: usize,
        segs: &[String],
        crate_relative: bool,
    ) -> Option<(usize, usize)> {
        if crate_relative {
            return Some((self.modules[module].root, 0));
        }
        match segs.first().map(String::as_str) {
            Some("crate") => Some((self.modules[module].root, 1)),
            Some("self") => Some((module, 1)),
            Some("super") => {
                let mut cur = module;
                let mut at = 0;
                while segs.get(at).is_some_and(|s| s == "super") {
                    cur = self.modules[cur].parent?;
                    at += 1;
                }
                Some((cur, at))
            }
            _ => Some((module, 0)),
        }
    }

    /// Start making `segs`, written in `module`, absolute.
    fn enter_absolute(
        &self,
        decl: &ImplDecl<'_>,
        search: &mut Search<'_>,
        module: usize,
        segs: Vec<String>,
        leading_colon: bool,
        reading: Reading,
    ) -> Step {
        let Some(head) = segs.first() else {
            return Step::Return(Err(None));
        };
        let heads = reading.heads(Self::test_code(decl));
        let crate_relative = self.crate_relative(module, head, leading_colon, heads);
        if leading_colon && !crate_relative {
            return Step::Return(if self.crate_known(decl, head) {
                Ok(vec![segs])
            } else {
                Err(None)
            });
        }
        let Some((mut cur, mut at)) = self.path_start(module, &segs, crate_relative) else {
            return Step::Return(Err(None));
        };
        while at < segs.len() {
            let seg = &segs[at];
            let lookup =
                match self.lookup_in_read(cur, Namespace::Type, seg, reading.own(), search.steps) {
                    Ok(lookup) => lookup,
                    Err(error) => return Step::Storage(crate::settle::storage_failure(error)),
                };
            if let Some((bound, from_glob)) = lookup {
                // Every item the name is bound to is a way the path can go:
                // an `extern crate` item stands for the crate it names, a
                // module the path goes on through, and a local trait at the
                // end of the path is a candidate under its own path (which
                // only a path an ambiguous first segment leaves open meets:
                // anything bound locally otherwise resolved the trait
                // already). Several ways give several candidates, never the
                // first of them.
                let rest = &segs[at + 1..];
                let mut out = Vec::new();
                let mut inner: BTreeSet<usize> = BTreeSet::new();
                for id in bound.keys() {
                    let item = &self.items[id.0];
                    if let Some(real) = self.extern_names.get(id) {
                        if !self.crate_known(decl, real) {
                            return Step::Return(Err(None));
                        }
                        let mut path = vec![real.to_string()];
                        path.extend(rest.iter().cloned());
                        out.push(path);
                    } else if rest.is_empty() && item.kind == SymbolKind::Trait {
                        out.push(item.path.split("::").map(str::to_owned).collect());
                    } else {
                        inner.extend(self.modules_for(*id));
                    }
                }
                // The first segment of a `use` path of edition 2018 or later
                // that a glob binds and that is also a different crate of the
                // extern prelude is ambiguous: the path through the crate is
                // a candidate too.
                if let (0, true, Reading::Use { .. }) = (at, from_glob, reading)
                    && !crate_relative
                    && self
                        .glob_against_prelude(cur, seg, Self::test_code(decl), &bound)
                        .is_some()
                    && let Some(real) = self.crate_reading(decl, cur, seg)
                {
                    let mut path = vec![real];
                    path.extend(rest.iter().cloned());
                    out.push(path);
                }
                if rest.is_empty() {
                    // A path that ends at a module names no trait; one that
                    // ends at an `extern crate` item names its crate.
                    return Step::Return(if out.is_empty() { Err(None) } else { Ok(out) });
                }
                if out.is_empty()
                    && let [only] = inner.iter().copied().collect::<Vec<_>>().as_slice()
                {
                    cur = *only;
                    at += 1;
                    continue;
                }
                let mut from_self = vec!["self".to_owned()];
                from_self.extend(rest.iter().cloned());
                return Self::next_inner(
                    out,
                    inner.into_iter().rev().collect(),
                    from_self,
                    reading,
                );
            }
            if let (0, Reading::Use { own: Some(_) }) = (at, reading)
                && !crate_relative
            {
                match self.carried_readings(decl, cur, &segs, search.steps) {
                    Ok(Some(out)) => return Step::Return(Ok(out)),
                    Ok(None) => {}
                    Err(error) => return Step::Storage(error),
                }
            }
            // The scope of the search through the module's globs, fresh for
            // each name a path looks up.
            search.visited.push(BTreeSet::new());
            let prefixes = Prefixes {
                module: cur,
                name: seg.clone(),
                prelude: segs.len() == 1,
                skip: reading.own(),
                visited: search.visited.len() - 1,
                root_only: crate_relative && at == 0,
            };
            return Step::Call(
                Call::Prefixes(prefixes),
                Frame::Tail {
                    tail: segs[at + 1..].to_vec(),
                },
            );
        }
        Step::Return(Err(None))
    }

    /// Go on through the next of the `inner` modules a path can go on in, or
    /// return what the ways found.
    fn next_inner(
        out: Vec<Vec<String>>,
        mut inner: Vec<usize>,
        from_self: Vec<String>,
        reading: Reading,
    ) -> Step {
        let Some(module) = inner.pop() else {
            return Step::Return(if out.is_empty() { Err(None) } else { Ok(out) });
        };
        Step::Call(
            Call::Absolute {
                module,
                segs: from_self.clone(),
                leading_colon: false,
                reading,
            },
            Frame::Inner {
                out,
                inner,
                from_self,
                reading,
            },
        )
    }

    /// Start finding the absolute paths a name that the module does not bind
    /// to a local item stands for: what its explicit imports say (but the one
    /// whose own path asks), the name of a declared crate, or what its globs
    /// could provide. A glob of a local module is looked into; a glob of
    /// anything else is a candidate that cannot be confirmed.
    fn enter_prefixes(&self, decl: &ImplDecl<'_>, search: &mut Search<'_>, at: Prefixes) -> Step {
        let named: Vec<usize> = self
            .imports_of(at.module, &at.name)
            .iter()
            .copied()
            .filter(|position| Some(*position) != at.skip)
            .rev()
            .collect();
        if !named.is_empty() {
            return self.next_named(search, at, named, Vec::new());
        }
        // Every `extern crate` item of the name stands for its crate (`cfg`
        // alternatives can name two), never the first of them.
        let crates: Vec<&SharedStr> = self.modules[at.module]
            .defs
            .iter()
            .filter(|id| {
                self.items[id.0].kind == SymbolKind::ExternCrate && self.items[id.0].name == at.name
            })
            .filter_map(|id| self.extern_names.get(id))
            .collect();
        if !crates.is_empty() {
            return Step::Return(if crates.iter().all(|real| self.crate_known(decl, real)) {
                Ok(crates.iter().map(|real| vec![real.to_string()]).collect())
            } else {
                Err(None)
            });
        }
        // The name of a crate this package can name stands for that crate. A
        // name read from the crate root in edition 2015 names only the crate
        // the compiler puts there; any other crate needs an `extern crate`
        // item.
        let crate_named = if at.root_only {
            at.name == self.injected_crate(at.module)
        } else {
            self.crate_known(decl, &at.name)
        };
        if crate_named {
            return Step::Return(Ok(vec![vec![at.name]]));
        }
        if search.visited[at.visited].insert((at.module, at.name.clone())) {
            let globs: Vec<usize> = self
                .globs_of(at.module)
                .iter()
                .copied()
                .filter(|position| !search.globs.contains(position))
                .rev()
                .collect();
            return self.next_glob(decl, search, at, globs, Vec::new());
        }
        Step::Return(Ok(self.with_prelude(decl, &at, Vec::new())))
    }

    /// Make the path of the next of the `named` imports absolute, or return
    /// what they gave.
    fn next_named(
        &self,
        search: &mut Search<'_>,
        at: Prefixes,
        mut named: Vec<usize>,
        out: Vec<Vec<String>>,
    ) -> Step {
        // An import met again while its own path is being made absolute adds
        // nothing to this way, as a glob met again does: a cycle of imports
        // binds nothing, and a name it alone could give is not found.
        let position = loop {
            let Some(position) = named.pop() else {
                return Step::Return(Ok(out));
            };
            if search.named.insert(position) {
                break position;
            }
        };
        let u = &self.uses[position];
        let UseKind::Named { segs, .. } = &u.kind else {
            return Step::Return(Err(None));
        };
        Step::Call(
            Call::Absolute {
                module: at.module,
                segs: segs.clone(),
                leading_colon: u.leading_colon,
                reading: Reading::Use {
                    own: Some(position),
                },
            },
            Frame::Named {
                at,
                named,
                out,
                position,
            },
        )
    }

    /// Look into the next of the `globs` of the module, or return what they
    /// gave with the prelude trait of the name.
    fn next_glob(
        &self,
        decl: &ImplDecl<'_>,
        search: &mut Search<'_>,
        at: Prefixes,
        mut globs: Vec<usize>,
        out: Vec<Vec<String>>,
    ) -> Step {
        while let Some(position) = globs.pop() {
            let u = &self.uses[position];
            let UseKind::Glob { segs } = &u.kind else {
                continue;
            };
            let targets = match self.glob_targets(position, search.steps) {
                Err(Fail::Storage(error)) => return Step::Storage(error),
                targets => targets,
            };
            let local_enum = match &targets {
                Ok(targets) if targets.is_empty() => {
                    match self.globs_local_enum(u, segs, search.steps) {
                        Ok(local_enum) => local_enum,
                        Err(error) => return Step::Storage(error),
                    }
                }
                _ => false,
            };
            match targets {
                // A glob of a local enum brings in its variants, in the type
                // and the value name spaces. A variant is neither a trait nor
                // a module, so the glob gives no prefix.
                Ok(targets) if targets.is_empty() && local_enum => {}
                Ok(targets) if !targets.is_empty() => {
                    return self.next_target(
                        decl,
                        search,
                        at,
                        globs,
                        out,
                        targets.into_iter().rev().collect(),
                    );
                }
                // A glob that names no local module: a dependency, if the
                // crate is one this package can name, or a path in the crate
                // that the index cannot see.
                _ => {
                    search.globs.insert(position);
                    return Step::Call(
                        Call::Absolute {
                            module: at.module,
                            segs: segs.clone(),
                            leading_colon: u.leading_colon,
                            reading: Reading::Use { own: None },
                        },
                        Frame::Glob {
                            at,
                            globs,
                            out,
                            position,
                        },
                    );
                }
            }
        }
        let out = self.with_prelude(decl, &at, out);
        Step::Return(Ok(out))
    }

    /// Look for the name in the next of the `targets` of a glob of local
    /// modules, or go on with the next glob.
    fn next_target(
        &self,
        decl: &ImplDecl<'_>,
        search: &mut Search<'_>,
        at: Prefixes,
        globs: Vec<usize>,
        out: Vec<Vec<String>>,
        mut targets: Vec<usize>,
    ) -> Step {
        let Some(target) = targets.pop() else {
            return self.next_glob(decl, search, at, globs, out);
        };
        let call = Prefixes {
            module: target,
            name: at.name.clone(),
            prelude: at.prelude,
            skip: None,
            visited: at.visited,
            root_only: at.root_only,
        };
        Step::Call(
            Call::Prefixes(call),
            Frame::Target {
                at,
                globs,
                out,
                targets,
            },
        )
    }

    /// `out` with the path of the prelude trait `at` names, when the name is
    /// a whole path and in the prelude of the impl's edition.
    fn with_prelude(
        &self,
        decl: &ImplDecl<'_>,
        at: &Prefixes,
        mut out: Vec<Vec<String>>,
    ) -> Vec<Vec<String>> {
        if let (true, Some(path)) = (at.prelude, self.prelude_trait(decl, &at.name)) {
            out.push(path.split("::").map(str::to_owned).collect());
        }
        out
    }

    /// Go on with `frame` now that the call it made returned `result`.
    fn resume(
        &self,
        decl: &ImplDecl<'_>,
        search: &mut Search<'_>,
        frame: Frame,
        result: Result<Vec<Vec<String>>, Unknown>,
    ) -> Step {
        match frame {
            Frame::Tail { tail } => {
                search.visited.pop();
                Step::Return(result.and_then(|prefixes| {
                    if prefixes.is_empty() {
                        return Err(None);
                    }
                    Ok(prefixes
                        .into_iter()
                        .map(|mut prefix| {
                            prefix.extend(tail.iter().cloned());
                            prefix
                        })
                        .collect())
                }))
            }
            Frame::Inner {
                mut out,
                inner,
                from_self,
                reading,
            } => match result {
                Ok(paths) => {
                    out.extend(paths);
                    Self::next_inner(out, inner, from_self, reading)
                }
                Err(bad) => Step::Return(Err(bad)),
            },
            Frame::Named {
                at,
                named,
                mut out,
                position,
            } => {
                search.named.remove(&position);
                match result {
                    Ok(paths) => {
                        out.extend(paths);
                        self.next_named(search, at, named, out)
                    }
                    Err(bad) => Step::Return(Err(bad)),
                }
            }
            Frame::Target {
                at,
                globs,
                mut out,
                targets,
            } => match result {
                Ok(paths) => {
                    out.extend(paths);
                    self.next_target(decl, search, at, globs, out, targets)
                }
                Err(bad) => Step::Return(Err(bad)),
            },
            Frame::Glob {
                at,
                globs,
                mut out,
                position,
            } => {
                search.globs.remove(&position);
                let u = &self.uses[position];
                let UseKind::Glob { segs } = &u.kind else {
                    return Step::Return(Err(None));
                };
                let bases = match result {
                    Ok(bases) => bases,
                    Err(None) => {
                        // A glob of a path in the crate that names nothing
                        // the index can see (a module or an enum a macro
                        // generates): a candidate that cannot be confirmed,
                        // under that path.
                        let bases = match self.unseen_local(
                            u.module,
                            segs,
                            u.leading_colon,
                            u.test,
                            search.steps,
                        ) {
                            Ok(bases) => bases,
                            Err(error) => return Step::Storage(error),
                        };
                        if bases.is_empty() {
                            // A glob of something that is neither a local
                            // path nor a crate the package can name fails the
                            // path; the search goes on, so that the error
                            // names one glob whatever the order.
                            search.failed.insert((
                                format!("{}::*", segs.join("::")),
                                u.file.clone(),
                                u.line,
                                position,
                            ));
                        }
                        bases
                    }
                    Err(inner) => return Step::Return(Err(inner)),
                };
                for mut base in bases {
                    base.push(at.name.clone());
                    out.push(base);
                }
                self.next_glob(decl, search, at, globs, out)
            }
        }
    }

    /// Candidate spellings when one crate name selects several indexed roots.
    fn trait_candidates(&self, roots: &[ItemId], tr: &PathFact, rest: usize) -> Vec<String> {
        let mut candidates: Vec<String> = roots
            .iter()
            .map(|root| {
                let mut path = self.items[root.0].path.to_string();
                for segment in tr.segments.iter().skip(rest) {
                    path.push_str("::");
                    path.push_str(segment);
                }
                path
            })
            .collect();
        sort_unique(&mut candidates);
        candidates
    }

    /// The key of the trait of an impl that is not on a local type: a local
    /// trait at its definition, a dependency trait at its absolute path, or an
    /// explicit unresolved key when globs of dependencies leave the path open.
    fn trait_key(
        &self,
        decl: &ImplDecl<'_>,
        tr: &PathFact,
        meter: &crate::meter::Meter,
    ) -> Result<(TraitKey, Option<TargetId>), LoadError> {
        let memory = Transient::new(meter);
        let steps = Steps::LoadAt {
            memory: &memory,
            file: &decl.file,
            line: decl.fact.line,
        };
        let unresolved = || {
            Index::error(
                decl,
                LoadErrorKind::UnresolvedTrait {
                    path: tr.segments.join("::"),
                },
            )
        };
        let written = || {
            format!(
                "{}{}",
                if tr.leading_colon { "::" } else { "" },
                tr.segments.join("::")
            )
        };
        match self.walk(
            decl.module,
            &tr.segments,
            tr.leading_colon,
            Namespace::Type,
            Heads::Code {
                test: Self::test_code(decl),
            },
            steps,
        ) {
            Ok(walked) => {
                if let Some(key) = self.walked_key(&walked, written) {
                    return Ok(key);
                }
            }
            // A crate name that stands for several libraries: the trait is in
            // one of them, and the key lists the path in each.
            Err(Fail::SeveralCrates { roots, rest }) => {
                return Ok((
                    TraitKey::Unresolved {
                        written: written(),
                        candidates: self.trait_candidates(&roots, tr, rest),
                    },
                    None,
                ));
            }
            // A path in code is never ambiguous at its first segment.
            Err(Fail::Missing(_) | Fail::SuperAboveRoot | Fail::Ambiguous(_)) => {}
            Err(Fail::Budget(_)) => unreachable!("{LOAD_WALK}"),
            Err(Fail::Storage(error)) => return Err(error),
        }
        let paths = self
            .absolute(
                decl,
                decl.module,
                &tr.segments,
                tr.leading_colon,
                Reading::Code,
                steps,
            )?
            .map_err(|bad| match bad {
                None => unresolved(),
                Some(glob) => LoadError::new(
                    &glob.file,
                    Some(glob.line),
                    LoadErrorKind::UnresolvedTrait {
                        path: match &glob.kind {
                            UseKind::Glob { segs } | UseKind::Named { segs, .. } => {
                                format!("{}::*", segs.join("::"))
                            }
                        },
                    },
                ),
            })?;
        // A candidate is a path of a crate the impl's code can name, or a path
        // in the impl's own crate that the index cannot see.
        let own = &self.modules[self.modules[decl.module].root].path;
        let in_own_crate = |path: &[String]| {
            path.join("::")
                .strip_prefix(own.as_str())
                .is_some_and(|rest| rest.starts_with("::"))
        };
        let mut candidates: Vec<String> = paths
            .into_iter()
            .filter(|path| self.crate_known(decl, &path[0]) || in_own_crate(path))
            .map(|mut path| {
                // `core` and `alloc` define what `std` re-exports under the
                // same path, so the three spellings are one key.
                if matches!(path[0].as_str(), "core" | "alloc") {
                    "std".clone_into(&mut path[0]);
                }
                path.join("::")
            })
            .collect();
        sort_unique(&mut candidates);
        match candidates.len() {
            0 => Err(unresolved()),
            1 => Ok((TraitKey::Canonical(candidates.remove(0)), None)),
            _ => Ok((
                TraitKey::Unresolved {
                    written: written(),
                    candidates,
                },
                None,
            )),
        }
    }

    fn super_check_impl(&self, decl: &ImplDecl<'_>, path: &PathFact) -> Result<(), LoadError> {
        let skip = usize::from(path.segments.first().is_some_and(|s| s == "self"));
        let supers = path
            .segments
            .iter()
            .skip(skip)
            .take_while(|s| *s == "super")
            .count();
        if !path.leading_colon && supers > self.module_depth(decl.module) {
            return Err(Index::error(
                decl,
                LoadErrorKind::SuperAboveRoot {
                    path: path.segments.join("::"),
                },
            ));
        }
        Ok(())
    }

    /// The structs, enums and unions of the workspace that the self type of
    /// an impl names; none for a self type that has no path or is one of the
    /// impl's generic parameters.
    fn local_types(
        &self,
        decl: &ImplDecl<'_>,
        own: Option<&PathFact>,
        meter: &crate::meter::Meter,
    ) -> Result<Vec<ItemId>, LoadError> {
        let memory = Transient::new(meter);
        let steps = Steps::LoadAt {
            memory: &memory,
            file: &decl.file,
            line: decl.fact.line,
        };
        match own {
            Some(path)
                if !(path.segments.len() == 1
                    && decl.fact.generics.contains(&path.segments[0])) =>
            {
                self.super_check_impl(decl, path)?;
                self.nominal_types(
                    decl.module,
                    &path.segments,
                    path.leading_colon,
                    Heads::Code {
                        test: Self::test_code(decl),
                    },
                    steps,
                )
            }
            _ => Ok(Vec::new()),
        }
    }

    /// Attach the members of every impl block, charging each member to the
    /// item-bytes budget.
    pub(crate) fn attach_impls(
        &mut self,
        impls: Vec<ImplDecl<'_>>,
        store: &mut Store<'_>,
    ) -> Result<(), LoadError> {
        for decl in impls {
            let fact = decl.fact;
            let own = Index::path_fact(fact);
            let local = self.local_types(&decl, own.as_ref(), store.meter())?;
            let self_type: String = fact.self_type.split_whitespace().collect();
            if fact.trait_segments.is_none() && local.is_empty() {
                let members = self.attach_unresolved(&decl, own.as_ref(), &self_type, store)?;
                self.record_block(&decl, &self_type, local, members, store)?;
                self.settle_impl_lookups(store, &decl)?;
                continue;
            }
            let (trait_key, trait_definition_target) =
                match (&fact.trait_segments, local.is_empty()) {
                    (Some(tr), true) => {
                        let (key, target) = self.trait_key(&decl, tr, store.meter())?;
                        (Some(Arc::new(key)), target)
                    }
                    _ => (None, None),
                };
            self.settle_impl_lookups(store, &decl)?;
            if let Some(key) = &trait_key {
                Self::charge_trait_key(key, &decl, store)?;
            }
            let anchor = local.first().map(|id| self.items[id.0].path.clone());
            let mut members = Vec::new();
            store.reserve_items(&mut members, fact.items.len(), &decl.file, Some(fact.line))?;
            for member in &fact.items {
                let kind = match (member.kind, fact.trait_segments.is_some()) {
                    (ItemKind::Fn, false) => SymbolKind::InherentMethod,
                    (ItemKind::Fn, true) => SymbolKind::TraitImplMethod,
                    (ItemKind::TypeAlias, _) => SymbolKind::AssocType,
                    _ => SymbolKind::AssocConst,
                };
                let (path, self_key) = match (&anchor, trait_key.as_deref()) {
                    (Some(base), _) => (format!("{base}::{}", member.name), SelfType::Local),
                    (None, Some(TraitKey::Canonical(key))) => {
                        (format!("{key}::{}", member.name), SelfType::Trait)
                    }
                    (None, Some(TraitKey::Unresolved { written, .. })) => {
                        (format!("{written}::{}", member.name), SelfType::Trait)
                    }
                    (None, None) => {
                        return Err(Index::error(
                            &decl,
                            LoadErrorKind::Internal {
                                what: "an impl without a local type or a trait was attached"
                                    .to_owned(),
                            },
                        ));
                    }
                };
                let id = self.push_member(
                    &decl,
                    member,
                    kind,
                    &path,
                    &self_type,
                    self_key,
                    trait_key.clone(),
                    trait_definition_target,
                    store,
                )?;
                members.push(id);
                if local.is_empty() {
                    store.charge(member_bytes(&path), &decl.file, Some(member.name_line))?;
                    self.foreign.entry(path).or_default().push(id);
                } else {
                    for ty in &local {
                        let table = if self.assoc.contains_key(ty) {
                            0
                        } else {
                            MEMBERS_BYTES
                        };
                        store.charge(
                            member_bytes(&member.name) + table,
                            &decl.file,
                            Some(member.name_line),
                        )?;
                        self.assoc
                            .entry(*ty)
                            .or_default()
                            .entry(member.name.clone())
                            .or_default()
                            .push(id);
                    }
                }
            }
            self.record_block(&decl, &self_type, local, members, store)?;
        }
        Ok(())
    }

    /// Charge the one key shared by every member of a foreign impl block.
    fn charge_trait_key(
        key: &TraitKey,
        decl: &ImplDecl<'_>,
        store: &mut Store<'_>,
    ) -> Result<(), LoadError> {
        let bytes = match key {
            TraitKey::Canonical(path) => path.capacity(),
            TraitKey::Unresolved {
                written,
                candidates,
            } => {
                written.capacity()
                    + candidates.capacity() * size_of::<String>()
                    + candidates.iter().map(String::capacity).sum::<usize>()
            }
        };
        store.charge(
            shared_text(size_of::<TraitKey>()) + bytes,
            &decl.file,
            Some(decl.fact.line),
        )
    }

    /// Record the block, its written paths and its retained member identities.
    fn record_block(
        &mut self,
        decl: &ImplDecl<'_>,
        self_type: &str,
        local: Vec<ItemId>,
        members: Vec<ItemId>,
        store: &mut Store<'_>,
    ) -> Result<(), LoadError> {
        let fact = decl.fact;
        let (self_type, self_cost) = store.intern(self_type);
        let written = 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(
            self_cost + trait_cost + local.capacity() * size_of::<ItemId>(),
            &decl.file,
            Some(fact.line),
        )?;
        let required = self.impl_blocks.len().saturating_add(1);
        store.reserve_items(&mut self.impl_blocks, required, &decl.file, Some(fact.line))?;
        self.impl_blocks.push(ImplBlock {
            id: ImplId(self.impl_blocks.len()),
            file: decl.file.clone(),
            line: fact.line,
            span: fact.span.clone(),
            module: self.modules[decl.module].path.clone(),
            target: decl.target,
            test: combine(fact.test, decl.reach_test),
            self_type,
            trait_path,
            self_items: local,
            members,
            module_index: decl.module,
            unconditional_self: fact.unconditional_self,
        });
        Ok(())
    }

    /// A checkpoint of the lookups of the load for the impl block `decl`:
    /// what its paths looked up since the last one is charged to the work of
    /// the load at the impl's line (see [`Index::settle_lookups`]), so what
    /// passes the limit is the lookups of one impl.
    fn settle_impl_lookups(&self, store: &Store<'_>, decl: &ImplDecl<'_>) -> Result<(), LoadError> {
        self.drain_lookups(store.meter(), &decl.file, Some(decl.fact.line))
    }

    /// True when the glob path of `decl` names local enums only.
    fn globs_local_enum(
        &self,
        decl: &UseDecl,
        segs: &[String],
        steps: Steps<'_>,
    ) -> Result<bool, LoadError> {
        let walked = self.walk(
            decl.module,
            segs,
            decl.leading_colon,
            Namespace::Type,
            Heads::Use {
                test: decl.test,
                own: None,
            },
            steps,
        );
        match walked {
            Err(Fail::Storage(error)) => Err(error),
            walked => Ok(walked.is_ok_and(|walked| {
                !walked.items.is_empty()
                    && walked
                        .items
                        .keys()
                        .all(|id| self.items[id.0].kind == SymbolKind::Enum)
            })),
        }
    }

    /// The self path of an impl, written in its module: the module path and
    /// the path the self type is written with (`crate`, `self` and `super`
    /// taken from the module; a path with a leading `::` from its first
    /// segment, alone), or the
    /// module path and the written self type when the self type has no path.
    fn written_self_path(
        &self,
        decl: &ImplDecl<'_>,
        own: Option<&PathFact>,
        self_type: &str,
    ) -> Result<String, LoadError> {
        let Some(path) = own else {
            return Ok(format!("{}::{self_type}", self.modules[decl.module].path));
        };
        let mut at = decl.module;
        if path.leading_colon {
            // In edition 2015 a path with a leading `::` starts at the crate
            // root; in later ones at a crate.
            if self.edition(decl.module) != 2015 {
                return Ok(path.segments.join("::"));
            }
            at = self.modules[at].root;
        }
        let mut rest = path.segments.as_slice();
        match rest.first().map(String::as_str) {
            Some("crate") => {
                at = self.modules[at].root;
                rest = &rest[1..];
            }
            Some("self") => rest = &rest[1..],
            _ => {}
        }
        while rest.first().is_some_and(|segment| segment == "super") {
            // `super` above the crate root was refused before the impl was
            // attached.
            at = self.modules[at].parent.ok_or_else(|| {
                Index::error(
                    decl,
                    LoadErrorKind::Internal {
                        what: "a self path climbs above the crate root".to_owned(),
                    },
                )
            })?;
            rest = &rest[1..];
        }
        let mut written = self.modules[at].path.to_string();
        for segment in rest {
            written.push_str("::");
            written.push_str(segment);
        }
        Ok(written)
    }

    /// Record the members of an inherent impl whose self type names no
    /// struct, enum or union the index can see under the self path written
    /// in its module, marked [`SelfType::Unresolved`], and the impl among the
    /// unresolved impls. No scope or type names the members. Returns the
    /// members.
    fn attach_unresolved(
        &mut self,
        decl: &ImplDecl<'_>,
        own: Option<&PathFact>,
        self_type: &str,
        store: &mut Store<'_>,
    ) -> Result<Vec<ItemId>, LoadError> {
        let fact = decl.fact;
        let written = self.written_self_path(decl, own, self_type)?;
        let (path, path_cost) = store.intern(&written);
        let (shared_type, type_cost) = store.intern(self_type);
        store.charge(
            vec_slot::<UnresolvedImpl>()
                + path_cost
                + type_cost
                + if fact.items.is_empty() {
                    0
                } else {
                    vec_first::<ItemId>()
                },
            &decl.file,
            Some(fact.line),
        )?;
        let mut members = Vec::new();
        for member in &fact.items {
            let kind = match member.kind {
                ItemKind::Fn => SymbolKind::InherentMethod,
                ItemKind::TypeAlias => SymbolKind::AssocType,
                _ => SymbolKind::AssocConst,
            };
            store.charge(vec_slot::<ItemId>(), &decl.file, Some(member.name_line))?;
            let id = self.push_member(
                decl,
                member,
                kind,
                &format!("{written}::{}", member.name),
                self_type,
                SelfType::Unresolved,
                None,
                None,
                store,
            )?;
            members.push(id);
        }
        let mut retained_members = Vec::new();
        store.reserve_items(
            &mut retained_members,
            members.len(),
            &decl.file,
            Some(fact.line),
        )?;
        retained_members.extend_from_slice(&members);
        self.unresolved.push(UnresolvedImpl {
            path,
            self_type: shared_type,
            file: decl.file.clone(),
            line: fact.line,
            span: fact.span.clone(),
            target: decl.target,
            test: combine(fact.test, decl.reach_test),
            members: retained_members,
        });
        Ok(members)
    }

    /// The paths in the crate of a glob path written in `module` that starts
    /// in the crate (`crate`, `self`, `super`, a local module the module
    /// binds, or in edition 2015 a local module the crate root binds) and
    /// goes on through names the index cannot see: for each way the path can
    /// go, the path of the last local module it reaches, followed by the rest
    /// as written. A name bound to several modules gives a path through each.
    /// None for a path that starts at a crate of the extern prelude or with a
    /// name that is not a local module.
    fn unseen_local(
        &self,
        module: usize,
        segs: &[String],
        leading_colon: bool,
        test: bool,
        steps: Steps<'_>,
    ) -> Result<Vec<Vec<String>>, LoadError> {
        let Some(head) = segs.first() else {
            return Ok(Vec::new());
        };
        let heads = Heads::Use { test, own: None };
        let start = if self.crate_relative(module, head, leading_colon, heads) {
            self.modules[module].root
        } else if leading_colon {
            return Ok(Vec::new());
        } else {
            module
        };
        let bound_modules = |at: usize, name: &str| -> Result<BTreeSet<usize>, LoadError> {
            Ok(self
                .read_lookup(at, Namespace::Type, name, None, None, steps)
                .map_err(crate::settle::storage_failure)?
                .as_ref()
                .map_or_default(|(bound, _)| {
                    bound.keys().flat_map(|id| self.modules_for(*id)).collect()
                }))
        };
        let mut work = WorkList::<_, 8>::new();
        match head.as_str() {
            "crate" => push_work(&mut work, (self.modules[module].root, &segs[1..]), steps)?,
            "self" => push_work(&mut work, (module, &segs[1..]), steps)?,
            "super" => push_work(&mut work, (module, segs), steps)?,
            first => {
                for at in bound_modules(start, first)? {
                    push_work(&mut work, (at, &segs[1..]), steps)?;
                }
            }
        }
        let mut out = Vec::new();
        'ways: while let Some((mut at, mut rest)) = work.pop() {
            while rest.first().is_some_and(|segment| segment == "super") {
                // `super` above the crate root is refused for every import
                // before a trait key consults it.
                let Some(parent) = self.modules[at].parent else {
                    continue 'ways;
                };
                at = parent;
                rest = &rest[1..];
            }
            while let Some((first, tail)) = rest.split_first() {
                let mut inner = bound_modules(at, first)?.into_iter();
                let Some(next) = inner.next() else {
                    break;
                };
                for other in inner {
                    push_work(&mut work, (other, tail), steps)?;
                }
                at = next;
                rest = tail;
            }
            let mut path: Vec<String> = self.modules[at]
                .path
                .split("::")
                .map(str::to_owned)
                .collect();
            path.extend(rest.iter().cloned());
            out.push(path);
        }
        sort_unique(&mut out);
        Ok(out)
    }
}