cpp_code_analysis 0.3.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
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
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
//! # `textDocument/completion` — the list a cursor is asking for, and **why each item is in it**
//!
//! A completion is one question with one answer, and the whole of this module is the reading that decides *which*
//! question the cursor is asking. Everything below — the scope tree, the index, the search path — already knows how
//! to list what it has; what was missing was the reading that decides which of those lists belongs here, and the
//! ordering that decides what a reader sees first.
//!
//! ```text
//! the shape at the cursor   →  what may be written here                  (context)
//! the candidates            →  every one of them, with where it came from (names, members, table)
//! the order                 →  the nearest declaration first              (Score)
//! the budget                →  the biggest useful list, not the whole one (ITEM_BUDGET)
//! ```
//!
//! # Why "everything visible" is not an answer
//!
//! `#include <iostream>` puts the whole standard library in scope, transitively and honestly: a lookup that stops
//! at every declaration reachable through the include graph is *correct*, and it is what this layer used to answer
//! — measured on one real file, **692 names** for a blank line inside a function body, of which **6** came from the
//! file itself. A list whose useful part is one percent of it is a list nobody reads.
//!
//! The number is not wrong, it is the wrong *answer to the question a completion asks*. What a reader wants when
//! they press the key is what they were about to type, and the signals for that are textual and structural rather
//! than semantic — which is what this module ranks by:
//!
//! ```text
//! local_variable   declared in the scope the cursor is in          ← what they meant
//! w                declared in the scope the cursor is in
//! Widget           declared at file scope in this file
//! readMessage      declared at file scope in this file
//! std::string      declared in a header this file includes
//! _ARGMAX          declared in a header that header includes
//! ```
//!
//! The same list, ordered by how far the declaration is from the cursor **in the program text**: the body, the
//! file, what the file includes, what *that* includes. It is the rule every C++ front end's completion uses, and
//! it is C++'s own order of consideration seen from the other end — a name lookup walks outward, so the names it
//! reaches first are the ones a reader is most likely writing.
//!
//! # The vocabulary rules, which are separate from the ordering
//!
//! * **A member access is not a name position.** After `w.` the answer is `Widget`'s members and nothing else: a
//!   file-scope name cannot follow the operator, and offering one is offering a syntax error.
//! * **A `#` owns its cursor.** After a `#` the answer is the directives, after `#include` it is headers, and
//!   after `#endif ` it is nothing at all.
//! * **Prose is not code.** A cursor in a comment or a literal gets an empty list, because a list of names to type
//!   into a sentence is not a suggestion.
//!
//! # What is deliberately *not* filtered
//!
//! Nothing is dropped for being *unlikely*. `abort` and `FILE` are genuinely visible and genuinely occasionally
//! what somebody is writing, so they stay and are ranked low; `while` is offered inside an expression because C++
//! has no statement/expression divide a completion can see. What is dropped is what **cannot** be written here (a
//! member name after a `::`, a keyword where the reader is mid-identifier), what the implementation reserves
//! (`_Arg`, `__crt_…`), and what is past the budget. The remaining judgement is expressed as an *order*, because
//! an order can be wrong cheaply and a filter cannot.

pub mod context;
pub mod includes;
pub mod matching;
pub mod table;

use std::path::{Path, PathBuf};
use std::sync::Arc;

use cpp_parser::{CppSyntaxNode, SourceRange};

pub use context::{CompletionContext, context_at, doc_comment_at};
pub use includes::{Header, HeaderIndex, HeaderKind, SharedHeaders};
pub use table::{
    BUILTIN_TYPES, DIRECTIVES, DirectiveName, KEYWORDS, Keyword, KeywordUse, SNIPPETS, Snippet,
};

use crate::sema::symbol::{Known, ScopeKind, ScopeTree};
use crate::summary::{DeclFact, DeclKind};
use crate::{ProjectIndex, ProjectMember};

/// What an item is, in the vocabulary every consumer understands.
///
/// The analysis does not speak the protocol — `CompletionItemKind` is LSP's, and its numbers are a wire format —
/// so the kind is stated here once and mapped where the wire is. See `crate::util::kind` in the server for the
/// mapping, which is the only place that knows both vocabularies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ItemKind {
    Variable,
    Function,
    Method,
    Field,
    Class,
    Enum,
    EnumMember,
    Namespace,
    Macro,
    TypeParameter,
    Keyword,
    Snippet,
    Header,
}

/// One item a completion can offer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompletionItem {
    /// The text shown in the list, and what is inserted unless `CompletionItem::snippet` says otherwise.
    pub label: String,
    pub kind: ItemKind,
    /// What to insert, when that is not the label. For a snippet this is the body **in snippet syntax**.
    pub insert: String,
    /// Is [`CompletionItem::insert`] a snippet body rather than plain text?
    pub snippet: bool,
    /// One line beside the label: a type, a signature, "inherited from `Base`".
    pub detail: Option<String>,
    /// Where the declaration is, for `completionItem/resolve`: the file, and the offset of the declared **name**.
    /// `None` for a keyword, a snippet or a header, which declare nothing to document.
    pub identity: Option<(PathBuf, usize)>,
    /// What the client should compare against the typed prefix, when that is not the label: a qualified name whose
    /// tail is what is being typed (`std::string` against `str`).
    pub filter: Option<String>,
    /// The declaration this item is, when it has one.
    pub fact: Option<DeclFact>,
    /// The range a client **replaces** with [`CompletionItem::insert`].
    pub replace: SourceRange,
    /// **What accepting this item must also add** — an `#include` or an `import`, when the name comes from a header
    /// this file does not include yet.
    ///
    /// The item is offered because it is *strongly related* (the session supplies the candidates); accepting it without
    /// the include would produce code that does not compile, so the client gets both edits in one accept.
    pub inclusion: Option<Inclusion>,
    /// **The edits that go with this item**, in the file's own offsets: where to insert, and what.
    ///
    /// Filled in by the session, which has the **written text** the client is editing: the insertion point is a line in
    /// that text, and the rendering a completion is computed on has neither the line nor the offset.
    pub additional_edits: Vec<(SourceRange, String)>,
}

/// **A file that declares names this file could use but does not include** — a completion candidate the session
/// supplies, with the line that would bring it in.
///
/// The session decides *which* files are "strongly related" (its own directory, the libraries its target depends on);
/// the completion layer decides which of their declarations answer what was typed. The split matters: the first is a
/// question about the project's configuration, the second about the program.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unincluded {
    pub file: std::path::PathBuf,
    pub inclusion: Inclusion,
}

/// **An `#include` or an `import` a completion item carries** — see [`CompletionItem::inclusion`].
///
/// The spelling is decided where the item is built (that layer knows the include directories); the *position* is not,
/// because the position is a question about the file's text rather than about the program.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Inclusion {
    /// `#include "widgets/widget.h"` — the spelling a compiler will find.
    Include(String),
    /// `import report;` — a module interface, which is imported rather than included.
    Import(String),
}

impl Inclusion {
    /// The whole line this inclusion inserts, newline included.
    pub fn line(&self) -> String {
        match self {
            Inclusion::Include(spelling) => format!("#include \"{spelling}\"\n"),
            Inclusion::Import(module) => format!("import {module};\n"),
        }
    }
}

/// **How to spell an `#include` for `header` from `asking`**, given the include directories this file is built with.
///
/// Relative to an include directory first — that is what `-I` means, and what survives the project being moved — then
/// relative to the including file, which is what a quoted `#include` searches first, and only then the absolute path.
/// One implementation for the code action and the completion item: two spellings of one include would be a defect a
/// reader meets as "the fix wrote something my compiler cannot find".
pub fn the_include_spelling(
    header: &std::path::Path,
    asking: &std::path::Path,
    include_paths: &[crate::include::config::IncludePath],
) -> String {
    let header_normal = header.to_string_lossy().replace('\\', "/");
    for path in include_paths {
        let directory = path.directory.to_string_lossy().replace('\\', "/");
        let directory = directory.trim_end_matches('/');
        if directory.is_empty() {
            continue;
        }
        if let Some(relative) = header_normal.strip_prefix(&format!("{directory}/")) {
            return relative.to_string();
        }
    }
    if let (Some(from), Some(to)) = (asking.parent(), header.parent()) {
        let from: Vec<String> = from
            .components()
            .map(|part| part.as_os_str().to_string_lossy().to_string())
            .collect();
        let to: Vec<String> = to
            .components()
            .map(|part| part.as_os_str().to_string_lossy().to_string())
            .collect();
        let shared = from
            .iter()
            .zip(&to)
            .take_while(|(left, right)| left.eq_ignore_ascii_case(right))
            .count();
        if shared > 0 {
            let mut relative: Vec<String> = vec!["..".to_string(); from.len() - shared];
            relative.extend(to[shared..].iter().cloned());
            if let Some(file) = header.file_name() {
                relative.push(file.to_string_lossy().to_string());
            }
            let spelled = relative.join("/");
            if !spelled.is_empty() {
                return spelled;
            }
        }
    }
    header_normal
}

impl CompletionItem {
    /// A declaration, as an item.
    fn declared(fact: &DeclFact, file: &Path) -> CompletionItem {
        // An item with no name — a destructor the index could not spell — has nothing to resolve *to*, and an
        // identity pointing at an empty range would fetch another declaration's documentation.
        let identity =
            (!fact.name.is_empty()).then(|| (file.to_path_buf(), fact.name_range.start_offset));

        CompletionItem {
            label: fact.name.clone(),
            kind: kind_of(fact.kind),
            insert: match (&fact.kind, &fact.parameter_list) {
                // **A function-like macro is inserted with its parenthesis** — the only hint a completion item carries about how a
                // name is used: `MAX(` says it takes arguments, and `MAX` alone does not. Measured before this: the item for
                // `#define MAX(a, b)` read `insert: "MAX"`, `kind: Macro`, and nothing else.
                (crate::DeclKind::MacroLike, Some(_)) => format!("{}(", fact.name),
                _ => fact.name.clone(),
            },
            snippet: false,
            detail: detail_of(fact),
            identity,
            filter: None,
            fact: Some(fact.clone()),
            replace: SourceRange::new(0, 0),
            inclusion: None,
            additional_edits: Vec::new(),
        }
    }

    fn word(label: &str, kind: ItemKind, detail: &str) -> CompletionItem {
        CompletionItem {
            label: label.to_string(),
            kind,
            insert: label.to_string(),
            snippet: false,
            detail: Some(detail.to_string()),
            identity: None,
            filter: None,
            fact: None,
            replace: SourceRange::new(0, 0),
            inclusion: None,
            additional_edits: Vec::new(),
        }
    }

    fn snippet(trigger: &str, detail: &str, body: &str) -> CompletionItem {
        CompletionItem {
            label: trigger.to_string(),
            kind: ItemKind::Snippet,
            insert: body.to_string(),
            snippet: true,
            detail: Some(detail.to_string()),
            identity: None,
            filter: None,
            fact: None,
            replace: SourceRange::new(0, 0),
            inclusion: None,
            additional_edits: Vec::new(),
        }
    }

    /// **A declaration from a header this file does not include**, with the include that would make it usable.
    fn unincluded(fact: &DeclFact, file: &Path, inclusion: Inclusion) -> CompletionItem {
        let mut item = CompletionItem::declared(fact, file);
        let line = inclusion.line();
        item.detail = Some(format!(
            "not included — accepting this adds `{}`",
            line.trim_end()
        ));
        item.inclusion = Some(inclusion);
        item
    }

    fn header(header: &Header) -> CompletionItem {
        CompletionItem {
            label: header.name.clone(),
            kind: ItemKind::Header,
            insert: header.name.clone(),
            snippet: false,
            detail: None,
            identity: None,
            filter: Some(header.name.clone()),
            fact: None,
            replace: SourceRange::new(0, 0),
            inclusion: None,
            additional_edits: Vec::new(),
        }
    }
}

/// A declaration's kind, in the item vocabulary.
fn kind_of(kind: DeclKind) -> ItemKind {
    match kind {
        DeclKind::Type => ItemKind::Class,
        DeclKind::Function => ItemKind::Function,
        DeclKind::Variable => ItemKind::Variable,
        DeclKind::Namespace => ItemKind::Namespace,
        DeclKind::MacroLike => ItemKind::Macro,
        DeclKind::Other => ItemKind::Variable,
    }
}

/// A declaration's **own** one-line description: its type, or what it returns with what it takes.
///
/// Deliberately not the kind ("a variable"): the icon already says that, and a line repeating the icon would
/// crowd out the one thing a reader wants — the type — which is also the one thing a name from another file does
/// not show in the list otherwise.
///
/// # Why a function shows its parameter list
///
/// Because a list of names is a list of *choices*, and two functions are told apart by what they take: the popup
/// after `std::` holds `format`, `format_to`, `format_to_n`, `formatted_size` and `vformat`, all returning
/// something string-shaped, and `string (…)` for every one of them is a row a reader cannot choose from. The
/// spelling comes from the declaration's own fact ([`DeclFact::parameter_list`]), so it is available for a name
/// declared in a header nobody has opened — the case this line exists for.
///
/// `(…)` survives for the one case it is still the honest answer to: a fact written before the field existed, or a
/// function whose declarator the reading could not reach. It says "this function takes something", which is less
/// than the truth and not more.
pub fn detail_of(fact: &DeclFact) -> Option<String> {
    match fact.kind {
        DeclKind::Function => match (&fact.returns, &fact.parameter_list) {
            (Some(returns), Some(parameters)) => Some(format!("{returns} {parameters}")),
            (Some(returns), None) => Some(format!("{returns} (…)")),
            (None, Some(parameters)) => Some(parameters.clone()),
            (None, None) => None,
        },
        DeclKind::Variable => fact.type_of.clone(),
        DeclKind::Type if !fact.bases.is_empty() => Some(format!(": {}", fact.bases.join(", "))),
        _ => None,
    }
}

/// What a completion found: the items, in the order they should be shown, and **whether the answer is complete**.
///
/// `Default` is written out rather than derived because [`SourceRange`] has no default of its own: a range of
/// nothing at offset zero is the same "no edit" the type means everywhere else, and giving `SourceRange` a
/// `Default` would make an accidental one compile at every other call site too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompletionSet {
    pub items: Vec<CompletionItem>,
    /// The scope the names were listed from — `ns`, `Widget`, `::`, or empty for "wherever the cursor is".
    pub scope: String,
    /// What of the name is already written before the cursor, which is what filters the list.
    pub prefix: String,
    /// The range a client **replaces** with the chosen item.
    pub replace: SourceRange,
    ///
    /// Distinct from the analysis being incomplete, and the distinction is the protocol's `isIncomplete`: a client
    /// told "incomplete" asks again as the user types, which is exactly right while a background index is still
    /// reading files and exactly wrong when the answer was merely capped — the retry would return the same capped
    /// list for ever.
    pub truncated: bool,
    /// **Was the analysis itself incomplete** — a class this answer depends on that could not be read?
    ///
    /// The protocol's `isIncomplete` means one thing: *ask again later*. `truncated` is a budget, and re-asking
    /// returns the same list; this is the other kind — a class whose facts the index does not have yet, so the
    /// members are **missing rather than few**. Measured on a real project: `std::string* message; message->`
    /// offered **one** item on the first keystroke (`operator basic_string_view`, the only member the raw reading of
    /// `<xstring>` had at file scope) and **58** once the file was cooked. A list that looks final and holds a
    /// quarter of the truth is worse than an empty one, because the reader believes it.
    pub incomplete: bool,
}

impl CompletionSet {
    /// **Did the answer hold nothing that could be what the reader is typing?**
    ///
    /// A client filters the list by the typed prefix and, on an empty result, shows *"no suggestions"* — and some
    /// clients cache that for the prefix, so only the next keystroke re-opens the question. An answer holding nothing
    /// that matches is therefore **not final**, whatever the reason: the file's closure was still being read, its
    /// summary had just been dropped by an edit, or the gathering layer stopped short.
    ///
    /// The test is the engine's own matcher rather than a prefix comparison, because `gp` legitimately matches
    /// `getPid` without being a prefix of it — a list that answered `getPid` *did* answer what was typed.
    pub fn nothing_matched(&self) -> bool {
        !self.prefix.is_empty()
            && !self.items.iter().any(|item| {
                let compared = item.filter.as_deref().unwrap_or(&item.label);
                crate::completion::matching::quality(compared, &self.prefix)
                    != crate::completion::matching::NONE
            })
    }
}

impl Default for CompletionSet {
    fn default() -> CompletionSet {
        CompletionSet {
            items: Vec::new(),
            scope: String::new(),
            prefix: String::new(),
            replace: SourceRange::new(0, 0),
            truncated: false,
            incomplete: false,
        }
    }
}

/// An item and the score that orders it.
///
/// The score is **not** a field of [`CompletionItem`]: a consumer renders items, and a number it must not re-sort
/// by is a field it would eventually misuse. Keeping the two together here means the order is decided once, in one
/// place, and thrown away at the same moment.
///
/// `matched` is how well the item answers what was typed, and it is the **last** thing the order looks at — after the
/// tier, which says where a declaration is, and after the penalty, which says what kind of thing it is. It is here
/// rather than inside `score` because it is a fact about the *typed text* and not about the declaration: the same
/// name scores the same whatever the reader has written, and the same declaration scores differently on every
/// keystroke.
#[derive(Debug, Clone)]
struct Scored {
    score: Score,
    matched: crate::completion::matching::Quality,
    item: CompletionItem,
}

/// **The completion for a cursor**, given everything the analysis knows.
///
/// This is the whole of the feature: the context decides which vocabulary applies, the layers below gather it, and
/// the score orders it. A caller that wants one of the *queries* rather than the list — a test, a probe — should
/// look at [`NameCompletions`](crate::NameCompletions) and [`MemberCompletions`](crate::MemberCompletions), which
/// are the two questions this dispatches between.
pub fn completion_at(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    offset: usize,
    headers: &HeaderIndex,
    cuda: bool,
    budget: usize,
    unincluded: &[Unincluded],
) -> CompletionSet {
    // The context is this function's first question and the only one read from a tree; a caller that has already read
    // it — `Session::completions`, for the two contexts that live in the **file's** own text rather than in the
    // rendering — hands it over instead of having it asked again of the wrong tree.
    let asked = context_at(root, offset);
    completion_with(
        index, scopes, root, path, offset, headers, asked, cuda, budget, unincluded,
    )
}

/// **The same dispatch with the context already decided**, and the entry point for a caller whose context came from
/// another tree — see `Session::completions`.
///
/// `offset` is in the coordinates of **the tree the context was read from**: the reading's for a context asked of
/// `root`, and the **file's** for one asked of a parse of the written text. The `replace` range a context carries is
/// built from it, and a range a client is to edit has to be the file's.
pub fn completion_with(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    offset: usize,
    headers: &HeaderIndex,
    context: CompletionContext,
    cuda: bool,
    budget: usize,
    unincluded: &[Unincluded],
) -> CompletionSet {
    // **The measurement window for one completion**, opened here because this is the entry point the feature has:
    // everything below is the query's own work, and the server's log line splits only the outside of it
    // (`view`/`completions`). Opt-in, on `CPPLS_TRACE_COMPLETION`, like this crate's other traces — see

    match context {
        CompletionContext::Nothing => CompletionSet {
            replace: SourceRange::new(offset, 0),
            ..CompletionSet::default()
        },
        CompletionContext::Member(access) => {
            members(index, scopes, root, path, &access, offset, budget).set
        }
        CompletionContext::Qualified(position) => names(
            index, scopes, root, path, &position, offset, false, cuda, budget, unincluded,
        ),
        CompletionContext::Name(position) => names(
            index, scopes, root, path, &position, offset, true, cuda, budget, unincluded,
        ),
        CompletionContext::DirectiveName { written, range } => directives(&written, range),
        // **A module name is answered by the session, not here**, and the empty set says so rather than guessing:
        // the names are the *project's* (its `.cppm` files and the modules the index can name), which is a question
        // about the index and the file list rather than about the tree — see `Session::module_completions`. This arm
        // exists because the match must be total, and a caller that reaches it has no session to ask.
        CompletionContext::ModuleName { .. } => CompletionSet::default(),
        CompletionContext::DirectiveArgument { written, range } => {
            let position = crate::sema::resolve::NamePosition {
                scope: String::new(),
                written,
                range,
            };

            // `#define NAME`, `#undef NAME`, `#ifdef NAME`: the argument is a *name*, and what may be written is
            // what the program already declares. No keywords and no snippets — a macro's name is an identifier, and
            // a control-flow statement is not one — which is why this goes through the name query only.
            names(
                index, scopes, root, path, &position, offset, false, cuda, budget, unincluded,
            )
        }
        CompletionContext::Include {
            written,
            closed,
            range,
            ..
        } => headers_for(headers, &written, closed, range),
        // **A `#define`'s replacement list**: the macro's own parameters first, then the macros already defined.
        // Nothing else belongs here — the body is preprocessor text, where a class member or a local cannot appear.
        CompletionContext::MacroBody {
            written,
            range,
            parameters,
        } => macro_body(index, path, &written, range, &parameters),
        // **A preprocessor condition** — `#if`, `#elif`, `#ifdef`, `#undef`: the macros, and the operators on them.
        CompletionContext::Condition { written, range } => condition(index, path, &written, range),
        // **Inside a documentation comment**: Doxygen's vocabulary, or the name the command takes. Both are read
        // from the file's own text rather than from a scope, so neither needs the index — see
        // [`doc_comment_at`].
        CompletionContext::DocComment {
            written,
            range,
            wants,
        } => doc_comments(index, path, &written, range, wants),
        CompletionContext::DocLink { written, range } => doc_link_names(
            index, scopes, root, path, &written, range, cuda, budget, unincluded,
        ),
        // **A code block is code**, so it is answered with the same list a statement gets — keywords and snippets
        // included, because that is what a reader writing an example is writing.
        CompletionContext::DocCode { written, range } => {
            let position = crate::sema::resolve::NamePosition {
                scope: String::new(),
                written,
                range,
            };
            names(
                index, scopes, root, path, &position, 0, true, cuda, budget, unincluded,
            )
        }
    }
}

/// **What a documentation reference may name** — the names this file can see, without the keyword table.
///
/// A link takes a *symbol*: `class` and `dowhile` are what a statement position offers, and offering them inside
/// ``[`…`]`` is the same mistake as offering them in the prose around it. `with_table` is the switch that decides
/// that, so it is passed `false` here and nothing else changes.
///
/// A qualified prefix is split off — `Widget::gr` asks about the scope `Widget`, which is what the index can answer.
///
/// The lookup is asked at the rendering's **start**: a link has no reading position, because a comment is trivia and
/// the cook removes it, and the first byte of a translation unit is the one place whose enclosing scope is the file
/// itself — which is the question "what can this file name".
fn doc_link_names(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    written: &str,
    range: SourceRange,
    cuda: bool,
    budget: usize,
    unincluded: &[Unincluded],
) -> CompletionSet {
    let (scope, written) = match written.rsplit_once("::") {
        Some((scope, rest)) => (scope.to_string(), rest.to_string()),
        None => (String::new(), written.to_string()),
    };
    let position = crate::sema::resolve::NamePosition {
        scope,
        written,
        range,
    };
    names(
        index, scopes, root, path, &position, 0, false, cuda, budget, unincluded,
    )
}

/// **What the completion made of a cursor** — the one diagnosis this layer is worth logging.
///
/// A `.` whose answer is the names in scope is the shape a user reported as "补全明显错误": the popup is full of
/// things that cannot follow the operator, and nothing in it says whether the *type* could not be worked out, the
/// class could not be found, or the cursor was never read as a member access at all. Those three have different
/// fixes, and the reason is thrown away by the time a client sees an answer with no members in it.
///
/// **Asked of the same reader the answer came from**, and that is the whole of why this function takes `root` and
/// not the set: the member list is produced together with the reason it came out empty, so the sentence a log shows
/// is about *this* query rather than about a second one that may disagree with it. Measured on a live server: the
/// diagnostic said "the cursor is not a member access at all" while the completion beside it was listing the
/// members — because the diagnostic asked the index layer, whose tree-only shape reader does not accept a cursor
/// drawn **on** the operator's own column, and the feature asks the context reader, which does.
///
/// Only asked when the answer contained no members, so the cost is one extra query on exactly the keystrokes a
/// reader would complain about.
pub fn why_no_members(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    // **A typed offset, because an untyped one let a caller pass the file's** — and the failure was a panic inside
    // `rowan` rather than a wrong answer: `"Bad offset: range 0..27 offset 52"`, where 52 is a position in the file
    // (the header inlined, the directive gone) and 27 is the length of its rendering. This function reads `root`, so
    // its offset is the rendering's.
    offset: crate::file::coordinates::ReadingOffset,
) -> String {
    let offset = offset.get();
    match context_at(root, offset) {
        CompletionContext::Member(access) => {
            members(index, scopes, root, path, &access, offset, ITEM_BUDGET).why
        }
        other => format!("the cursor is not a member access at all: {other:?}"),
    }
}

/// The members of an object, after a `.` or `->`, and **the sentence that explains an empty list**.
///
/// # Why the object comes from the caller rather than from a second reading of the tree
///
/// This used to call `member_completions_at`, which reads the shape off the tree itself — and that is a **second
/// reading of the same fact**, which is how the two came to disagree. The reader above answers "is the cursor a
/// member access" from the tree **and** from the text (see [`context::context_at`]), because a parser recovering
/// from a line that ends in an operator does not always build the access node; the query behind it only asked the
/// tree, so a cursor the reader had just classified as a member access came back as *not a member access at all*
/// and the list was empty. Measured on a live server: `full2.` on the last line of a body answered nothing.
///
/// There is one reader of the shape and it is the one above. What this function needs from it is the **object**,
/// which is what a type is inferred from — and that inference is [`type_of_expression`], the same call the query
/// makes, so the two layers still cannot disagree about the *type*.
///
/// # Why it returns the reason rather than only the list
///
/// An empty list has four causes — the object's type could not be read, the class is not declared anywhere the
/// index can see, the class has no members, or every member was the implementation's — and they have four different
/// fixes. The reason is produced *here*, where the steps are, rather than re-derived by a diagnostic that would
/// have to ask the same questions again and could answer them differently. See [`why_no_members`].
/// **Which class a `.` or a `->` reaches** — the answer a member list is built from.
///
/// A `.` means the object's own class (or, for a pointer, the class it points at — C++ makes that ill-formed, and a
/// reader typing `.` on a pointer is asking about the class anyway). A `->` means the same thing *after* the arrow has
/// been followed as far as the type answers, which is what makes the two cases a reader reports work:
///
/// ```text
/// Widget* p;                    p->   reaches Widget          (a pointer's pointee)
/// std::unique_ptr<Widget> sp;   sp->  reaches Widget          (the class's own operator->, then its pointee)
/// std::shared_ptr<T> sp;        sp->  reaches T               (same, one more hop through the pointer)
/// standard containers           it->  reaches the element     (`iterator::operator->`'s return)
/// ```
///
/// Answering the object's own class instead was the defect reported as "智能指针的补全没有考虑指向的内容": a smart
/// pointer's own member list is `operator->`, `operator*`, `reset`, `get`, … — none of which can be reached through
/// `->` — while the class it points at has exactly the members the arrow means.
///
/// **Bounded.** A class whose `operator->` returns itself (a proxy) is a loop, and four hops is past every real chain
/// measured: `shared_ptr<T>` is two, a `unique_ptr` is two, a container iterator is two.
pub(crate) fn the_class_after_the_operator(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    written: &crate::sema::types::Type,
    arrow: bool,
) -> Option<(String, bool)> {
    // **Whether a pointer was followed to find the class**, which is what says a `.` should have been a `->`.
    let mut followed_a_pointer = false;
    let mut current = written.clone();
    for _ in 0..4 {
        if let Some(bare) = current.class_name().map(str::to_string) {
            // **The spelling the use wrote is not always the one the index keys the class on.** `auto unique =
            // std::make_unique<Resource>(1);` makes `unique`'s type `unique_ptr<Resource>`, whose class is declared as
            // `std::unique_ptr` — a member list asked for the bare `unique_ptr` answers nothing (measured: 0 members
            // against 52), and the arrow then resolved to the *pointer's own* (empty) members. The qualification is
            // the index's own answer (`css::Widget` for a `Widget` declared there), and it is a `None` when the name is
            // already qualified or nothing declares it, in which case the spelling stands.
            // **Only a bare spelling is qualified.** `class_name()` answers the spelling the type was written with — for
            // `std::unique_ptr<Base>` that already carries its namespace — and prepending the index's scope to it
            // produced `std::std::unique_ptr` (measured on `classes.cpp`'s `clone->describe()`, which then resolved to
            // the pointer's own typedef `pointer` and offered nothing).
            let class = if bare.contains("::") {
                bare.clone()
            } else {
                crate::index::project::qualified_from_the_index(index, path, &bare)
                    .unwrap_or_else(|| bare.clone())
            };

            // **1. A pointer-like class says what its arrow reaches, in `element_type`** — the standard's own
            // protocol, which `std::pointer_traits` is written in terms of and which `unique_ptr`, `shared_ptr` and
            // `weak_ptr` all take part in. It is asked **first**, because on those classes the arrow's declared
            // return type is a member alias of a dependent `typename …::type`:
            //
            // ```cpp
            // _NODISCARD pointer operator->() const noexcept;         // unique_ptr
            // using pointer = typename _Get_deleter_pointer_type<_Ty, remove_reference_t<_Dx>>::type;
            // ```
            //
            // Following *that* lands on a trait template — or, when the fact carries no readable return type at all,
            // on nothing, which is how the answer became the smart pointer's **own** members. Measured on a real
            // project: `std::unique_ptr<int> p; p->` offered `get`/`get_deleter` (none of which can be written after
            // that arrow) and `std::unique_ptr<std::string> p; p->` offered nothing.
            //
            // It is asked **only of a class that declares `operator->`** — that is what "pointer-like" means, and it
            // is what keeps an ordinary pointer from being stolen: `std::string* p; p->` must reach `std::string`,
            // whose member list has no `operator->`, so the pointer is stripped by the arm below instead of `p->`
            // becoming `basic_string::value_type`'s members (`char`'s, of which there are none).
            // **Only an arrow follows the pointer protocol.** A `.` on a class means the class's own members, and a
            // smart pointer is a class like any other there: `shared.reset()`, `shared.use_count()` and
            // `shared.get()` are written with a dot and are the handle's. Following `element_type` for a dot listed
            // the *pointee's* members instead — measured on `test_cpp/src/smart_pointers.cpp`, `shared.` offered
            // `Resource`'s two members (`identifier`, `~Resource`) and none of the handle's twelve, which is the report
            // "`shared_ptr`'s own fields are not completed".
            //
            // Two cases look like that one and are not:
            //
            // * a **raw pointer** left of a dot — `Widget* p; p.` is ill-formed, and the `pointee()` arm below still
            //   follows it and reports `followed_a_pointer`, so the client can rewrite the `.` as `->`;
            // * a **class that is not pointer-like** — `std::optional<std::string>` declares `value_type`, not
            //   `element_type`, and its dot has always answered its own members. The `value_type` line of the note
            //   above is still why the protocol is `element_type` and not any contained-type typedef.
            if arrow
                && let Some(pointee) =
                    the_element_type_pointed_at(index, scopes, root, path, &class, &current)
            {
                current = crate::sema::types::parse_type_spelling(&pointee);
                followed_a_pointer = true;
                continue;
            }
            // **2. A class's own `operator->`, when its declared return type can be read.** For an `arrow` this is
            // the chain continuing; for a `.` it is a reader who typed the wrong operator, which is reported by
            // `followed_a_pointer` so that the completion can rewrite the `.` as `->`.
            let returns = if arrow {
                crate::index::project::operator_returns_of(
                    index,
                    &mut |_: &Path| None,
                    scopes,
                    root,
                    path,
                    &current,
                    "operator->",
                )
            } else {
                // **A dot does not follow a class's `operator->`** — see the note on step 1 above.
                None
            };
            let Some(returns) = returns else {
                // **3. Where the arrow stops.** A plain `struct` on the left of `->` is ill-formed, and its members
                // are the honest answer for a reader who typed one by mistake.
                return Some((class, followed_a_pointer));
            };
            current = crate::sema::types::parse_type_spelling(&returns);
            if !arrow {
                followed_a_pointer = true;
            }
            continue;
        }
        {
            let pointee = current.pointee()?;
            followed_a_pointer = true;
            current = (*pointee).clone();
        }
    }
    current.class_name().map(str::to_string).map(|bare| {
        let class = if bare.contains("::") {
            bare.clone()
        } else {
            crate::index::project::qualified_from_the_index(index, path, &bare)
                .unwrap_or_else(|| bare.clone())
        };
        (class, followed_a_pointer)
    })
}

/// **What a pointer-like class's arrow reaches**, asked of the index's own walk — see
/// [`crate::index::project::element_type_of`], which is the one implementation of that rule.
///
/// # Why the member list is asked first
///
/// The standard's answer to "what does this arrow reach" is `element_type` — `std::pointer_traits` is written in
/// terms of it, and `unique_ptr`, `shared_ptr` and `weak_ptr` all take part — so a class that declares one is
/// **pointer-like**, whether it declares `operator->` itself or inherits it. The member list is what says so, and it
/// walks bases.
///
/// It used to require the class's **own** `operator->`/`operator*`, and that is where `std::shared_ptr` fell out:
/// measured on a real project, `members_of("shared_ptr")` answers fifteen members — its constructors, its assignment
/// operators, `element_type`, `weak_type` and two friends — and **no `operator->` at all**, because libstdc++ declares
/// that one two bases down (`shared_ptr` → `__shared_ptr` → `__shared_ptr_access<_Tp, _Lp, false, false>`). So
/// `std::shared_ptr<State> state_; state_->` listed the handle's own members instead of `State`'s.
///
/// The guard is still needed, and still for the reason it was written: `element_type`/`value_type` alone are too
/// common — `std::string` has `value_type = char`, so asking *any* class turned `std::string* p; p->` into "the
/// members of `char`". `element_type` is the pointer protocol's typedef rather than a container's, and no container
/// declares one.
///
/// The **arguments the use wrote** (`["std::string"]` for `std::unique_ptr<std::string>`) are what its `element_type`
/// is substituted with, and the class is passed to `template_parameters_for` **qualified**: with the bare `unique_ptr`
/// the walk reached the primary template's parameters and answered `_Ty` unsubstituted, which then pointed the arrow at
/// a class called `_Ty`.
fn the_element_type_pointed_at(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    class: &str,
    written: &crate::sema::types::Type,
) -> Option<String> {
    let Known::Yes(members) = crate::index::project::members_of(index, scopes, root, path, class)
    else {
        return None;
    };
    let pointer_like = members.members.iter().any(|member| {
        matches!(
            member.fact.name.as_str(),
            "element_type" | "operator->" | "operator*"
        )
    });
    if !pointer_like {
        if crate::probes::members() {
            let names: Vec<&str> = members
                .members
                .iter()
                .map(|member| member.fact.name.as_str())
                .filter(|name| name.starts_with("operator"))
                .collect();
            eprintln!(
                "element_type: {class} is not pointer-like ({} member(s), operators {names:?})",
                members.members.len()
            );
        }
        return None;
    }
    let arguments: Vec<String> = written
        .arguments()
        .iter()
        .map(|argument| argument.to_string())
        .collect();
    let walked =
        crate::index::project::element_type_of(index, scopes, root, path, class, class, &arguments);

    // **A spelling only counts when it names a *class*.** `_Ptr_base` — `shared_ptr`'s base — says
    // `using element_type = remove_extent_t<_Ty>;`, and that is an **alias template**: substituted at the use it is
    // `remove_extent_t<std::string>`, whose target is `typename remove_extent<T>::type`, a trait evaluation rather
    // than a spelling. Following it reaches a class template with no arguments, no members and no way back — which is
    // exactly what `shared_ptr<std::string> p; p->` answered: nothing.
    //
    // For a class that takes an arrow through its own operator, **its own argument is the element** — that is what
    // `shared_ptr<T>`, `unique_ptr<T>` and `weak_ptr<T>` mean, and it is the same rule
    // `the_class_an_arrow_points_at` states for the other reader of this question.
    match walked {
        Some(pointee) if leads_to_members(index, scopes, root, path, &pointee) => Some(pointee),
        _ => arguments
            .first()
            .filter(|first| leads_to_members(index, scopes, root, path, first))
            .cloned(),
    }
}

/// **Can a member query be asked about this spelling at all?** — the test for "is this a type, or a dead end?".
///
/// Deliberately asked of the *member list* rather than of the declaration: `std::string` is an **alias** of
/// `basic_string<char, …>` and its members are 58; `remove_extent_t<std::string>` is an **alias template** whose target
/// is a trait evaluation and whose member list is empty. The distinction that matters here is exactly that one, and a
/// kind/`type_of` test gets it backwards on the case this exists for.
///
/// The list is cached by the index, and the walk for a class with no declaration answers immediately, so this is a
/// hash lookup in the common case.
fn leads_to_members(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    name: &str,
) -> bool {
    matches!(
        crate::index::project::members_of(index, scopes, root, path, name),
        Known::Yes(list) if !list.members.is_empty()
    )
}

fn members(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    access: &crate::sema::resolve::MemberAccess,
    offset: usize,
    budget: usize,
) -> MemberAnswer {
    let replace = access.member_range;
    let prefix = written_before(access, offset);

    let refused = |why: String| MemberAnswer {
        set: CompletionSet {
            scope: String::new(),
            prefix: prefix.clone(),
            replace,
            truncated: false,
            // **"Not worked out" is not "nothing there".** Every refusal below is a missing fact — the type of the
            // object, or the class it names — so the client has to be told to ask again, and the handler's
            // `isIncomplete` is the only way to say so.
            incomplete: true,
            items: Vec::new(),
        },
        why,
    };

    let written = match crate::index::project::type_of_expression(
        index,
        &mut |_: &Path| None,
        scopes,
        root,
        path,
        &access.object,
        0,
    ) {
        Known::Yes((written, _)) => written,
        // The object's type could not be worked out — a call, a dereference, a subscript: each needs a type
        // *computed* rather than read off a declaration. **Nothing is offered**, and that is the answer rather than
        // a failure: a name that cannot follow the `.` is worse than no name, because the user believes it. The
        // empty list is not marked truncated, so a client that sees `isIncomplete` alongside it knows the
        // difference between "no members" and "not known yet".
        Known::Unknown(reason) => return refused(reason.describe()),
        Known::No => {
            return refused(format!(
                "nothing says what `{}` is, so its members are not known",
                access.object.text().to_string().trim()
            ));
        }
    };

    // **The class, not the type.** `std::vector<int>` is a type and `std::vector` is what has members; listing the
    // members of the whole spelling asked about a class nobody declares, which is why a completion after a standard
    // container's member answered nothing.
    //
    // **And for `->` it is the class the arrow reaches, not the object's own class.** `p->` on a `Widget*` means
    // `Widget`; `sp->` on a `std::unique_ptr<Widget>` means `Widget` as well, through the class's own `operator->`
    // (whose return type is a pointer, whose pointee is the class). Answering the object's own class was the defect
    // a reader reported as "智能指针的补全没有考虑指向的内容": a smart pointer's own members are `operator->`,
    // `operator*`, `reset`, … — none of which can be reached through `->` — while the class it points at has exactly
    // the members the arrow means.
    let Some((class, followed_a_pointer)) =
        the_class_after_the_operator(index, scopes, root, path, &written, access.arrow)
    else {
        // **A type that names no class has no members, and that is a fact rather than a gap.** Every way of working
        // the type out has already been taken by the time `the_class_after_the_operator` answers `None` — it follows
        // pointers, a class's own `operator->` and `element_type` — so what is left is a type that is not a class at
        // all: `int`, `double`, `void`, a function pointer. `int* p; p->` therefore answers "nothing here", and it is
        // **complete**: `isIncomplete` would make a client ask again for an answer that cannot change, which is the
        // shape of a popup that stays empty for ever.
        return MemberAnswer {
            set: CompletionSet {
                scope: String::new(),
                prefix,
                replace,
                truncated: false,
                incomplete: false,
                items: Vec::new(),
            },
            why: format!(
                "the type of `{}` is `{written}`, which names no class to list members of",
                access.object.text().to_string().trim()
            ),
        };
    };

    let found = match crate::index::project::members_of(index, scopes, root, path, &class) {
        Known::Yes(found) => found,
        // **The class was not found, which on a real project is usually "not read yet".** `<xstring>` declares
        // `basic_string` inside `_STD_BEGIN`/`_STD_END`, so the class is at *file* scope until that header is
        // cooked — and a member list for it is empty (or holds the handful of members the raw reading happened to
        // place) until then. Told to ask again, the client retries on the next keystroke and gets the real list;
        // told nothing, it shows the list it got and the reader believes it.
        Known::Unknown(reason) => {
            return MemberAnswer {
                set: CompletionSet {
                    scope: class.to_string(),
                    prefix,
                    replace,
                    truncated: false,
                    incomplete: true,
                    items: Vec::new(),
                },
                why: reason.describe(),
            };
        }
        // `members_of` reports a class nothing declares as `Unknown`, so this arm is for totality and says the same
        // thing it would.
        Known::No => {
            return MemberAnswer {
                set: CompletionSet {
                    scope: class.to_string(),
                    prefix,
                    replace,
                    truncated: false,
                    incomplete: true,
                    items: Vec::new(),
                },
                why: format!("`{class}` is not a class this analysis can see"),
            };
        }
    };

    let mut scored: Vec<Scored> = Vec::new();

    // **The two offer rules are applied before the ranking**, in one place that both consumers of a member list go
    // through: the names the implementation owns, and the members the reader cannot name from here — see
    // [`crate::index::project::offerable_members`], which is where the access rule reads [`DeclFact::access`]
    // against the classes the cursor is in.
    let members = {
        let mut members = found;
        let hidden = crate::index::project::offerable_members(
            index,
            scopes,
            root,
            path,
            offset,
            &mut members,
        );
        (members, hidden)
    };
    let (members, hidden_by_access) = members;

    // **One row per spelling.** A class declares `replace` eleven times and `insert` nine, and every one of them is
    // a real declaration a jump should find — but a list is something a reader *picks* from, and eleven rows
    // reading `replace` are one choice offered eleven times. So the member query's list is collapsed by name here,
    // which is the same rule the name query applies and for the same reason. The declarations are not lost: the
    // jump and the hover ask `members_of` / `member_definitions_across_files`, which keep the whole overload set.
    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();

    for member in &members.members {
        // **A name the implementation owns is not offered to a reader who is not typing one.** See
        // [`reserved_for_the_implementation`] for the rule and the screenshot behind it.
        if reserved_for_the_implementation(&member.fact.name, &prefix) {
            continue;
        }
        // **A member the reader cannot name is not offered** — and that decision is the *query's*, not this
        // layer's: `member_completions_at` compares each member's access level with the classes the cursor is in
        // and reports what it kept out (`MemberCompletions::hidden_by_access`). Filtering here as well would be a
        // second reader of one rule, which is the shape of every bug in this area.
        if !seen.insert(member.fact.name.as_str()) {
            continue;
        }

        let mut item = CompletionItem::declared(&member.fact, &member.file);
        item.kind = member_kind(member, &class);
        item.replace = replace;

        if member.depth > 0 {
            item.detail = Some(match &item.detail {
                Some(type_of) => format!("{type_of}  (inherited from {})", member.declared_in),
                None => format!("inherited from {}", member.declared_in),
            });
        }

        if member.ambiguous {
            item.detail = Some(match &item.detail {
                Some(detail) => format!("{detail}  (ambiguous)"),
                None => "ambiguous: more than one base declares it".to_string(),
            });
        }

        // **What the reader has typed, matched against the name they would be typing.** A member list has a prefix
        // like any other, and a member whose name does not answer it is dropped rather than merely ranked low — see
        // [`crate::completion::matching`] for the rule and why the client's own filter cannot do this alone (it
        // cannot see `to_string` when the reader typed `string`, and it does not know the words of a name).
        let matched = crate::completion::matching::quality(&item.label, &prefix);
        if matched == crate::completion::matching::NONE {
            continue;
        }

        scored.push(Scored {
            score: member_score(member, &class),
            matched,
            item,
        });
    }

    let (items, truncated) = ordered(scored, budget);
    let offered = items.len();

    // **A `.` typed on a pointer completes as `->`.** The list is the pointee's — what the reader meant — and the
    // operator they typed is the one thing about the answer that is wrong: `.size` on a `Widget*` does not compile.
    // So the operator is replaced as part of the insertion: the range grows one byte to the left (the `.`) and every
    // insert text gains the `->`. The handler keeps the rewrite for a client that cannot interpolate snippets by
    // noticing the prefix, and a client that filters on the label is unaffected (the label stays the member's name).
    // **…and only when the operator typed was the wrong one.** `followed_a_pointer` says "a pointer was followed to
    // find the class", which is also true of `p->` itself — and on an arrow this rewrite made every insert
    // `->append` with a range grown one byte left over the `>`, so accepting an item wrote `p-->append`. A reader on
    // `p->` typed the right operator; the rewrite is for the one case where the operator and the answer disagree,
    // which is a `.` on a pointer.
    let (replace, items) = if followed_a_pointer && !access.arrow {
        let operator = replace.start_offset.saturating_sub(1);
        let items: Vec<crate::completion::CompletionItem> = items
            .into_iter()
            .map(|mut item| {
                item.insert = format!("->{}", item.insert);
                item
            })
            .collect();
        (
            cpp_parser::SourceRange::new(operator, replace.length + 1),
            items,
        )
    } else {
        (replace, items)
    };

    let why = if offered > 0 {
        format!("the member query answered, with {offered} members")
    } else if hidden_by_access > 0 {
        // The distinction matters to whoever reads the log: "the class has no members" and "its members are
        // `private` from here" are different facts, and the second one has a fix the reader can apply.
        format!(
            "`{class}` declares {} member(s) and {hidden_by_access} of them are `private` or `protected` where the \
             cursor is",
            members.members.len() + hidden_by_access
        )
    } else {
        format!("`{class}` is declared and has no members this analysis can see")
    };

    // **A list that names where it stops is an incomplete answer**, and the client has to be able to tell it from a
    // complete one — `MemberList::unlisted` is exactly that field (the bases this walk could not open, with why). The
    // list is still offered: a partial list plus "ask again later" is better than a partial list that looks final.
    let incomplete = !members.unlisted.is_empty();

    MemberAnswer {
        set: CompletionSet {
            scope: class.to_string(),
            prefix,
            replace,
            truncated,
            incomplete,
            items,
        },
        why,
    }
}

/// A member list and **why it is what it is** — see [`members`], which is the only producer.
///
/// The reason travels with the answer because the two are one reading: a diagnostic that had to ask a second query
/// to find out why a list is empty would be a second reader of the same facts, and the two would drift apart the
/// first time either changed. It costs nothing when the list is full — the sentence is built at the same moment the
/// list is, and only a caller with an empty list has any use for it.
struct MemberAnswer {
    set: CompletionSet,
    /// A sentence for a log line: what was looked up and what came back.
    why: String,
}

/// **A name whose spelling the implementation reserved, offered to a reader who is not typing one.**
///
/// Reported with a screenshot: typing `_ser` in a project file produced a list that began
/// `_Adl_verify_range`, `_Add_alloc_size`, `_Adjacent_difference_no_overlap`, `_Adjust_manually_vector_aligned` —
/// MSVC's `std` internals, which are not names a program may write. The rule asked for is the reader's own: **if what
/// has been typed does not begin with `_`, do not offer what does**.
///
/// It is a *filter* and not a ranking, because a list of forty internals pushes the four names the reader wanted past
/// the budget: on a `std::` completion the reserved names are the majority. Typing `_` brings them back, which is what
/// makes it safe — every one of them is still reachable when somebody has a reason to reach for one.
fn reserved_for_the_implementation(name: &str, typed: &str) -> bool {
    name.starts_with('_') && !typed.starts_with('_')
}

/// The names visible at a cursor, from the scope tree and the index.
///
/// `with_table` is whether the language's own vocabulary — keywords, snippets, built-in type names — belongs in
/// this answer. It does in a **statement** and does not in a directive's argument.
/// **The adaptors `std::views` declares, when the scope being completed is that namespace.**
///
/// `(name, does it take arguments, detail)`. The arity is a *hint for the item's kind* — a callable is drawn as a function
/// and an object as a variable — and no argument list is inserted, because each adaptor's own overloads decide what a call
/// means.
fn the_views_adaptors_a_scope_names(
    scope: &str,
) -> Option<&'static [(&'static str, bool, &'static str)]> {
    let is_the_views_namespace =
        scope == "std::views" || scope == "ranges::views" || scope.ends_with("::views");
    if !is_the_views_namespace {
        return None;
    }
    Some(THE_VIEWS_ADAPTORS)
}

/// **The adaptors in `std::views`**, as the standard lists them — C++20's, plus the C++23 additions this server's language
/// level already writes.
const THE_VIEWS_ADAPTORS: &[(&str, bool, &str)] = &[
    ("all", false, "a view of the whole range"),
    ("as_const", false, "a view whose elements are const"),
    (
        "common",
        false,
        "a view with a common iterator and sentinel",
    ),
    ("counted", true, "a counted view over an iterator"),
    ("drop", true, "skip the first n elements"),
    ("drop_while", true, "skip while the predicate holds"),
    ("elements", true, "a view over one member of each element"),
    (
        "filter",
        true,
        "a view of the elements the predicate accepts",
    ),
    ("join", false, "flatten a range of ranges"),
    ("keys", false, "a view over the first member of each pair"),
    (
        "lazy_split",
        true,
        "a view of the subranges between separators",
    ),
    ("owning_view", true, "a view that owns its range"),
    ("ref_view", true, "a view that refers to a range"),
    ("reverse", false, "a view of the elements in reverse order"),
    ("split", true, "a view of the subranges between separators"),
    ("take", true, "the first n elements"),
    ("take_while", true, "the elements while the predicate holds"),
    (
        "transform",
        true,
        "a view with the function applied to each element",
    ),
    (
        "values",
        false,
        "a view over the second member of each pair",
    ),
    ("iota", true, "a sequence of increasing values"),
];

fn names(
    index: &ProjectIndex,
    scopes: &ScopeTree,
    root: &CppSyntaxNode,
    path: &Path,
    position: &crate::sema::resolve::NamePosition,
    offset: usize,
    with_table: bool,
    cuda: bool,
    budget: usize,
    unincluded: &[Unincluded],
) -> CompletionSet {
    let mut scored: Vec<Scored> = Vec::new();
    let mut listed_scope = position.scope.clone();
    let mut listed_prefix = position.written.clone();
    let mut replace = position.range;
    let mut truncated = false;
    // **A scope was written: `std::`, `ns::`, `Widget::`** — only what that scope holds may be offered. A keyword, a
    // snippet, a built-in type and a name from elsewhere in the file are all things that cannot follow a `::`; the
    // earlier code offered them, and the reader saw the `std::` list begin with `case`, `catch`, `class`.
    let mut inside_a_scope = !position.scope.is_empty();

    // **A written scope is answered from the scope itself, not from the offset.** The context came from the file's
    // own text while the offset handed here is the *rendering's* (they differ by everything the directives spliced in),
    // so asking the tree at that offset answers about a different position — measured: `std::ve` in a real file resolved
    // to scope `std` at the written offset and to an **empty** scope at the rendering's, which produced a list of zero
    // items. The scope is already known; only the prefix has to come from the caller.
    let listed = if inside_a_scope {
        Known::Yes(crate::index::project::NameCompletions {
            scope: position.scope.clone(),
            prefix: position.written.clone(),
            name_range: position.range,
            names: index
                .declarations_in(&position.scope, path)
                .into_iter()
                .map(|declaration| crate::index::project::OfferedName {
                    fact: declaration.fact.clone(),
                    file: declaration.file.clone(),
                    depth: 0,
                    from: crate::index::project::NameProvenance::Scope,
                })
                .collect(),
        })
    } else {
        crate::index::project::name_completions_at(index, scopes, root, path, offset)
    };

    match listed {
        Known::Yes(listed) => {
            listed_scope = listed.scope.clone();
            // **The tree's answer is a refinement, and it can say nothing at all.** `name_completions_at` reads the
            // position from the *tree*, and a documentation comment is not in the tree — a `[`Wid`]` target or an
            // `@code` block's word has no node, so the answer comes back with an empty prefix and an empty range. The
            // caller's `NamePosition` is then the only information there is: taking the tree's empty answer over it
            // meant a list of every name in the file beside a replace range of zero characters, so typing `Wid` after
            // `@see ` offered `grow` and `f` too.
            if listed.prefix.is_empty() {
                listed_prefix = position.written.clone();
            } else {
                listed_prefix = listed.prefix.clone();
            }
            replace = if listed.name_range.length == 0 {
                position.range
            } else {
                listed.name_range
            };
            inside_a_scope |= !listed_scope.is_empty();

            let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();

            for offered in &listed.names {
                // **A name the implementation owns is not offered to a reader who is not typing one.** This is what
                // kept the `std::` list full of `_Adl_verify_range`, `_Add_alloc_size`, `_Allocate_at_least_helper` —
                // reported with a screenshot from an editor. See [`reserved_for_the_implementation`].
                if reserved_for_the_implementation(&offered.fact.name, &listed_prefix) {
                    continue;
                }
                // The query hides what an inner scope hides. What it cannot hide is one spelling listed twice by
                // *two files* — a namespace two headers reopen, a declaration and its redeclaration — and the list
                // is a list of things to type.
                if !seen.insert(offered.fact.name.as_str()) {
                    continue;
                }

                let mut item = CompletionItem::declared(&offered.fact, &offered.file);
                item.replace = replace;

                // **What is being typed is the tail of the name.** Inside `std::` the reader writes `str` and means
                // `string`: a client filtering on the bare label would show `string` for `str` anyway (it is a
                // substring), but a qualified detail is what makes the *ordering* stable when two scopes declare
                // one name.
                if !listed.scope.is_empty() {
                    item.filter = Some(format!("{}::{}", listed.scope, offered.fact.name));
                }

                // **Matched against what the client would filter on**, which is `filter` when the item has one and the
                // label otherwise: inside `std::` the reader types `str` and the item's filter is `std::string`, so
                // matching the label alone would answer `str` with nothing.
                let matched = matching::quality(
                    item.filter.as_deref().unwrap_or(&item.label),
                    &listed_prefix,
                );
                if matched == matching::NONE {
                    continue;
                }

                scored.push(Scored {
                    score: name_score(offered),
                    matched,
                    item,
                });
            }
        }
        // The position is not answerable — a `::` that names a scope nothing declares, a cursor the scope tree
        // cannot place. The list stays empty and the table still contributes, because `#define ret|` has a use for
        // `return` whether or not any name is visible.
        Known::Unknown(_) | Known::No => {}
    }

    // **`std::views`' adaptors are standard names, and the index may hold none of them.** Measured: `members_of("std::views")`
    // answered **0** while `std::ranges` answered 125 — the `views` namespace is filled with `inline constexpr` adaptor
    // objects that the summary does not reach — so `numbers | std::views::f` completed nothing at all, on the header whose
    // whole purpose is those names. The set is closed and the names are the standard's, which is the argument
    // `PREDEFINED_MACROS` makes for the compiler's own macros; a name the index also holds is merged by label below.
    if let Some(adaptors) = the_views_adaptors_a_scope_names(&listed_scope) {
        for (name, takes_arguments, detail) in adaptors {
            let matched = matching::quality(name, &listed_prefix);
            if matched == matching::NONE {
                continue;
            }
            let mut item = CompletionItem::word(
                name,
                if *takes_arguments {
                    ItemKind::Function
                } else {
                    ItemKind::Variable
                },
                detail,
            );
            item.replace = replace;
            item.filter = Some(format!("{listed_scope}::{name}"));
            scored.push(Scored {
                score: Score::new(Score::DIRECT_INCLUDE, 0),
                matched,
                item,
            });
        }
    }

    // **Nothing from the vocabulary table inside a written scope.** A `::` can only be followed by a name that scope
    // declares, so a keyword, a snippet and a built-in type are all wrong there — and the earlier code offered them,
    // which is why the `std::` list started with `case`, `catch`, `class`.
    if with_table && !inside_a_scope {
        let statements = true;
        let in_a_class = in_a_class_body(scopes, offset);

        for snippet in table::snippets_for(statements) {
            let matched = matching::quality(snippet.trigger, &listed_prefix);
            if matched == matching::NONE {
                continue;
            }
            scored.push(Scored {
                score: Score::new(Score::SNIPPET, 0),
                matched,
                item: CompletionItem::snippet(snippet.trigger, snippet.detail, snippet.body),
            });
        }

        for keyword in table::keywords_for(statements, in_a_class) {
            // A snippet that writes the same word already stands for it: two items with one label and different
            // effects is a choice to make by accident.
            if table::a_snippet_writes_this(keyword.spelling) {
                continue;
            }
            let matched = matching::quality(keyword.spelling, &listed_prefix);
            if matched == matching::NONE {
                continue;
            }
            scored.push(Scored {
                score: Score::new(Score::KEYWORD, 0),
                matched,
                item: CompletionItem::word(keyword.spelling, ItemKind::Keyword, keyword.detail),
            });
        }

        // The built-in type names that are not keywords (`size_t`, `char16_t`). They are names rather than
        // keywords because that is how a compiler reads them, and they are here because a file that never includes
        // `<cstddef>` still writes `size_t`.
        for (name, detail) in table::BUILTIN_TYPES {
            let matched = matching::quality(name, &listed_prefix);
            if matched == matching::NONE {
                continue;
            }
            scored.push(Scored {
                score: Score::new(Score::KEYWORD, 0),
                matched,
                item: CompletionItem::word(name, ItemKind::Class, detail),
            });
        }

        // **CUDA's vocabulary, when the project is CUDA.** `__global__` is an identifier to the lexer and a specifier
        // to a CUDA compiler, so what may be written here is a fact about the *family* — and offering it in a file no
        // CUDA compiler will see is a claim that is false. The kinds differ on purpose: a qualifier is a keyword, a
        // built-in variable is a variable, and a vector type is a class, because that is what each would be if a
        // toolkit header had declared it.
        if cuda {
            for word in crate::cuda::words() {
                let matched = matching::quality(word.name, &listed_prefix);
                if matched == matching::NONE {
                    continue;
                }
                let kind = match word.kind {
                    crate::cuda::WordKind::Qualifier => ItemKind::Keyword,
                    crate::cuda::WordKind::Builtin => ItemKind::Variable,
                    crate::cuda::WordKind::VectorType => ItemKind::Class,
                };
                scored.push(Scored {
                    score: Score::new(Score::KEYWORD, 0),
                    matched,
                    item: CompletionItem::word(word.name, kind, word.detail),
                });
            }
        }
    }

    // **Nothing that matched nothing survives a typed prefix.** The client filters the list by what was typed and
    // drops those rows anyway — keeping them only made the *budget* shorter for the names that can be what the
    // reader is writing. Measured with a prefix: the corpus answers 3 items at `fpr` and would answer 1000+ if the
    // non-matching names were carried along; the CUDA arm above has filtered this way from the start.
    if !listed_prefix.is_empty() {
        scored.retain(|one| one.matched != matching::NONE);
    }

    // **And the names a related header declares but this file cannot see** — offered *with* the include that makes
    // them usable, which is what an accept has to carry. They are added before the label deduplication, so a name the
    // file can already see wins over the same name from a header it does not include.
    if !unincluded.is_empty() && !inside_a_scope {
        let labels: std::collections::HashSet<String> =
            scored.iter().map(|one| one.item.label.clone()).collect();
        for related in unincluded {
            let Some(summary) = index.summary(&related.file) else {
                continue;
            };
            for fact in &summary.declarations {
                if fact.kind != DeclKind::Type || labels.contains(&fact.name) {
                    continue;
                }
                let matched = matching::quality(&fact.name, &listed_prefix);
                if matched == matching::NONE {
                    continue;
                }
                scored.push(Scored {
                    score: Score::new(Score::UNINCLUDED, Score::kind_penalty(fact.kind)),
                    matched,
                    item: CompletionItem::unincluded(
                        fact,
                        &related.file,
                        related.inclusion.clone(),
                    ),
                });
            }
        }
    }

    // **One row per label.** Two arms can offer one name — the index's adaptor and the `std::views` table's fallback for
    // it, a keyword and the table's snippet — and a list with two identical rows is a choice to make by accident. The
    // order is by score, so the first of a label is the better one; the rest are dropped.
    {
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        scored.retain(|one| seen.insert(one.item.label.clone()));
    }

    let (items, cut) = ordered(scored, budget);
    truncated |= cut;

    CompletionSet {
        items,
        scope: listed_scope,
        prefix: listed_prefix,
        replace,
        truncated,
        // A name list is not a member list: nothing here can be *missing* because a class was not read.
        incomplete: false,
    }
}

/// The directives themselves, after a `#`.
///
/// Filtered by the same rule as every other list — see [`crate::completion::matching`] — so that `#ifnd` finds
/// `ifndef` and `#inc` finds `include` for the same reason a name list answers the initials of its words.
fn directives(written: &str, range: SourceRange) -> CompletionSet {
    let items: Vec<CompletionItem> = table::DIRECTIVES
        .iter()
        .filter(|directive| matching::quality(directive.name, written) != matching::NONE)
        .map(|directive| {
            let mut item =
                CompletionItem::word(directive.name, ItemKind::Keyword, directive.detail);
            item.replace = range;
            item
        })
        .collect();

    CompletionSet {
        scope: String::new(),
        prefix: written.to_string(),
        replace: range,
        truncated: false,
        incomplete: false,
        items,
    }
}

/// **Inside a documentation comment** — Doxygen's vocabulary, and then the name that command takes.
///
/// ```cpp
/// /// @par|              → `param`, `paragraph`, … (filtered, and by the same quality rule as every other list)
/// /// @param |           → the parameter names of the declaration below the comment
/// /// @tparam |          → its template parameters
/// ```
///
/// The commands come from the **parser's own table** ([`cpp_parser::every_command`]), which is the single list of
/// what may follow an `@`: a completion carrying its own copy would be a second source of truth, free to disagree
/// about `@retval` the day one of them is updated.
///
/// The names come from the **facts**, not from the tree: the declaration a comment documents is the first one after
/// it, and the index already says what its parameters are called (`DeclFact::parameters` for the template head and
/// `parameter_list` for the parameter list). A comment above a declaration in *another* file cannot be reached from
/// here, and does not need to be — a completion is asked in the file being written.
fn doc_comments(
    index: &ProjectIndex,
    path: &Path,
    written: &str,
    range: SourceRange,
    wants: Option<cpp_parser::DocCommandKind>,
) -> CompletionSet {
    use cpp_parser::DocCommandKind;

    let mut items: Vec<CompletionItem> = Vec::new();
    match wants {
        // **The name the command takes.** `@param`/`@tparam` want a parameter of the documented declaration, and
        // `@exception`/`@ref` want a name this layer has no better answer for than the ones in scope — so those
        // are answered with nothing rather than with a wrong list.
        Some(DocCommandKind::Parameter) => {
            let Some(summary) = index.summary(path) else {
                return CompletionSet {
                    prefix: written.to_string(),
                    replace: range,
                    ..CompletionSet::default()
                };
            };

            // **The declaration the comment documents** — the first one that starts after the comment. `range`
            // here is the span of the *typed name*, so the comment is what precedes it on an earlier line; the
            // fact's own start is after the comment's text either way.
            let documented = summary
                .declarations
                .iter()
                .filter(|fact| fact.range.start_offset > range.start_offset)
                .min_by_key(|fact| fact.range.start_offset);

            if let Some(fact) = documented {
                // A **template parameter** is documented with `@tparam` and a function's parameter with `@param`,
                // and the fact separates the two: `parameters` is the template head, `parameter_list` the
                // parameter list. Both are offered, because which command the reader typed is a spelling and the
                // name they want is a name.
                // **The empty name is a slot, not a parameter.** `fact.parameters` keeps one entry per template
                // parameter so that arguments pair with names by position, and an **unnamed** parameter's entry is
                // the empty string (`template <typename, class T>` is `["", "T"]`). It is not a name a reader can be
                // told about — offering it would put a blank item in the list.
                let mut names: Vec<String> = fact
                    .parameters
                    .iter()
                    .filter(|name| !name.is_empty())
                    .cloned()
                    .collect();
                if let Some(list) = &fact.parameter_list
                    && let Some(found) = crate::inlay::parameter_names_from_text(list)
                {
                    names.extend(found.into_iter().flatten());
                }

                for name in names {
                    if matching::quality(&name, written) == matching::NONE {
                        continue;
                    }
                    let mut item = CompletionItem::word(&name, ItemKind::Variable, "a parameter");
                    item.replace = range;
                    items.push(item);
                }
            }
        }
        Some(_) => {}
        // **A command's own name**: the whole vocabulary, filtered by what has been typed.
        None => {
            for spec in cpp_parser::every_command() {
                if matching::quality(spec.name, written) == matching::NONE {
                    continue;
                }
                let detail = match spec.kind {
                    DocCommandKind::Description => "describe",
                    DocCommandKind::Parameter => "a parameter",
                    DocCommandKind::Exception => "an exception",
                    DocCommandKind::Reference => "a reference",
                    DocCommandKind::Advisory => "a note",
                    DocCommandKind::Structural => "structure",
                    DocCommandKind::Callout => "a callout",
                };
                let mut item = CompletionItem::word(spec.name, ItemKind::Keyword, detail);
                item.replace = range;
                items.push(item);
            }
        }
    }

    CompletionSet {
        scope: String::new(),
        prefix: written.to_string(),
        replace: range,
        truncated: false,
        incomplete: false,
        items,
    }
}

/// **A `#define`'s replacement list** — its own parameters, and the macros already defined.
///
/// ```cpp
/// #define MAX(a, b) ((a) > (b) ? (a) : (b))
/// #define MAX_OF_THREE(a, b, c) MAX(MAX(a, b), c)
/// ```
///
/// The parameters come first because they are the names that exist **nowhere else**: the index has never heard of
/// `a`, and a reader who mistypes it gets a macro that quietly substitutes nothing. The macros follow, because a
/// body that composes another macro is the other half of what a replacement list is written from.
fn macro_body(
    index: &ProjectIndex,
    path: &Path,
    written: &str,
    range: SourceRange,
    parameters: &[String],
) -> CompletionSet {
    let mut items: Vec<CompletionItem> = Vec::new();

    for parameter in parameters {
        if matching::quality(parameter, written) == matching::NONE {
            continue;
        }
        let mut item =
            CompletionItem::word(parameter, ItemKind::Variable, "a parameter of this macro");
        item.replace = range;
        items.push(item);
    }

    for name in macro_names(index, path) {
        if matching::quality(name, written) == matching::NONE {
            continue;
        }
        let mut item = CompletionItem::word(name, ItemKind::Macro, "a macro");
        item.replace = range;
        items.push(item);
    }

    CompletionSet {
        scope: String::new(),
        prefix: written.to_string(),
        replace: range,
        truncated: false,
        incomplete: false,
        items,
    }
}

/// **The macros this file can see** — its own and those of the headers it includes directly, sorted and deduplicated.
///
/// The list a *preprocessor position* completes from: a `#define`'s body, `#if`, `#elif`, `#ifdef`, `#undef`. A macro
/// two headers away is reachable only through the macro environment, which is the hover's question, not this one's —
/// so the boundary is the direct includes, the same one `names` uses for the same reason.
fn macro_names<'a>(index: &'a ProjectIndex, path: &Path) -> Vec<&'a str> {
    let Some(summary) = index.summary(path) else {
        return Vec::new();
    };

    let mut macros: Vec<&str> = summary
        .macros
        .iter()
        .map(|fact| fact.name.as_str())
        .collect();
    for include in &summary.includes {
        let Some(resolved) = &include.resolved else {
            continue;
        };
        let Some(included) = index.summary(resolved) else {
            continue;
        };
        macros.extend(included.macros.iter().map(|fact| fact.name.as_str()));
    }
    // **The macros no file declares.** `__LINE__`, `__FILE__`, `__DATE__`, `__TIME__`, `__cplusplus` and the `__STDC_*`
    // family are defined by the compiler for every translation unit, so an index query cannot find them — and a
    // preprocessor condition is exactly where a reader writes them (`#if __cplusplus >= 202002L`). The compiler's own
    // table (`_MSC_VER`, `__GNUC__`, …) is the toolchain's, which this layer does not hold; these are the standard's.
    macros.extend(PREDEFINED_MACROS.iter().copied());
    macros.sort_unstable();
    macros.dedup();
    macros
}

/// **The macros every compiler defines**, which no declaration in any project does.
const PREDEFINED_MACROS: &[&str] = &[
    "__LINE__",
    "__FILE__",
    "__DATE__",
    "__TIME__",
    "__cplusplus",
    "__STDC__",
    "__STDC_HOSTED__",
    "__STDC_VERSION__",
];

/// **`#if`, `#elif`, `#ifdef`, `#ifndef`, `#undef`** — the vocabulary is the macros, and the operator on them.
///
/// ```cpp
/// #if |                 the macros this file can see, and `defined`
/// #if defined(|         the same: `defined` takes a macro name
/// #elif VERSION >= |    …and again, because the right-hand side of a comparison is a macro's value
/// ```
///
/// Nothing else belongs here. An `#if` expression is evaluated by the preprocessor before a single declaration
/// exists, so a function or a class name is not a candidate — offering the program's names, which is what a directive
/// argument used to do there, is offering words the condition can never mean.
fn condition(
    index: &ProjectIndex,
    path: &Path,
    written: &str,
    range: SourceRange,
) -> CompletionSet {
    let mut items: Vec<CompletionItem> = Vec::new();

    // **`defined` first**: the one operator a condition is written with, and a word of the preprocessor rather than a
    // macro anyone defined.
    for operator in ["defined", "__has_include", "__has_include_next"] {
        if matching::quality(operator, written) == matching::NONE {
            continue;
        }
        let mut item = CompletionItem::word(operator, ItemKind::Keyword, "a preprocessor operator");
        item.replace = range;
        items.push(item);
    }

    for name in macro_names(index, path) {
        if matching::quality(name, written) == matching::NONE {
            continue;
        }
        let mut item = CompletionItem::word(name, ItemKind::Macro, "a macro");
        item.replace = range;
        items.push(item);
    }

    CompletionSet {
        scope: String::new(),
        prefix: written.to_string(),
        replace: range,
        truncated: false,
        incomplete: false,
        items,
    }
}
/// The headers a `#include` may name.
fn headers_for(
    headers: &HeaderIndex,
    written: &str,
    closed: bool,
    range: SourceRange,
) -> CompletionSet {
    // `#include <vector>` with the cursor at the end: the name is written, and offering another one would insert a
    // second header into a directive that already has one.
    if closed {
        return CompletionSet {
            prefix: written.to_string(),
            replace: range,
            ..CompletionSet::default()
        };
    }

    let items: Vec<CompletionItem> = headers
        .matching(written, HEADER_BUDGET)
        .into_iter()
        .map(|header| {
            let mut item = CompletionItem::header(&header);
            item.replace = range;

            // **Where the header comes from**, which is the one thing a reader cannot see from the name and the one
            // thing that decides whether the include will resolve — and, since a real search path holds four
            // thousand headers of which a hundred and fifty are the standard library's, the thing that decides
            // which one they meant.
            item.detail = Some(match header.kind {
                HeaderKind::StandardLibrary => "the C++ standard library".to_string(),
                HeaderKind::Project => "this project".to_string(),
                HeaderKind::System => "on the include path".to_string(),
            });
            item
        })
        .collect();

    CompletionSet {
        scope: String::new(),
        prefix: written.to_string(),
        replace: range,
        truncated: headers.truncated(),
        incomplete: false,
        items,
    }
}

/// The part of a member's spelling that lies **before** the cursor.
///
/// Separate from the range because the two answer different halves of one edit: the range is what the client
/// **replaces** (`size`, so nothing of the old spelling is left behind) while this is what filters the list — and a
/// cursor inside a name has only typed the part before it. Taking the whole spelling for both is what makes
/// `w.si|ze` offer nothing.
fn written_before(access: &crate::sema::resolve::MemberAccess, offset: usize) -> String {
    let start = access.member_range.start_offset;
    let end = access.member_range.end_offset().min(offset);

    if end <= start {
        return String::new();
    }

    access
        .member
        .get(..end - start)
        .unwrap_or(&access.member)
        .to_string()
}

/// Which kind of member this is, for the icon: a member function is a method, a variable is a field, and a function
/// whose name spells its own class is a constructor.
fn member_kind(member: &ProjectMember, class: &str) -> ItemKind {
    match member.fact.kind {
        DeclKind::Function if member.fact.name == class => ItemKind::Function,
        DeclKind::Function => ItemKind::Method,
        DeclKind::Variable => ItemKind::Field,
        DeclKind::Type => ItemKind::Class,
        DeclKind::Namespace => ItemKind::Namespace,
        DeclKind::MacroLike => ItemKind::Macro,
        DeclKind::Other => ItemKind::Field,
    }
}

/// How many headers one `#include` offers.
const HEADER_BUDGET: usize = 200;

/// How many items one completion offers before it is cut short.
///
/// A **payload** bound rather than a UI one: a client renders ten rows and still receives all of them, and 14 351
/// items was 4.5 MB of JSON for one keystroke. Two hundred is more than any list a reader scrolls and small enough
/// that the request stays a few kilobytes.
pub const ITEM_BUDGET: usize = 1000;

/// Put the items in order, apply the budget, and say whether anything was cut.
///
/// The sort is **stable**, which is what makes it a refinement rather than a re-decision: two items the gathering
/// layer produced in one order and the score cannot separate keep that order, so the query's own ordering (C++'s,
/// by how far the lookup walked) survives wherever the score has nothing to say.
///
/// # The budget is spent **fairly**, not first-come
///
/// Sorting is not enough on its own, because the deepest tier is the widest: every name of every included header has
/// the same score, so the alphabetical tiebreak decides which 200 survive — and an alphabetical cut of thousands of
/// names reaches only the first header's `a`–`b`. Measured through the real server at `fprintf(` in a 200-line C file
/// that includes `<stdio.h>`: 200 items, `first: ["code", "add", "average"]`, and **`fprintf` absent** — the reader
/// then types `fpr`, the client filters those 200 and the popup is empty, which is reported as "completion never works
/// here" when the analysis answered perfectly well. So the cut is made **round-robin per declaring file**: each file
/// contributes a share, and a header with a thousand names cannot starve one with ten.
fn ordered(mut scored: Vec<Scored>, budget: usize) -> (Vec<CompletionItem>, bool) {
    let by_rank = |one: &Scored, other: &Scored| {
        // **How well it answers what was typed, before where the declaration is.** `str` must put `string` above
        // `to_string` — the module's own rule — and the tier alone does not express that: measured with `fpr` in a
        // C file, the list began `functions_pointers` (a *local*, matched as a word-start) above `fprintf` (an
        // exact prefix match from `<stdio.h>`). A reader who typed three characters of a name means that name, and
        // "nearer" is a tiebreak between the candidates that answer equally well — not a veto over them.
        other
            .matched
            .cmp(&one.matched)
            .then_with(|| one.score.keys().cmp(&other.score.keys()))
            // **Then the alphabetical tiebreak**, which keeps a list stable between keystrokes.
            .then_with(|| one.item.label.cmp(&other.item.label))
    };
    scored.sort_by(by_rank);

    if scored.len() <= budget {
        return (
            scored.into_iter().map(|scored| scored.item).collect(),
            false,
        );
    }

    // One bucket per declaring file, first seen in rank order — so the *nearest* file's names still lead, and an item
    // with no identity (a snippet, a keyword, a member) is a bucket of its own.
    let mut buckets: Vec<Vec<Scored>> = Vec::new();
    let mut which: std::collections::HashMap<Option<std::path::PathBuf>, usize> =
        std::collections::HashMap::new();
    for one in scored {
        let key = one.item.identity.as_ref().map(|(file, _)| file.clone());
        let index = *which.entry(key).or_insert_with(|| {
            buckets.push(Vec::new());
            buckets.len() - 1
        });
        buckets[index].push(one);
    }

    // Draw one item per bucket per round until the budget is full. The chosen items are then **re-sorted by the same
    // order**, because a fair draw is a choice of *which* items survive, not a new ranking: a reader must never see
    // `abort` above the local variable in front of them because a bucket happened to be drawn first.
    let widest = buckets.iter().map(Vec::len).max().unwrap_or(0);
    let mut taken: Vec<Scored> = Vec::with_capacity(budget);
    'fill: for round in 0..widest {
        for bucket in &buckets {
            let Some(one) = bucket.get(round) else {
                continue;
            };
            taken.push(one.clone());
            if taken.len() == budget {
                break 'fill;
            }
        }
    }
    taken.sort_by(by_rank);

    (taken.into_iter().map(|scored| scored.item).collect(), true)
}

/// **How near a declaration is to the cursor**, which is the whole of the ranking.
///
/// A tier plus a penalty, and the two are separate because they answer different questions: the tier is *where the
/// declaration is* (the reader's body, this file, a header the file includes) and the penalty is *what kind of
/// thing it is* (a value before a type, a variable before a macro). The tier dominates, because "nearer
/// textually" is the signal that survives every language and every project.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Score {
    tier: i32,
    penalty: i32,
}

impl Score {
    /// A name declared in a scope of the file being edited — a local, a parameter, a member of the class the
    /// cursor's body is in, or the names written directly in the `::`-qualified scope that was asked about.
    const LOCAL: i32 = 0;
    /// A name at **file scope** in the file being edited.
    const FILE: i32 = 100;
    /// A snippet: a shape the reader is about to write. Between their own names and the headers', because a
    /// construct is likelier than a name from `<cstdio>` and unlikelier than the variable in front of them.
    const SNIPPET: i32 = 140;
    /// A keyword or a built-in type name.
    const KEYWORD: i32 = 150;
    /// A name from a header the file includes **directly**.
    const DIRECT_INCLUDE: i32 = 200;
    /// A name from a header reached through another header: the standard library's own, mostly.
    const INDIRECT_INCLUDE: i32 = 300;
    /// **A name from a header this file does not include** — offered only when it is strongly related, and ranked
    /// after every name that resolves today, because accepting it also edits the file.
    const UNINCLUDED: i32 = 400;

    fn new(tier: i32, penalty: i32) -> Score {
        Score { tier, penalty }
    }

    /// The comparable key. A method rather than a derived `Ord` so that the field order is stated once, where a
    /// reader looking for "what sorts first" will find it.
    fn keys(&self) -> (i32, i32) {
        (self.tier, self.penalty)
    }

    /// A small nudge within a tier: a **value** before a type, a variable before a namespace.
    ///
    /// Not a filter, and deliberately small — a type is very often exactly what is being written (`Widget w;`) —
    /// so this reorders two candidates that were equally near and never decides whether one is offered at all.
    fn kind_penalty(kind: DeclKind) -> i32 {
        match kind {
            DeclKind::Variable | DeclKind::Function => 0,
            DeclKind::Type => 4,
            DeclKind::Other => 5,
            DeclKind::Namespace => 6,
            DeclKind::MacroLike => 8,
        }
    }
}

/// The score of a name the scope walk produced: **how far from the cursor its file is**, plus what it declares.
fn name_score(offered: &crate::OfferedName) -> Score {
    use crate::index::project::NameProvenance;

    let tier = match offered.from {
        // A scope of this file — which is where the *depth* earns its place: the scope the cursor is in comes
        // first, then each enclosing one outward, which is the order C++ looks in.
        NameProvenance::Scope => Score::LOCAL + offered.depth as i32,
        NameProvenance::ThisFile => Score::FILE,
        NameProvenance::DirectInclude => Score::DIRECT_INCLUDE,
        NameProvenance::IndirectInclude => Score::INDIRECT_INCLUDE,
    };

    // A destructor is spelled `~D` and a conversion function is not reachable by its spelling either. Both are
    // listed — they are real declarations — but after everything a reader could be typing the start of.
    let penalty = Score::kind_penalty(offered.fact.kind)
        + if offered.fact.name.starts_with('~') {
            20
        } else {
            0
        };

    Score::new(tier, penalty)
}

/// The score of a member of an accessed type.
fn member_score(member: &ProjectMember, class: &str) -> Score {
    // An inherited member is reachable but is not what the class itself declares, so it comes after the class's
    // own — the order C++ looks in, and the order a reader expects to see. The base walk produced the depth.
    let tier = Score::LOCAL + 10 * member.depth as i32;

    let penalty = Score::kind_penalty(member.fact.kind)
        + if member.fact.name == class { 6 } else { 0 }
        + if member.fact.name.starts_with('~') {
            20
        } else {
            0
        };

    Score::new(tier, penalty)
}

/// Is the cursor inside a class body, so that `public`, `virtual` and `friend` may be written?
fn in_a_class_body(scopes: &ScopeTree, offset: usize) -> bool {
    let Some(innermost) = scopes.scope_at(offset) else {
        return false;
    };

    scopes.scope_chain(innermost).iter().any(|scope| {
        matches!(
            scopes.scope(*scope).map(|data| data.kind),
            Some(ScopeKind::Class | ScopeKind::Enum)
        )
    })
}

/// **An index of headers**, read from a configuration and a project's own file list.
///
/// The one constructor a session needs, so that the walk and its budget are decided in one place rather than at the
/// call site: the search path first — that is what `<…>` means — and the project's files after it, which is what
/// the quoted form is resolved against.
///
/// Shared and behind a lock rather than owned, because one half of it can grow: [`crate::Session::add_project_files`]
/// hands over more of the project after the session is built, and the header list has to see them.
pub fn header_index(
    config: &crate::CompilerConfig,
    root: &Path,
    project_files: impl IntoIterator<Item = PathBuf>,
) -> SharedHeaders {
    Arc::new(std::sync::RwLock::new(
        HeaderIndex::read(includes::search_directories(config), root).with_project(project_files),
    ))
}

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

    /// **A name that does not answer what was typed is dropped, not ranked low.** The rule itself lives in
    /// [`crate::completion::matching`] and is tested there; this is the property the list depends on — that the
    /// filtering happens on this side at all, so a client does not have to receive and sort several hundred names to
    /// show four.
    #[test]
    fn a_candidate_that_does_not_answer_the_prefix_is_dropped() {
        use crate::completion::matching::{NONE, PREFIX, SUBSEQUENCE, WORD_START, quality};

        assert_eq!(quality("Widget", "wid"), PREFIX);
        assert_eq!(
            quality("Widget", ""),
            quality("Widget", ""),
            "the empty prefix matches everything"
        );
        // The fuzzy tiers are why this is not `starts_with` any more: `bsc` is nowhere in `basic_string` as a
        // prefix, and the analysis still offers it. Which *tier* it earns is the matching module's business — what
        // this test is about is that a candidate the rule rejects is dropped and one it accepts is not.
        assert!(quality("basic_string", "bsc") > NONE);
        assert_eq!(quality("get_parent_id", "gpid"), WORD_START);
        // The characters are not in `Widget` at all, so it is dropped rather than ranked last.
        assert_eq!(quality("Widget", "xyz"), NONE);
        assert_eq!(quality("Widget", "wz"), NONE);
        // …and this one is in there in order, which is a real match and the lowest tier.
        assert_eq!(quality("Widget", "wdgt"), SUBSEQUENCE);
    }

    /// The **order of the tiers** is the feature, so it is asserted rather than assumed: a local before a keyword,
    /// a keyword before a name from a header this file includes, and that before one from a header only a header
    /// includes.
    ///
    /// The constants are `const`, so the comparison is one rustc folds away — and that is the point rather than a
    /// waste: this test fails to *compile* the day two tiers are put in the wrong order, which is the earliest any
    /// test could notice.
    #[test]
    fn the_tiers_are_in_the_order_a_reader_expects() {
        const _: () = assert!(Score::LOCAL < Score::SNIPPET);
        const _: () = assert!(Score::SNIPPET < Score::KEYWORD);
        const _: () = assert!(Score::KEYWORD < Score::DIRECT_INCLUDE);
        const _: () = assert!(Score::DIRECT_INCLUDE < Score::INDIRECT_INCLUDE);
    }

    /// **A function's row shows what it takes.** The one thing a reader choosing between `format`, `format_to` and
    /// `format_to_n` has to see, and the thing this model did not record until it had a parameter list: every
    /// function in another file used to be described as `returns (…)`.
    ///
    /// The `(…)` survives only where it is still the truth — a fact written before the field existed, or a declarator
    /// the reading could not reach — and that case is asserted here too, because a fallback nobody tests is a
    /// fallback that silently stops working.
    #[test]
    fn a_functions_detail_line_is_what_it_takes() {
        let fact = |returns: Option<&str>, parameter_list: Option<&str>| DeclFact {
            frees: 0,
            reflection: None,
            name: "format".to_string(),
            scope: Some("std".to_string()),
            local: false,
            in_namespace: None,
            kind: DeclKind::Function,
            modifiers: crate::DeclModifiers::VIRTUAL,
            type_of: None,
            returns: returns.map(str::to_string),
            bases: Vec::new(),
            parameters: Vec::new(),
            constraints: Vec::new(),
            // A clause is the declaration's text, and this literal is a fixture with no text to read.
            requires_clause: None,
            parameter_defaults: Vec::new(),
            pattern: None,
            parameter_list: parameter_list.map(str::to_string),
            range: cpp_parser::SourceRange::new(0, 0),
            name_range: cpp_parser::SourceRange::new(0, 0),
            clean: true,
            split_by_a_directive: false,
            guard: crate::FactGuard::Unconditional,
            access: None,
            exported: false,
            definition: true,
        };

        assert_eq!(
            detail_of(&fact(Some("string"), Some("(_Fmt, _Args...)"))).as_deref(),
            Some("string (_Fmt, _Args...)"),
            "the return type and the parameters, as the file spells them"
        );
        assert_eq!(
            detail_of(&fact(Some("string"), Some("()"))).as_deref(),
            Some("string ()"),
            "a function that takes nothing says so — that is an answer, not an absence"
        );
        assert_eq!(
            detail_of(&fact(Some("string"), None)).as_deref(),
            Some("string (…)"),
            "and with no list recorded, the old spelling is still the honest one"
        );
        assert_eq!(
            detail_of(&fact(None, Some("(int)"))).as_deref(),
            Some("(int)"),
            "a constructor has no return type, and its parameters are then the whole description"
        );
        assert_eq!(detail_of(&fact(None, None)), None, "nothing to say");
    }
}