rllvm-query 0.8.0

Source-level queries over LLVM bitcode captured by rllvm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
//! Source-level queries over bitcode captured by
//! [rllvm](https://crates.io/crates/rllvm).
//!
//! This is the only crate in the workspace that links LLVM, through
//! `llvm-sys`. The wrappers that capture bitcode, and the library behind
//! them, do not depend on it.
//!
//! Every answer is wrapped in [`QueryResult`], this project's honesty
//! surface. Four rules hold for every query, not just the ones that
//! obviously need them:
//!
//! 1. `scope` is quoted from the catalog and never shrinks. A module that
//!    failed to parse, went missing, or failed hash verification is counted
//!    in the separate `analysis` block instead. Merging the two would let a
//!    parse failure silently narrow the program the answer claims to
//!    describe.
//! 2. `analysis.modules` carries `ir_stage` and `debug_info` per module, not
//!    as one aggregate: a mixed catalog is ordinary, and one summary flag
//!    would misrepresent it.
//! 3. Indirect call sites are never dropped from a `callees` answer. They
//!    appear as unresolved with their locations, so the answer does not read
//!    as a complete list of what a function calls.
//! 4. An empty `reach` result is not unreachability. It means "no path over
//!    resolved edges within the selected scope", and `uncertainty` names the
//!    indirect sites and ambiguous bindings that could carry a path the walk
//!    cannot see.

// Keeps the public surface deliberate: a `pub` item that no `pub use`
// re-exports is a mistake, not API.
#![warn(unreachable_pub)]

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

use serde::Serialize;

use rllvm_core::{
    catalog::{CatalogOrigin, CatalogScope, ModuleCatalog},
    error::Error,
};

/// Command-line definitions for the `rllvm-query` binary. Not a supported
/// interface.
#[doc(hidden)]
pub mod cli;

pub mod extract;
pub use extract::{ModuleFacts, llvm_version};

pub mod facts;
pub use facts::*;

pub mod load;

pub mod bind;
pub use bind::{BindingCandidate, BindingStatus, SymbolBinding};

pub mod cache;
pub use cache::{CacheUsage, Cleared, FactsCache, GenerationUsage, render_usage};

/// How the per-module facts cache served one load. Present on an answer only
/// when the session was opened with a cache.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct CacheReport {
    /// Modules whose facts came from the cache; their bytes were not re-read.
    pub hits: usize,
    /// Modules extracted because the cache had no usable entry.
    pub misses: usize,
    /// Misses whose facts were stored for next time.
    pub written: usize,
    /// Size of every entry on disk: measured once before this load's writes,
    /// plus what it wrote.
    pub disk_bytes: u64,
    /// `query_cache_warn_mb`, in bytes.
    pub warn_bytes: u64,
    pub over_threshold: bool,
}

pub mod index;
pub use index::{
    Direction, NameMatch, NameResolution, PathStep, ReachResult, Session, SliceEdge, SliceResult,
};

pub mod overlay;
pub use overlay::{
    Confidence, EdgeKey, OVERLAY_VERSION, Overlay, OverlayCoverage, OverlayEdge, OverlaySummary,
    OverlayView, Record, SummaryEdge, TargetSpec, Verdict, Verification, default_overlay_path,
};

pub mod mcp;

pub mod render;
pub use render::{Color, TextMode, render};

pub mod slice;
pub use slice::{EmittedModule, emit_module, emit_slice};

#[cfg(test)]
pub(crate) mod testing;

/// One of the twelve source-level queries. Serializes with a `kind` tag, e.g.
/// `{"kind": "callers", "name": "parse_frame"}`.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Query {
    /// Every definition of the symbol, with module and configuration.
    Defs { name: String },
    /// Functions with at least one instruction mapped to `file:line`, and
    /// the call sites recorded there. Deliberately not source-range
    /// containment: a line that generated no instructions answers empty
    /// rather than guessing at a containing function.
    At { file: String, line: u32 },
    /// Functions containing a call to the target, each with its call sites.
    Callers { name: String },
    /// Outgoing call sites of the target, classified. Includes unresolved
    /// indirect sites: they are evidence of uncertainty, not omitted.
    Callees { name: String },
    /// Non-call uses: how and where the function's address is taken.
    Uses { name: String },
    /// One supporting path from `from` to `to`, or its explicit absence.
    /// Enumerating every path is out of scope.
    Reach {
        from: String,
        to: String,
        /// Also walk agent-proposed edges from the overlay. Never proof:
        /// every step through one is labeled `agent`.
        #[serde(default, skip_serializing_if = "is_false")]
        include_overlay: bool,
        /// The weakest overlay edge walked; `None` means `low`, every edge
        /// not refuted.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        min_confidence: Option<Confidence>,
    },
    /// Every function on some path from `from` to `to`, with the edges
    /// among them. Empty when no path exists over the edges walked.
    Slice {
        from: String,
        to: String,
        /// As for `Reach`.
        #[serde(default, skip_serializing_if = "is_false")]
        include_overlay: bool,
        /// As for `Reach`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        min_confidence: Option<Confidence>,
    },
    /// The set that can reach the target (`In`) or that it can reach
    /// (`Out`).
    Closure {
        name: String,
        direction: Direction,
        /// As for `Reach`.
        #[serde(default, skip_serializing_if = "is_false")]
        include_overlay: bool,
        /// As for `Reach`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        min_confidence: Option<Confidence>,
    },
    /// Unbound symbols: the captured program's boundary.
    Externals,
    /// Definitions a Rust module makes C-callable: external, attributed to
    /// Rust, and exported under a name that is not mangled, which is what
    /// `#[no_mangle]` and `#[export_name]` produce.
    FfiExports,
    /// `!callees` at a call site, when CVP produced it; otherwise
    /// unresolved. `at` is a `file:line` location, e.g. `"t.c:4"`.
    IndirectTargets { at: String, heuristics: bool },
    /// Unresolved indirect call sites grouped by the record field they
    /// dispatch through, with the functions stored into that field. A join
    /// of facts: candidates, never edges.
    ResolutionCandidates,
}

/// One definition of a queried symbol.
#[derive(Debug, Serialize)]
pub struct DefEntry {
    pub function: FunctionId,
    /// Quoted from the defining module's `ModuleReport`, not reconstructed.
    pub configuration_id: Option<String>,
    pub location: Option<SourceLocation>,
}

/// One function found at a queried location, with the call sites it makes
/// there.
#[derive(Debug, Serialize)]
pub struct AtEntry {
    pub function: FunctionId,
    pub call_sites: Vec<CallSiteFact>,
}

/// One function calling the queried target, with its call sites.
#[derive(Debug, Serialize)]
pub struct CallerEntry {
    pub function: FunctionId,
    pub call_sites: Vec<CallSiteFact>,
}

/// The answer to `indirect-targets`, built from three fields that are never
/// merged.
#[derive(Debug, Serialize)]
pub struct IndirectTargetsResult {
    pub site: CallSiteId,
    pub location: Option<SourceLocation>,
    pub signature: String,
    /// From `!callees`. An LLVM-derived upper bound: a defined execution of
    /// the call cannot target a function outside this set. Absent when CVP
    /// could not bound the call.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub llvm_target_bound: Option<Vec<FunctionId>>,
    /// True exactly when `llvm_target_bound` is absent.
    pub unresolved: bool,
    /// Opt-in only: `None` unless `heuristics` was requested. Derived from
    /// `ProgramFacts::uses`: a function with any recorded use has had its
    /// address taken somewhere in scope. A heuristic inventory, not a
    /// result, and never a source of graph edges.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address_taken_inventory: Option<Vec<FunctionId>>,
    /// Present only alongside the unfiltered `address_taken_inventory`,
    /// never instead of it: casting function pointers is routine in C.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_compatible: Option<Vec<FunctionId>>,
    /// States the bound this scope's soundness: `dlopen` and a callback
    /// registered by uncaptured code both escape it.
    pub assumptions: Vec<String>,
}

/// Unresolved indirect sites that share a dispatch, and the functions that
/// could be what they call. Never an edge: no walk follows it.
#[derive(Debug, Serialize)]
pub struct CandidateGroup {
    /// The field every site in the group dispatches through; `None` groups
    /// unresolved sites whose pointer was not traced to a field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<FieldRef>,
    /// Display only: the member name, when any site or assignment knew it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field_name: Option<String>,
    /// The function type the sites call through.
    pub signature: String,
    pub sites: Vec<CandidateSite>,
    pub candidates: Vec<Candidate>,
    /// Exactly one candidate, assigned at exactly one place. A hint for the
    /// reader; never applied as an edge.
    pub single_candidate: bool,
}

#[derive(Debug, Serialize)]
pub struct CandidateSite {
    pub site: CallSiteId,
    pub location: Option<SourceLocation>,
}

#[derive(Debug, Serialize)]
pub struct Candidate {
    pub function: FunctionId,
    /// Field groups: the stores and initializers that put this function's
    /// address into the field. The no-field group: every recorded use.
    pub assignments: Vec<UseFact>,
    /// The candidate's own type equals the group's `signature`. False is
    /// reported, not filtered: casting function pointers is routine in C.
    pub signature_matches: bool,
}

/// The per-query result list. Untagged: each query's own shape serializes
/// directly as the `results` array, with no wrapper variant name.
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum QueryResults {
    Defs(Vec<DefEntry>),
    At(Vec<AtEntry>),
    Callers(Vec<CallerEntry>),
    Callees(Vec<CallSiteFact>),
    Uses(Vec<UseFact>),
    /// `None` when no path over resolved edges exists. `Some` carries the
    /// path's steps, which may legitimately be empty: `reach(x, x)` finds
    /// `x` immediately and returns `Some(vec![])`, a found answer, not an
    /// absent one. Collapsing the two into one `Vec` would make a trivial
    /// found path read as unreachable.
    Reach(Option<Vec<PathStep>>),
    Slice(SliceResult),
    Closure(Vec<FunctionId>),
    Externals(Vec<SymbolBinding>),
    FfiExports(Vec<DefEntry>),
    IndirectTargets(Vec<IndirectTargetsResult>),
    ResolutionCandidates(Vec<CandidateGroup>),
}

impl QueryResults {
    pub fn is_empty(&self) -> bool {
        match self {
            QueryResults::Defs(items) => items.is_empty(),
            QueryResults::At(items) => items.is_empty(),
            QueryResults::Callers(items) => items.is_empty(),
            QueryResults::Callees(items) => items.is_empty(),
            QueryResults::Uses(items) => items.is_empty(),
            // `None` (no path) is the only "nothing to report" case;
            // `Some(_)` is a found answer even when its step list is
            // itself empty (a trivial `reach(x, x)`).
            QueryResults::Reach(path) => path.is_none(),
            QueryResults::Slice(slice) => slice.functions.is_empty(),
            QueryResults::Closure(items) => items.is_empty(),
            QueryResults::Externals(items) => items.is_empty(),
            QueryResults::FfiExports(items) => items.is_empty(),
            QueryResults::IndirectTargets(items) => items.is_empty(),
            QueryResults::ResolutionCandidates(items) => items.is_empty(),
        }
    }
}

/// Per-status module counts, plus the per-module detail they summarize.
/// Counted here, never in `scope`: a parse failure or a missing module must
/// not narrow the program `scope` claims to describe.
#[derive(Clone, Debug, Default, Serialize)]
pub struct Analysis {
    /// Read and hash-verified, but not extracted. [`open`] promotes every
    /// verified module to `analyzed` or `failed` before it returns, so this
    /// is 0 for a session opened from a catalog; it is non-zero only for a
    /// [`Session`] a caller assembled itself from [`ModuleReport`]s that
    /// extraction never saw. Counted rather than dropped so `analysis` stays
    /// total over [`ModuleAnalysis`]: a status with no count would let a
    /// module disappear from the summary entirely.
    pub verified: usize,
    pub analyzed: usize,
    pub changed: usize,
    pub missing: usize,
    pub failed: usize,
    pub unsupported: usize,
    pub not_built: usize,
    /// `ir_stage` and `debug_info` per module. A single aggregate would
    /// misrepresent a mixed catalog, which the compilation-database import
    /// makes an ordinary case.
    pub modules: Vec<ModuleReport>,
    /// How the facts cache served this load. Absent when the cache is off.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache: Option<CacheReport>,
}

/// What the answer could not see. Present on every answer, not only walks:
/// a `callees` or `defs` answer is read alongside the same uncertainty a
/// `reach` answer would report for the same program.
#[derive(Clone, Debug, Default, Serialize)]
pub struct Uncertainty {
    pub indirect_call_sites: usize,
    pub sites_with_llvm_target_bound: usize,
    pub functions_without_location: usize,
    pub locations_from_modified_sources: usize,
    /// Every ambiguous binding in the selected scope, on every query
    /// including `reach`. One meaning, program-wide: it is not the length of
    /// `frontier`, which for `reach` reports the narrower set that one walk
    /// actually reached.
    pub ambiguous_bindings: usize,
    /// For `reach`, the ambiguous bindings the walk actually reached, one
    /// entry per symbol. For every other query, every ambiguous binding in
    /// the selected scope.
    pub frontier: Vec<SymbolBinding>,
    /// Steps of a returned `reach` path, or edges of a `slice`, that are
    /// `bounded_indirect`, and so hold only if the call takes the member the
    /// path chose. Zero for a path of direct calls and resolved bindings,
    /// and for every query that returns no path: a non-zero count says
    /// *this* answer is conditional without the reader having to walk the
    /// step kinds.
    pub conditional_path_steps: usize,
    /// Steps of the returned path, or edges of a `slice`, that are agent
    /// edges. Non-zero means the answer is not proof.
    pub agent_path_steps: usize,
    /// `closure` with the overlay: functions reached only through at least
    /// one agent edge (closure with overlay minus closure without).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub agent_reached: Vec<FunctionId>,
    /// Present only when the query included the overlay.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub overlay: Option<OverlayCoverage>,
    /// `ffi-exports` only: external definitions whose symbol is fully
    /// unmangled but whose language neither debug info nor the producer
    /// could establish. They might be exports and were not searched.
    /// Non-zero when a module holding several languages has unmangled
    /// definitions without debug info: built without `-g`, or code the
    /// compiler generates, such as the C `main` rustc emits for a binary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub functions_of_unknown_language: Option<usize>,
}

/// How one name in the query reached the symbols it named.
///
/// Reported per name because the tiers are not equally certain: a `fuzzy`
/// match can gather unrelated functions that merely share an identifier, and
/// an answer that did not say so would read exactly like an exact hit.
#[derive(Clone, Debug, Serialize)]
pub struct Resolution {
    pub requested: String,
    /// Absent when the name matched nothing in the selected scope, which is
    /// an empty answer rather than an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matched: Option<NameMatch>,
    /// The mangled symbols the name resolved to, sorted and deduplicated.
    pub symbols: Vec<String>,
}

/// Where the answer's facts came from.
#[derive(Clone, Debug, Serialize)]
pub struct Provenance {
    /// Quoted from the catalog, not reconstructed.
    pub catalog_origin: CatalogOrigin,
    pub llvm_version: String,
    /// The version of `rllvm-query` -- the crate and binary that answered --
    /// not of the `rllvm` wrapper that captured the bitcode.
    pub rllvm_query_version: String,
}

/// The envelope every query answer is wrapped in.
#[derive(Debug, Serialize)]
pub struct QueryResult {
    pub schema_version: u32,
    pub query: Query,
    /// How each name the query took resolved. Empty for a query that takes a
    /// location or no name.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub resolution: Vec<Resolution>,
    pub results: QueryResults,
    /// The C++ reading of every mangled symbol this answer prints, keyed by
    /// the symbol.
    ///
    /// A table rather than a field beside each `symbol`: the reading is a
    /// function of the name alone, so one entry serves however many times the
    /// symbol occurs, and `FunctionId` keeps the plain identity it is used as
    /// a map key for. Empty for a C program, and for any answer whose symbols
    /// are all unmangled.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub symbols: BTreeMap<String, String>,
    /// Cloned from `ProgramFacts::scope`, never recomputed.
    pub scope: CatalogScope,
    pub analysis: Analysis,
    pub uncertainty: Uncertainty,
    pub provenance: Provenance,
}

/// Load a catalog into a [`Session`] ready to answer queries: read and
/// verify every module it names, extract facts from each, and resolve
/// cross-module symbol bindings.
///
/// Assembly order matters, and enforces two rules. First, only extraction
/// may promote a module's report from `Verified` (set by
/// [`load::load_catalog`]) to `Analyzed`; a module that fails to extract, or
/// that cannot be read at all by the time its bytes are wanted, is marked
/// `Failed` with the diagnostic instead, and the run continues -- the other
/// modules still answer. Second, assembly reads and holds one module's bytes
/// at a time by design, so no bitcode buffer stays resident once queries
/// start answering.
pub fn open(catalog: &Path) -> Result<Session, Error> {
    open_with_cache(catalog, None)
}

/// [`open`], reading each module's neutral facts from `cache` when given
/// (a hit never re-reads that module's bytes) or extracting and storing them
/// on a miss. Every module is bound to this catalog's ids and source status
/// the same way regardless of which path produced its facts.
pub fn open_with_cache(catalog: &Path, cache: Option<&FactsCache>) -> Result<Session, Error> {
    session_from_loaded(load::load_catalog(catalog)?, cache)
}

/// [`open`] for a catalog already in memory, resolving its relative module
/// paths against `catalog_dir`. The MCP `inventory` tool builds a catalog
/// from an artifact and queries it without ever writing it to disk.
pub fn open_catalog(catalog: ModuleCatalog, catalog_dir: &Path) -> Result<Session, Error> {
    open_catalog_with_cache(catalog, catalog_dir, None)
}

/// [`open_catalog`], reading and filling `cache` when given.
pub fn open_catalog_with_cache(
    catalog: ModuleCatalog,
    catalog_dir: &Path,
    cache: Option<&FactsCache>,
) -> Result<Session, Error> {
    session_from_loaded(load::load_catalog_value(catalog, catalog_dir)?, cache)
}

/// Extraction and binding, shared by every entry point above.
///
/// A module whose facts are already cached under its `content_sha256` is
/// served from there without reading its bytes at all. Everything else is
/// read one module at a time, as before: its neutral facts are extracted,
/// stored in `cache` when one was given, and then bound to this catalog --
/// exactly as a cache hit's facts are, so the two paths answer identically.
fn session_from_loaded(loaded: load::Loaded, cache: Option<&FactsCache>) -> Result<Session, Error> {
    // Every module the loader intends to read, regardless of whether
    // extraction later succeeds: `bind` only consults a module's
    // configuration when it also sees a `FunctionFact` from that module, so
    // an entry for a module that fails extraction is simply unused.
    let configurations: HashMap<String, Option<String>> = loaded
        .pending
        .iter()
        .map(|module| (module.id.clone(), module.record.configuration_id.clone()))
        .collect();

    let mut functions: Vec<FunctionFact> = Vec::new();
    let mut call_sites: Vec<CallSiteFact> = Vec::new();
    let mut uses: Vec<UseFact> = Vec::new();
    let mut reports = loaded.reports.clone();

    let mut report = cache.map(|cache| CacheReport {
        disk_bytes: cache.disk_bytes(),
        warn_bytes: cache.warn_bytes(),
        ..Default::default()
    });
    let mut archives = rllvm_core::catalog::ArchiveCache::default();
    let mut unreadable = Vec::new();

    for pending in &loaded.pending {
        // A module without a recorded hash cannot be keyed: extract it and
        // leave the cache alone.
        let cache_key = cache.zip(pending.record.content_sha256.as_deref());
        let neutral = match cache_key.and_then(|(cache, key)| cache.read(key)) {
            Some(facts) => {
                if let Some(report) = &mut report {
                    report.hits += 1;
                }
                Ok(facts)
            }
            None => {
                let module = match load::read_module(pending, &mut archives) {
                    Ok(module) => module,
                    Err(error) => {
                        unreadable.push((pending.id.clone(), error));
                        continue;
                    }
                };
                let extracted = extract::extract_neutral(&module);
                if let (Some((cache, key)), Some(report)) = (cache_key, &mut report) {
                    report.misses += 1;
                    if let Ok(facts) = &extracted {
                        match cache.write(key, facts) {
                            Ok(size) => {
                                report.written += 1;
                                report.disk_bytes += size;
                            }
                            Err(error) => {
                                tracing::debug!(module = %pending.id, %error, "facts not cached")
                            }
                        }
                    }
                }
                extracted
            }
        };
        match neutral {
            Ok(mut facts) => {
                facts.bind_to_catalog(&pending.id, &loaded.source_status);
                if let Some(report) = reports.iter_mut().find(|report| report.id == pending.id) {
                    report.status = ModuleAnalysis::Analyzed;
                    report.producers = facts.producers.clone();
                    if !facts.diagnostics.is_empty() {
                        let joined = facts.diagnostics.join("; ");
                        report.diagnostic = Some(match report.diagnostic.take() {
                            Some(existing) => format!("{existing}; {joined}"),
                            None => joined,
                        });
                    }
                }
                functions.extend(facts.functions);
                call_sites.extend(facts.call_sites);
                uses.extend(facts.uses);
            }
            Err(error) => {
                tracing::warn!(module = %pending.id, %error, "module failed to extract");
                record_failure(&mut reports, &pending.id, error.to_string());
            }
        }
    }
    // Buffers are not needed once every module is read; restores the
    // pre-cache peak-memory behaviour.
    drop(archives);
    if let Some(report) = &mut report {
        report.over_threshold = report.disk_bytes > report.warn_bytes;
    }

    // Nor may a module that verified at load time and then vanished or
    // became unreadable: it is recorded in `analysis` like any other
    // failure, and every other module still answers.
    for (id, error) in unreadable {
        tracing::warn!(module = %id, %error, "module could not be read");
        record_failure(&mut reports, &id, error.to_string());
    }

    let bindings = bind::bind(&functions, &configurations);
    let facts = ProgramFacts {
        functions,
        call_sites,
        uses,
        scope: loaded.scope.clone(),
        origin: loaded.origin.clone(),
        modules: reports,
    };
    // This drops `Loaded` itself before the session below starts serving.
    drop(loaded);

    Ok(Session::new(facts, bindings).with_cache_report(report))
}

/// Answer one query over an already-loaded session.
///
/// Fails only on a query that cannot be interpreted -- an `indirect-targets`
/// location that does not parse as `file:line`. A query that is understood
/// but finds nothing is an answer, not an error, and comes back as an empty
/// `results` list.
pub fn run(session: &Session, query: &Query) -> Result<QueryResult, Error> {
    run_with_overlay(session, None, query)
}

/// [`run`], with an overlay of agent-proposed edges that `reach`, `closure`
/// and `slice` walk when the query sets `include_overlay`. A query that asks
/// for the overlay when `overlay` is `None` is an argument error, never a
/// silent direct-only answer.
pub fn run_with_overlay(
    session: &Session,
    overlay: Option<&Overlay>,
    query: &Query,
) -> Result<QueryResult, Error> {
    let view = match query.overlay_request()? {
        Some(min_confidence) => {
            let overlay = overlay.ok_or_else(|| {
                Error::InvalidArguments(
                    "`include_overlay` needs an overlay: none is loaded for this catalog"
                        .to_string(),
                )
            })?;
            Some(OverlayView::new(session, overlay, min_confidence))
        }
        None => None,
    };
    let view = view.as_ref();

    let mut reach_frontier: Option<Vec<SymbolBinding>> = None;
    let mut conditional_path_steps = 0;
    let mut agent_path_steps = 0;
    let mut agent_reached = Vec::new();
    let mut unknown_language = None;

    let results = match query {
        Query::Defs { name } => QueryResults::Defs(defs(session, name)),
        Query::At { file, line } => QueryResults::At(at_entries(session, Path::new(file), *line)),
        Query::Callers { name } => QueryResults::Callers(callers(session, name)),
        Query::Callees { name } => QueryResults::Callees(session.callees(name)),
        Query::Uses { name } => QueryResults::Uses(uses_of(session, name)),
        Query::Reach { from, to, .. } => {
            let reach = session.reach_with(from, to, view);
            reach_frontier = Some(reach.frontier);
            (conditional_path_steps, agent_path_steps) = hedged_steps(reach.path.iter().flatten());
            QueryResults::Reach(reach.path)
        }
        Query::Slice { from, to, .. } => {
            let slice = session.slice_with(from, to, view);
            (conditional_path_steps, agent_path_steps) =
                hedged_steps(slice.edges.iter().map(|edge| &edge.step));
            QueryResults::Slice(slice)
        }
        Query::Closure {
            name, direction, ..
        } => {
            let reached = session.closure_with(name, *direction, view);
            if view.is_some() {
                let direct: HashSet<FunctionId> =
                    session.closure(name, *direction).into_iter().collect();
                agent_reached = reached
                    .iter()
                    .filter(|id| !direct.contains(id))
                    .cloned()
                    .collect();
            }
            QueryResults::Closure(reached)
        }
        Query::Externals => QueryResults::Externals(externals(session)),
        Query::FfiExports => {
            let (exports, unknown) = ffi_exports(session);
            unknown_language = Some(unknown);
            QueryResults::FfiExports(exports)
        }
        Query::IndirectTargets { at, heuristics } => {
            QueryResults::IndirectTargets(indirect_targets(session, at, *heuristics)?)
        }
        Query::ResolutionCandidates => {
            QueryResults::ResolutionCandidates(resolution_candidates(session))
        }
    };

    // Reach reports exactly the ambiguous bindings its own walk hit, which
    // may legitimately be empty even while other bindings elsewhere in
    // scope are ambiguous. Every other query has no walk of its own, so it
    // reports the full program-wide set instead. The `ambiguous_bindings`
    // count is program-wide either way -- see `uncertainty_of`.
    let frontier = reach_frontier.unwrap_or_else(|| ambiguous_bindings(session));

    let symbols = symbols_in(session, &results, &frontier);

    Ok(QueryResult {
        schema_version: 2,
        query: query.clone(),
        resolution: query
            .names()
            .into_iter()
            .map(|name| resolution_of(session, name))
            .collect(),
        results,
        symbols,
        scope: session.scope().clone(),
        analysis: analysis_of(session.modules(), session.cache_report()),
        uncertainty: Uncertainty {
            agent_path_steps,
            agent_reached,
            overlay: view.map(|view| view.coverage().clone()),
            functions_of_unknown_language: unknown_language,
            ..uncertainty_of(session, frontier, conditional_path_steps)
        },
        provenance: Provenance {
            catalog_origin: session.origin().clone(),
            llvm_version: llvm_version(),
            rllvm_query_version: env!("CARGO_PKG_VERSION").to_string(),
        },
    })
}

/// How many of `steps` are `bounded_indirect`, holding only if the call takes
/// the member chosen, and how many are agent edges, which are never proof.
fn hedged_steps<'s>(steps: impl Iterator<Item = &'s PathStep>) -> (usize, usize) {
    steps.fold((0, 0), |(conditional, agent), step| match step {
        PathStep::BoundedIndirect { .. } => (conditional + 1, agent),
        PathStep::Agent { .. } => (conditional, agent + 1),
        PathStep::Call(_) | PathStep::Binding(_) | PathStep::Alias { .. } => (conditional, agent),
    })
}

fn resolution_of(session: &Session, name: &str) -> Resolution {
    let resolved = session.resolve(name);
    let mut symbols: Vec<String> = resolved
        .iter()
        .flat_map(|resolution| &resolution.ids)
        .map(|id| id.symbol.clone())
        .collect();
    symbols.sort_unstable();
    symbols.dedup();
    Resolution {
        requested: name.to_string(),
        matched: resolved.map(|resolution| resolution.matched),
        symbols,
    }
}

/// The C++ reading of every mangled symbol the answer prints.
///
/// Collected from the results and from the frontier, which is where `reach`
/// reports the bindings it refused to guess through: those name symbols too,
/// and a reader meets them as often as the results.
fn symbols_in(
    session: &Session,
    results: &QueryResults,
    frontier: &[SymbolBinding],
) -> BTreeMap<String, String> {
    let mut names = BTreeSet::new();
    results.collect_symbols(&mut names);
    for binding in frontier {
        collect_binding(binding, &mut names);
    }
    names
        .into_iter()
        .filter_map(|name| {
            session
                .demangled(&name)
                .map(|reading| (name, reading.to_string()))
        })
        .collect()
}

impl QueryResults {
    /// Every symbol this answer prints. Exhaustive over the variants with no
    /// wildcard arm, so a new query's results cannot quietly go untabulated
    /// and leave its mangled names unreadable.
    fn collect_symbols(&self, into: &mut BTreeSet<String>) {
        match self {
            QueryResults::Defs(entries) | QueryResults::FfiExports(entries) => {
                for entry in entries {
                    collect_function(&entry.function, into);
                }
            }
            QueryResults::At(entries) => {
                for entry in entries {
                    collect_function(&entry.function, into);
                    collect_call_sites(&entry.call_sites, into);
                }
            }
            QueryResults::Callers(entries) => {
                for entry in entries {
                    collect_function(&entry.function, into);
                    collect_call_sites(&entry.call_sites, into);
                }
            }
            QueryResults::Callees(sites) => collect_call_sites(sites, into),
            QueryResults::Uses(uses) => {
                for use_fact in uses {
                    collect_function(&use_fact.used, into);
                    if let Some(id) = &use_fact.in_function {
                        collect_function(id, into);
                    }
                }
            }
            QueryResults::Reach(path) => {
                for step in path.iter().flatten() {
                    collect_step(step, into);
                }
            }
            QueryResults::Slice(slice) => {
                for id in &slice.functions {
                    collect_function(id, into);
                }
                for edge in &slice.edges {
                    collect_function(&edge.from, into);
                    collect_function(&edge.to, into);
                    collect_step(&edge.step, into);
                }
            }
            QueryResults::Closure(ids) => {
                for id in ids {
                    collect_function(id, into);
                }
            }
            QueryResults::Externals(bindings) => {
                for binding in bindings {
                    collect_binding(binding, into);
                }
            }
            QueryResults::ResolutionCandidates(groups) => {
                for group in groups {
                    for site in &group.sites {
                        collect_function(&site.site.function, into);
                    }
                    for candidate in &group.candidates {
                        collect_function(&candidate.function, into);
                        for assignment in &candidate.assignments {
                            if let Some(id) = &assignment.in_function {
                                collect_function(id, into);
                            }
                        }
                    }
                }
            }
            QueryResults::IndirectTargets(entries) => {
                for entry in entries {
                    collect_function(&entry.site.function, into);
                    let lists = [
                        &entry.llvm_target_bound,
                        &entry.address_taken_inventory,
                        &entry.signature_compatible,
                    ];
                    for id in lists.into_iter().flatten().flatten() {
                        collect_function(id, into);
                    }
                }
            }
        }
    }
}

fn collect_function(id: &FunctionId, into: &mut BTreeSet<String>) {
    into.insert(id.symbol.clone());
}

fn collect_call_sites(sites: &[CallSiteFact], into: &mut BTreeSet<String>) {
    for site in sites {
        collect_function(&site.id.function, into);
        match &site.target {
            CallTarget::Direct { callee } => collect_function(callee, into),
            CallTarget::Indirect {
                llvm_target_bound, ..
            } => {
                for id in llvm_target_bound.iter().flatten() {
                    collect_function(id, into);
                }
            }
            // An intrinsic is named `llvm.*` and is never mangled; inline
            // assembly names nothing at all.
            CallTarget::Intrinsic { .. } | CallTarget::InlineAsm => {}
        }
    }
}

fn collect_step(step: &PathStep, into: &mut BTreeSet<String>) {
    match step {
        PathStep::Call(site) => collect_function(&site.function, into),
        PathStep::BoundedIndirect {
            site,
            chosen,
            bound,
        } => {
            collect_function(&site.function, into);
            collect_function(chosen, into);
            for id in bound {
                collect_function(id, into);
            }
        }
        PathStep::Binding(binding) => collect_binding(binding, into),
        PathStep::Alias { alias, target } => {
            collect_function(alias, into);
            collect_function(target, into);
        }
        PathStep::Agent { site, chosen, .. } => {
            collect_function(&site.function, into);
            collect_function(chosen, into);
        }
    }
}

fn collect_binding(binding: &SymbolBinding, into: &mut BTreeSet<String>) {
    into.insert(binding.symbol.clone());
    for candidate in &binding.candidates {
        collect_function(&candidate.function, into);
    }
}

/// Marks one module's report `Failed` with the reason. Only extraction may
/// write `Analyzed`; every other outcome for a module the loader verified
/// lands here.
fn record_failure(reports: &mut [ModuleReport], id: &str, reason: String) {
    if let Some(report) = reports.iter_mut().find(|report| report.id == id) {
        report.status = ModuleAnalysis::Failed;
        report.diagnostic = Some(reason);
    }
}

/// Every ambiguous binding in the selected scope, one entry per symbol.
fn ambiguous_bindings(session: &Session) -> Vec<SymbolBinding> {
    session
        .bindings()
        .iter()
        .filter(|binding| binding.status == BindingStatus::Ambiguous)
        .cloned()
        .collect()
}

fn defs(session: &Session, name: &str) -> Vec<DefEntry> {
    session
        .definitions(name)
        .into_iter()
        .map(|function| def_entry(session, function))
        .collect()
}

fn configuration_of(session: &Session, module_id: &str) -> Option<String> {
    session
        .modules()
        .iter()
        .find(|module| module.id == module_id)
        .and_then(|module| module.configuration_id.clone())
}

/// One `DefEntry` for a function, shared by every query that reports
/// definitions: the configuration and location come from the same two
/// lookups either way.
fn def_entry(session: &Session, function: &FunctionFact) -> DefEntry {
    DefEntry {
        function: function.id.clone(),
        configuration_id: configuration_of(session, &function.id.module_id),
        location: function.location.clone(),
    }
}

fn at_entries(session: &Session, file: &Path, line: u32) -> Vec<AtEntry> {
    let call_sites = session.call_sites_at(file, line);
    session
        .functions_at(file, line)
        .iter()
        .map(|id| {
            let call_sites = call_sites
                .iter()
                .filter(|site| &site.id.function == id)
                .map(|site| (*site).clone())
                .collect();
            AtEntry {
                function: id.clone(),
                call_sites,
            }
        })
        .collect()
}

fn callers(session: &Session, name: &str) -> Vec<CallerEntry> {
    let mut grouped: BTreeMap<FunctionId, Vec<CallSiteFact>> = BTreeMap::new();
    for site in session.callers(name) {
        grouped
            .entry(site.id.function.clone())
            .or_default()
            .push(site);
    }
    grouped
        .into_iter()
        .map(|(function, call_sites)| CallerEntry {
            function,
            call_sites,
        })
        .collect()
}

fn uses_of(session: &Session, name: &str) -> Vec<UseFact> {
    session
        .uses()
        .iter()
        .filter(|use_fact| use_fact.used.symbol == name)
        .cloned()
        .collect()
}

fn externals(session: &Session) -> Vec<SymbolBinding> {
    session
        .bindings()
        .iter()
        .filter(|binding| binding.status == BindingStatus::Unbound)
        .cloned()
        .collect()
}

/// Neither a Rust symbol, in either scheme, nor an Itanium one. `#[no_mangle]`
/// and `#[export_name]` produce these; C++ never does.
fn is_fully_unmangled(symbol: &str) -> bool {
    !symbol.starts_with("_Z") && rustc_demangle::try_demangle(symbol).is_err()
}

/// The exported Rust definitions, sorted by symbol, and how many fully
/// unmangled external definitions could not be attributed to a language.
fn ffi_exports(session: &Session) -> (Vec<DefEntry>, usize) {
    let mut exports = Vec::new();
    let mut unknown = 0;
    for function in session.functions().iter().filter(|function| {
        function.is_definition
            && function.linkage == Linkage::External
            && is_fully_unmangled(&function.id.symbol)
    }) {
        match function.language.map(|language| language.name) {
            Some(Language::Rust) => exports.push(def_entry(session, function)),
            Some(Language::Other) => {}
            None => unknown += 1,
        }
    }
    exports.sort_by(|left, right| {
        (&left.function.symbol, &left.function.module_id)
            .cmp(&(&right.function.symbol, &right.function.module_id))
    });
    (exports, unknown)
}

fn indirect_targets(
    session: &Session,
    at: &str,
    heuristics: bool,
) -> Result<Vec<IndirectTargetsResult>, Error> {
    let (file, line) = parse_location(at)?;

    // Computed once whether or not any site below needs it, but never
    // exposed unless `heuristics` was requested: the whole point is that it
    // must not leak into a default answer.
    let inventory = heuristics.then(|| address_taken_inventory(session));
    let assumptions = vec![
        "Soundness holds only within the captured scope.".to_string(),
        "dlopen and a callback registered by code outside the captured scope both escape this bound.".to_string(),
    ];

    Ok(session
        .call_sites_at(&file, line)
        .into_iter()
        .filter_map(|site| {
            let CallTarget::Indirect {
                signature,
                llvm_target_bound,
                ..
            } = &site.target
            else {
                return None;
            };
            let signature_compatible = inventory.as_ref().map(|functions| {
                functions
                    .iter()
                    .filter(|id| {
                        session
                            .function(id)
                            .is_some_and(|function| &function.signature == signature)
                    })
                    .cloned()
                    .collect()
            });
            Some(IndirectTargetsResult {
                site: site.id.clone(),
                location: site.location.clone(),
                signature: signature.clone(),
                unresolved: llvm_target_bound.is_none(),
                llvm_target_bound: llvm_target_bound.clone(),
                address_taken_inventory: inventory.clone(),
                signature_compatible,
                assumptions: assumptions.clone(),
            })
        })
        .collect())
}

/// Every function with at least one recorded use, deduplicated. Not filtered
/// by signature: that filtering is `signature_compatible`'s job, reported
/// only alongside this unfiltered set.
fn address_taken_inventory(session: &Session) -> Vec<FunctionId> {
    let mut seen: BTreeSet<FunctionId> = BTreeSet::new();
    let mut inventory = Vec::new();
    for use_fact in session.uses() {
        if seen.insert(use_fact.used.clone()) {
            inventory.push(use_fact.used.clone());
        }
    }
    inventory
}

/// Joins each unresolved indirect site to the functions stored into the field
/// it dispatches through. A site with no traced field falls back to the
/// address-taken functions of its signature.
fn resolution_candidates(session: &Session) -> Vec<CandidateGroup> {
    let mut grouped: BTreeMap<(Option<FieldRef>, String), Vec<&CallSiteFact>> = BTreeMap::new();
    for site in session.call_sites() {
        if let CallTarget::Indirect {
            signature,
            llvm_target_bound: None,
            via_field,
        } = &site.target
        {
            let field = via_field.as_ref().map(|evidence| evidence.field.clone());
            grouped
                .entry((field, signature.clone()))
                .or_default()
                .push(site);
        }
    }

    // `None` sorts first in an `Option` key; the no-field groups go last.
    let (without_field, with_field): (Vec<_>, Vec<_>) = grouped
        .into_iter()
        .partition(|((field, _), _)| field.is_none());
    with_field
        .into_iter()
        .chain(without_field)
        .map(|((field, signature), mut sites)| {
            sites.sort_by(|left, right| left.id.cmp(&right.id));
            let mut candidates = match &field {
                Some(field) => field_candidates(session, field, &signature),
                None => signature_candidates(session, &signature),
            };
            candidates.sort_by(|left, right| left.function.cmp(&right.function));
            let field_name = sites
                .iter()
                .find_map(|site| match &site.target {
                    CallTarget::Indirect { via_field, .. } => via_field
                        .as_ref()
                        .and_then(|evidence| evidence.name.clone()),
                    _ => None,
                })
                .or_else(|| {
                    candidates
                        .iter()
                        .flat_map(|candidate| &candidate.assignments)
                        .find_map(|assignment| {
                            assignment
                                .field
                                .as_ref()
                                .and_then(|evidence| evidence.name.clone())
                        })
                });
            let single_candidate = candidates.len() == 1 && candidates[0].assignments.len() == 1;
            CandidateGroup {
                field,
                field_name,
                signature,
                sites: sites
                    .into_iter()
                    .map(|site| CandidateSite {
                        site: site.id.clone(),
                        location: site.location.clone(),
                    })
                    .collect(),
                candidates,
                single_candidate,
            }
        })
        .collect()
}

/// Every function with a use that puts its address into `field`, under any
/// `kind`.
fn field_candidates(session: &Session, field: &FieldRef, signature: &str) -> Vec<Candidate> {
    let mut by_function: BTreeMap<FunctionId, Vec<UseFact>> = BTreeMap::new();
    for use_fact in session.uses() {
        if use_fact
            .field
            .as_ref()
            .is_some_and(|evidence| &evidence.field == field)
        {
            by_function
                .entry(use_fact.used.clone())
                .or_default()
                .push(use_fact.clone());
        }
    }
    by_function
        .into_iter()
        .map(|(function, assignments)| Candidate {
            signature_matches: session
                .function(&function)
                .is_some_and(|fact| fact.signature == signature),
            function,
            assignments,
        })
        .collect()
}

/// The address-taken functions whose type is `signature`, with every use.
fn signature_candidates(session: &Session, signature: &str) -> Vec<Candidate> {
    address_taken_inventory(session)
        .into_iter()
        .filter(|id| {
            session
                .function(id)
                .is_some_and(|fact| fact.signature == signature)
        })
        .map(|function| Candidate {
            assignments: session
                .uses()
                .iter()
                .filter(|use_fact| use_fact.used == function)
                .cloned()
                .collect(),
            function,
            signature_matches: true,
        })
        .collect()
}

impl Query {
    /// The symbol names this query takes, in the order it takes them.
    ///
    /// Exhaustive over `Query` with no wildcard arm: a new query that takes a
    /// name has to be listed here, or its answer would never say how that
    /// name resolved -- and a fuzzy match would look like an exact one.
    fn names(&self) -> Vec<&str> {
        match self {
            Query::Defs { name }
            | Query::Callers { name }
            | Query::Callees { name }
            | Query::Uses { name }
            | Query::Closure { name, .. } => vec![name],
            Query::Reach { from, to, .. } | Query::Slice { from, to, .. } => vec![from, to],
            // These take a location or nothing at all.
            Query::At { .. }
            | Query::Externals
            | Query::FfiExports
            | Query::IndirectTargets { .. }
            | Query::ResolutionCandidates => Vec::new(),
        }
    }

    /// Check the arguments that can be rejected without reading any bitcode.
    ///
    /// `open` loads and extracts every selected module, which for a real
    /// program is the expensive part. A mistyped location is the one input
    /// that can be known bad beforehand, so callers check it first and a typo
    /// costs a diagnostic rather than a full analysis.
    pub fn validate(&self) -> Result<(), Error> {
        self.overlay_request()?;
        match self {
            Query::IndirectTargets { at, .. } => parse_location(at).map(|_| ()),
            _ => Ok(()),
        }
    }

    /// Whether this query walks the overlay, and so needs one opened.
    pub fn walks_overlay(&self) -> bool {
        matches!(self.overlay_fields(), Some((true, _)))
    }

    /// Whether this kind of query can walk the overlay, asked to or not:
    /// what decides which tools take the overlay arguments.
    pub fn takes_overlay(&self) -> bool {
        self.overlay_fields().is_some()
    }

    /// `include_overlay` and `min_confidence`, for the queries that carry
    /// them: the one list of queries that can walk the overlay.
    fn overlay_fields(&self) -> Option<(bool, Option<Confidence>)> {
        match self {
            Query::Reach {
                include_overlay,
                min_confidence,
                ..
            }
            | Query::Slice {
                include_overlay,
                min_confidence,
                ..
            }
            | Query::Closure {
                include_overlay,
                min_confidence,
                ..
            } => Some((*include_overlay, *min_confidence)),
            _ => None,
        }
    }

    /// The weakest overlay edge a walk takes, when it asked for the overlay
    /// at all. A minimum without the overlay is an error rather than a
    /// filter that silently does nothing.
    fn overlay_request(&self) -> Result<Option<Confidence>, Error> {
        match self.overlay_fields() {
            Some((true, minimum)) => Ok(Some(minimum.unwrap_or(Confidence::Low))),
            Some((false, Some(_))) => Err(Error::InvalidArguments(
                "`min_confidence` filters overlay edges; it needs `include_overlay`".to_string(),
            )),
            Some((false, None)) | None => Ok(None),
        }
    }
}

/// For `skip_serializing_if`: a flag left off is not written, so a query
/// that did not ask for an option serializes as it did before the option.
fn is_false(flag: &bool) -> bool {
    !flag
}

/// Splits a `file:line` location on its last colon, so a path containing a
/// colon earlier does not shift the parse.
///
/// A location that does not parse is an error, not an empty answer.
/// `indirect-targets` exists to surface what cannot be resolved, so a typo
/// that answered `results: []` would be byte-identical to a valid line with
/// no indirect calls -- and over MCP an agent client would have no way to
/// tell the two apart.
fn parse_location(at: &str) -> Result<(PathBuf, u32), Error> {
    let invalid = || {
        Error::InvalidArguments(format!(
            "invalid location `{at}`: expected `file:line`, e.g. `parser.c:8`"
        ))
    };
    let (file, line) = at.rsplit_once(':').ok_or_else(invalid)?;
    let line: u32 = line.parse().map_err(|_| invalid())?;
    Ok((PathBuf::from(file), line))
}

fn analysis_of(modules: &[ModuleReport], cache: Option<&CacheReport>) -> Analysis {
    let mut analysis = Analysis {
        modules: modules.to_vec(),
        cache: cache.cloned(),
        ..Default::default()
    };
    for module in modules {
        match module.status {
            ModuleAnalysis::Verified => analysis.verified += 1,
            ModuleAnalysis::Analyzed => analysis.analyzed += 1,
            ModuleAnalysis::Changed => analysis.changed += 1,
            ModuleAnalysis::Missing => analysis.missing += 1,
            ModuleAnalysis::Failed => analysis.failed += 1,
            ModuleAnalysis::Unsupported => analysis.unsupported += 1,
            ModuleAnalysis::NotBuilt => analysis.not_built += 1,
        }
    }
    analysis
}

fn uncertainty_of(
    session: &Session,
    frontier: Vec<SymbolBinding>,
    conditional_path_steps: usize,
) -> Uncertainty {
    let call_sites = session.call_sites();
    let indirect_call_sites = call_sites
        .iter()
        .filter(|site| matches!(&site.target, CallTarget::Indirect { .. }))
        .count();
    let sites_with_llvm_target_bound = call_sites
        .iter()
        .filter(|site| {
            matches!(
                &site.target,
                CallTarget::Indirect {
                    llvm_target_bound: Some(_),
                    ..
                }
            )
        })
        .count();
    let functions_without_location = session
        .functions()
        .iter()
        .filter(|function| function.location.is_none())
        .count();

    let is_modified = |location: &Option<SourceLocation>| {
        location
            .as_ref()
            .is_some_and(|location| location.source_status == SourceStatus::Modified)
    };
    let locations_from_modified_sources = session
        .functions()
        .iter()
        .filter(|function| is_modified(&function.location))
        .count()
        + call_sites
            .iter()
            .filter(|site| is_modified(&site.location))
            .count()
        + session
            .uses()
            .iter()
            .filter(|use_fact| is_modified(&use_fact.location))
            .count();

    Uncertainty {
        indirect_call_sites,
        sites_with_llvm_target_bound,
        functions_without_location,
        locations_from_modified_sources,
        // Program-wide on every query, `reach` included: `frontier.len()`
        // would mean "reached by this walk" here and "program-wide"
        // everywhere else, and a `reach` frontier counts one symbol once
        // however many declarations reached it. Counted in place rather than
        // through `ambiguous_bindings`, which clones each binding -- on a
        // non-`reach` query that helper already ran once to build `frontier`.
        ambiguous_bindings: session
            .bindings()
            .iter()
            .filter(|binding| binding.status == BindingStatus::Ambiguous)
            .count(),
        frontier,
        conditional_path_steps,
        // Overwritten by `run_with_overlay` for a walk; every other query
        // leaves them zero, empty and absent.
        agent_path_steps: 0,
        agent_reached: Vec::new(),
        overlay: None,
        // Overwritten by `run` for `Query::FfiExports`; every other query
        // leaves it absent.
        functions_of_unknown_language: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rllvm_core::catalog::{
        ModuleCatalog, ModuleRecord, ModuleStatus, hash_bytes, write_catalog,
    };

    use crate::{facts::Language, load::load_catalog, testing::*};

    #[test]
    fn a_module_is_analyzed_only_after_it_parses() {
        // The loader marks Verified; only extraction may promote to Analyzed.
        let scratch = tempfile::tempdir().unwrap();
        let loaded = load_catalog(&write_catalog_with_one_module(&scratch)).unwrap();
        assert_eq!(loaded.reports[0].status, ModuleAnalysis::Verified);
    }

    /// `load_catalog` verifies a module's bytes against its recorded hash,
    /// but a concurrent rewrite between that check and `session_from_loaded`
    /// reading the bytes for real is exactly what `load::read_module`'s own
    /// re-hash exists to catch. On a cache-enabled load this has to happen
    /// *before* the cache is ever consulted for that module: the module must
    /// be marked `Failed`, not analyzed under the wrong bitcode, and nothing
    /// about it may reach the cache.
    ///
    /// The replacement is real, parseable bitcode -- different from the
    /// original, but not garbage -- so this pins the re-hash catching it
    /// specifically. Garbage bytes would also end up `Failed` with nothing
    /// cached, just because extraction itself fails, which would pass this
    /// test even if the re-hash check were silently removed.
    #[test]
    fn a_module_rewritten_after_verification_is_failed_and_never_cached() {
        let scratch = tempfile::tempdir().unwrap();
        let module_path = rllvm_testkit::compile_bitcode(
            &scratch,
            "orig.c",
            "int add(int a,int b){return a+b;}\n",
        );
        let original_bytes = std::fs::read(&module_path).unwrap();

        let mut record = ModuleRecord::new("m");
        record.path = Some(PathBuf::from(module_path.file_name().unwrap()));
        record.content_sha256 = Some(hash_bytes(&original_bytes));
        record.status = ModuleStatus::Available;
        let catalog = ModuleCatalog::new(
            CatalogOrigin {
                kind: "test".into(),
                input: PathBuf::from("test"),
                sha256: None,
            },
            "test",
            vec![record],
        );
        let catalog_path = scratch.path().join("catalog.json");
        write_catalog(&catalog_path, &catalog).unwrap();

        let loaded = load_catalog(&catalog_path).unwrap();

        // Overwritten with different, still-valid bitcode after
        // `load_catalog` already verified the original bytes: the mismatch
        // is only visible to the re-check inside `session_from_loaded`.
        let replacement = rllvm_testkit::compile_bitcode(
            &scratch,
            "replacement.c",
            "int sub(int a,int b){return a-b;}\n",
        );
        std::fs::copy(&replacement, &module_path).unwrap();

        let cache = FactsCache::new(&scratch.path().join("cache"), u64::MAX);
        let session = session_from_loaded(loaded, Some(&cache)).unwrap();

        assert_eq!(
            session.modules()[0].status,
            ModuleAnalysis::Failed,
            "a module that changed after verification must not be silently analyzed"
        );
        let report = session.cache_report().unwrap();
        assert_eq!(
            report.written, 0,
            "a module that was never read must never be cached"
        );
        assert_eq!(cache.disk_bytes(), 0);
    }

    #[test]
    fn scope_counts_survive_a_failed_module() {
        let facts = facts_with_one_failed_module();
        let result = run(&Session::new(facts, vec![]), &Query::Externals).unwrap();
        assert_eq!(result.scope.selected_entries, 2);
        assert_eq!(result.analysis.analyzed, 1);
        assert_eq!(result.analysis.failed, 1);
        // Per-module detail, not just a count: rule 2 requires `ir_stage`
        // and `debug_info` to survive per module rather than collapsing
        // into one aggregate flag.
        assert_eq!(result.analysis.modules[0].debug_info, Some(true));
    }

    #[test]
    fn an_empty_reach_names_the_indirect_sites_it_could_not_follow() {
        let session = session_with_indirect_gap();
        let result = run(
            &session,
            &Query::Reach {
                from: "a".into(),
                to: "c".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert!(result.results.is_empty());
        assert_eq!(result.uncertainty.indirect_call_sites, 1);
    }

    #[test]
    fn a_trivial_reach_is_a_found_path_not_an_absent_one() {
        // `session.reach("a", "a")` finds `a` immediately and returns
        // `Some(vec![])`: a found path with zero steps. Collapsing that
        // into the same empty `Vec` a missing path produces would make a
        // trivial found path read as unreachable.
        let session = session_from(&[("a", "b")]);

        let trivial = run(
            &session,
            &Query::Reach {
                from: "a".into(),
                to: "a".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert!(
            !trivial.results.is_empty(),
            "a==a must be a found path, not an absent one"
        );

        let missing = run(
            &session,
            &Query::Reach {
                from: "a".into(),
                to: "absent".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert!(missing.results.is_empty());
    }

    #[test]
    fn heuristics_are_absent_unless_requested() {
        let session = session_with_address_taken_function();
        let result = run(
            &session,
            &Query::IndirectTargets {
                at: "t.c:4".into(),
                heuristics: false,
            },
        )
        .unwrap();
        let json = serde_json::to_value(&result).unwrap();
        assert!(json.to_string().find("address_taken_inventory").is_none());
    }

    #[test]
    fn requested_heuristics_stay_in_their_own_field() {
        let session = session_with_address_taken_function();
        let result = run(
            &session,
            &Query::IndirectTargets {
                at: "t.c:4".into(),
                heuristics: true,
            },
        )
        .unwrap();
        let json = serde_json::to_value(&result).unwrap();
        let entry = &json["results"][0];
        assert!(
            entry["address_taken_inventory"]
                .as_array()
                .unwrap()
                .iter()
                .any(|f| f["symbol"] == "add"),
            "inventory must list address-taken functions when requested"
        );
        assert!(
            entry["llvm_target_bound"].is_null(),
            "a heuristic must never appear as an LLVM-provided bound"
        );
    }

    #[test]
    fn at_returns_nothing_for_a_line_with_no_instructions() {
        // Lines 2 and 10 are mapped, but 5 is not: a range-containment
        // implementation (`min..max`) would wrongly return the function for
        // line 5, since it falls inside `2..10`. Only a mapping
        // implementation answers empty here, which is `at`'s actual
        // contract: at least one instruction mapped to that exact line.
        let session = session_from_source_lines(&[("t.c", 2), ("t.c", 10)]);
        let result = run(
            &session,
            &Query::At {
                file: "t.c".into(),
                line: 5,
            },
        )
        .unwrap();
        assert!(result.results.is_empty());
    }

    #[test]
    fn callees_of_b_keeps_the_unresolved_indirect_site() {
        // A future refactor could add a `CallTarget::Indirect { .. } => {}`
        // arm to `callees_by_function` by symmetry with the match just
        // below it for `callers_by_function` (`index.rs`), which would
        // drop every unresolved indirect site from every `callees` answer
        // without failing any existing test. This pins that it must not.
        let session = session_with_indirect_gap();
        let result = run(&session, &Query::Callees { name: "b".into() }).unwrap();
        let QueryResults::Callees(sites) = &result.results else {
            panic!("Query::Callees must produce QueryResults::Callees");
        };
        let indirect = sites
            .iter()
            .find(|site| matches!(&site.target, CallTarget::Indirect { .. }))
            .expect("the unresolved indirect call site must not be dropped");
        assert_eq!(indirect.id.instruction_index, 1);
        assert_eq!(indirect.location, None);
    }

    #[test]
    fn ambiguous_bindings_counts_the_scope_not_the_walk() {
        // Two ambiguous bindings in scope; the walk from `caller` reaches
        // one. `ambiguous_bindings` has to mean the same thing on both
        // answers, or a reader comparing two queries over one catalog sees
        // two different numbers for one program.
        let session = session_with_ambiguous_bindings();

        let reach = run(
            &session,
            &Query::Reach {
                from: "caller".into(),
                to: "target".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert_eq!(
            reach.uncertainty.frontier.len(),
            1,
            "the frontier is what this walk reached"
        );
        assert_eq!(
            reach.uncertainty.ambiguous_bindings, 2,
            "the count is program-wide, not the frontier's length"
        );

        let externals = run(&session, &Query::Externals).unwrap();
        assert_eq!(externals.uncertainty.ambiguous_bindings, 2);
    }

    #[test]
    fn a_path_through_a_bounded_indirect_call_is_flagged_conditional() {
        // The path holds only if the call takes the member it chose. Without
        // a count in `uncertainty`, a reader has to walk the step kinds to
        // learn that, and an agent client reading the envelope will not.
        let conditional = run(
            &session_with_bounded_indirect(),
            &Query::Reach {
                from: "a".into(),
                to: "target".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert!(!conditional.results.is_empty(), "a path must be found");
        assert_eq!(conditional.uncertainty.conditional_path_steps, 1);

        let direct = run(
            &session_from(&[("a", "b"), ("b", "c")]),
            &Query::Reach {
                from: "a".into(),
                to: "c".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert!(!direct.results.is_empty());
        assert_eq!(
            direct.uncertainty.conditional_path_steps, 0,
            "a path of direct calls is not conditional"
        );
    }

    #[test]
    fn an_unparseable_location_is_an_error_not_an_empty_answer() {
        // `indirect-targets parser.c` (no `:8`) must not answer `results:
        // []`, which is byte-identical to a valid line with no indirect
        // calls -- for the one query whose purpose is surfacing what cannot
        // be resolved.
        let session = session_with_address_taken_function();
        let error = run(
            &session,
            &Query::IndirectTargets {
                at: "parser.c".into(),
                heuristics: false,
            },
        )
        .expect_err("a location without a line must not answer");
        assert!(error.to_string().contains("parser.c"), "{error}");

        assert!(
            run(
                &session,
                &Query::IndirectTargets {
                    at: "parser.c:notaline".into(),
                    heuristics: false,
                },
            )
            .is_err(),
            "a non-numeric line must not answer either"
        );
    }

    #[test]
    fn a_module_extraction_never_saw_is_counted_verified() {
        // `open` promotes every verified module, so this count is 0 there;
        // it is reachable for a `Session` a caller assembles itself, and
        // dropping the field would leave `ModuleAnalysis::Verified`
        // uncounted in `analysis` rather than reported as zero.
        let result = run(
            &Session::new(facts_with_one_verified_module(), vec![]),
            &Query::Externals,
        )
        .unwrap();
        assert_eq!(result.analysis.verified, 1);
        assert_eq!(result.analysis.analyzed, 0);
        assert_eq!(
            result.scope.selected_entries, 1,
            "scope still quotes the catalog"
        );
    }

    #[test]
    fn an_answer_carries_the_reading_of_every_mangled_symbol_it_prints() {
        let result = run(
            &session_with_cxx_symbols(),
            &Query::Defs {
                name: "_Z5twiceIiET_S0_".into(),
            },
        )
        .unwrap();
        assert_eq!(
            result.symbols.get("_Z5twiceIiET_S0_").map(String::as_str),
            Some("int twice<int>(int)")
        );
        assert!(
            !result.symbols.contains_key("main"),
            "a C name has no reading, so it gets no entry: {:?}",
            result.symbols
        );
    }

    /// The table indexes what the answer actually prints, not the program:
    /// a `defs` answer for one instantiation must not hand back every
    /// mangled name in scope.
    #[test]
    fn the_symbol_table_covers_the_answer_not_the_whole_scope() {
        let result = run(
            &session_with_cxx_symbols(),
            &Query::Defs {
                name: "int twice<int>(int)".into(),
            },
        )
        .unwrap();
        assert_eq!(
            result.symbols.keys().collect::<Vec<_>>(),
            vec!["_Z5twiceIiET_S0_"],
            "only the one function this answer names"
        );
    }

    #[test]
    fn a_c_only_answer_carries_no_symbol_table_at_all() {
        let result = run(
            &session_from(&[("a", "b")]),
            &Query::Defs { name: "a".into() },
        )
        .unwrap();
        assert!(result.symbols.is_empty());
        let json = serde_json::to_value(&result).unwrap();
        assert!(
            json.get("symbols").is_none(),
            "an empty table is omitted rather than printed as {{}}"
        );
    }

    /// The point of the `resolution` block: `defs twice` gathering three
    /// unrelated functions must not read like an exact hit on one.
    #[test]
    fn an_answer_says_which_tier_resolved_its_name() {
        let session = session_with_cxx_symbols();

        let exact = run(
            &session,
            &Query::Defs {
                name: "_Z5twiceIiET_S0_".into(),
            },
        )
        .unwrap();
        assert_eq!(exact.resolution[0].requested, "_Z5twiceIiET_S0_");
        assert_eq!(exact.resolution[0].matched, Some(NameMatch::Mangled));
        assert_eq!(exact.resolution[0].symbols.len(), 1);

        let fuzzy = run(
            &session,
            &Query::Defs {
                name: "twice".into(),
            },
        )
        .unwrap();
        assert_eq!(fuzzy.resolution[0].matched, Some(NameMatch::Fuzzy));
        assert_eq!(
            fuzzy.resolution[0].symbols,
            ["_Z5twiceIdET_S0_", "_Z5twiceIiET_S0_", "_ZN2ns5twiceEv"],
            "the block names every symbol the fuzzy tier gathered"
        );
        assert!(!fuzzy.results.is_empty(), "all three still answer");
    }

    #[test]
    fn a_name_that_matches_nothing_reports_no_tier() {
        let result = run(
            &session_with_cxx_symbols(),
            &Query::Defs {
                name: "absent".into(),
            },
        )
        .unwrap();
        assert!(result.results.is_empty());
        assert_eq!(result.resolution[0].matched, None);
        assert!(result.resolution[0].symbols.is_empty());
    }

    /// `reach` takes two names, so it reports two resolutions, in order.
    /// A query that takes a location or nothing reports none.
    #[test]
    fn resolution_is_reported_once_per_name_the_query_takes() {
        let session = session_from(&[("a", "b")]);

        let reach = run(
            &session,
            &Query::Reach {
                from: "a".into(),
                to: "b".into(),
                include_overlay: false,
                min_confidence: None,
            },
        )
        .unwrap();
        assert_eq!(
            reach
                .resolution
                .iter()
                .map(|entry| entry.requested.as_str())
                .collect::<Vec<_>>(),
            ["a", "b"]
        );

        let externals = run(&session, &Query::Externals).unwrap();
        assert!(externals.resolution.is_empty());
        let json = serde_json::to_value(&externals).unwrap();
        assert!(json.get("resolution").is_none(), "omitted when empty");
    }

    #[test]
    fn ffi_exports_lists_unmangled_external_rust_definitions() {
        let rust = Some(Language::Rust);
        let mut declared = attributed("imported", Linkage::External, rust);
        declared.is_definition = false;
        let session = Session::new(
            facts(
                vec![
                    attributed("lib_add", Linkage::External, rust),
                    attributed("_RNvCs9jdNsLYHTiK_3lib6helper", Linkage::External, rust),
                    attributed(
                        "_ZN3lib6legacy17h0123456789abcdefE",
                        Linkage::External,
                        rust,
                    ),
                    attributed("internal_helper", Linkage::Internal, rust),
                    declared,
                    attributed("c_fn", Linkage::External, Some(Language::Other)),
                    attributed("_Z5twicei", Linkage::External, None),
                    attributed("mystery", Linkage::External, None),
                ],
                vec![],
            ),
            vec![],
        );
        let result = run(&session, &Query::FfiExports).unwrap();
        let QueryResults::FfiExports(entries) = &result.results else {
            panic!("wrong result kind");
        };
        let symbols: Vec<&str> = entries.iter().map(|e| e.function.symbol.as_str()).collect();
        assert_eq!(symbols, ["lib_add"]);
        assert_eq!(
            result.uncertainty.functions_of_unknown_language,
            Some(1),
            "`mystery` is counted; the C++ `_Z5twicei` never could be an export"
        );
    }

    #[test]
    fn only_ffi_exports_reports_the_unknown_language_count() {
        let session = Session::new(
            facts(vec![attributed("mystery", Linkage::External, None)], vec![]),
            vec![],
        );
        let externals = run(&session, &Query::Externals).unwrap();
        assert_eq!(externals.uncertainty.functions_of_unknown_language, None);
        let json = serde_json::to_value(&externals).unwrap();
        assert!(
            json["uncertainty"]
                .get("functions_of_unknown_language")
                .is_none()
        );
    }

    /// A synthetic one-module catalog whose module bytes are not real
    /// bitcode: `load_catalog` only verifies bytes against the recorded
    /// hash and never parses, so arbitrary content with a matching hash is
    /// enough to exercise the Verified status this test pins.
    fn write_catalog_with_one_module(scratch: &tempfile::TempDir) -> PathBuf {
        let module_path = scratch.path().join("m.bc");
        let bytes = b"not real bitcode, only its hash matters here";
        std::fs::write(&module_path, bytes).unwrap();

        let mut record = ModuleRecord::new("m");
        record.path = Some(PathBuf::from("m.bc"));
        record.content_sha256 = Some(hash_bytes(bytes));
        record.status = ModuleStatus::Available;

        let catalog = ModuleCatalog::new(
            CatalogOrigin {
                kind: "test".into(),
                input: PathBuf::from("test"),
                sha256: None,
            },
            "test",
            vec![record],
        );
        let catalog_path = scratch.path().join("catalog.json");
        write_catalog(&catalog_path, &catalog).unwrap();
        catalog_path
    }

    fn ops(offset: u64) -> FieldRef {
        FieldRef {
            record: "ops".into(),
            offset,
        }
    }

    /// `h` stored into `field` at `t.c:line`, from `in_function`.
    fn store_into(
        h: &FunctionFact,
        in_function: &FunctionFact,
        line: u32,
        field: FieldRef,
    ) -> UseFact {
        UseFact {
            used: h.id.clone(),
            in_function: Some(in_function.id.clone()),
            in_global: None,
            location: Some(source_location("t.c", line)),
            kind: UseKind::StoredToMemory,
            field: Some(FieldEvidence {
                field,
                basis: FieldBasis::StructGep,
                name: None,
            }),
        }
    }

    fn candidates_of(session: &Session) -> Vec<CandidateGroup> {
        match run(session, &Query::ResolutionCandidates).unwrap().results {
            QueryResults::ResolutionCandidates(groups) => groups,
            other => panic!("expected resolution candidates, got {other:?}"),
        }
    }

    #[test]
    fn candidates_group_sites_by_the_field_they_dispatch_through() {
        let caller = function("m", "caller", true, Linkage::Internal);
        let sites = vec![
            indirect_call_through(&caller, 1, Some(ops(8))),
            indirect_call_through(&caller, 2, Some(ops(8))),
            indirect_call_through(&caller, 3, Some(ops(16))),
        ];
        let session = Session::new(facts(vec![caller], sites), Vec::new());
        let groups = candidates_of(&session);
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0].field, Some(ops(8)));
        assert_eq!(groups[0].sites.len(), 2);
        assert_eq!(groups[1].field, Some(ops(16)));
        assert_eq!(groups[1].sites.len(), 1);
    }

    #[test]
    fn a_bounded_site_is_not_a_resolution_candidate() {
        let session = session_with_bounded_indirect();
        assert!(candidates_of(&session).is_empty());
        let result = run(&session, &Query::ResolutionCandidates).unwrap();
        assert!(result.results.is_empty());
    }

    #[test]
    fn a_function_stored_into_the_field_is_its_candidate() {
        let caller = function("m", "caller", true, Linkage::Internal);
        let h1 = function("m", "h1", true, Linkage::Internal);
        let h2 = function("m", "h2", true, Linkage::Internal);
        let mut base = facts(
            vec![caller.clone(), h1.clone(), h2.clone()],
            vec![indirect_call_through(&caller, 1, Some(ops(8)))],
        );
        base.uses = vec![
            store_into(&h1, &caller, 20, ops(8)),
            store_into(&h2, &caller, 21, ops(16)),
        ];
        let groups = candidates_of(&Session::new(base, Vec::new()));
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].candidates.len(), 1);
        let candidate = &groups[0].candidates[0];
        assert_eq!(candidate.function, h1.id);
        assert_eq!(candidate.assignments.len(), 1);
        assert_eq!(candidate.assignments[0].location.as_ref().unwrap().line, 20);
        assert!(candidate.signature_matches);
    }

    #[test]
    fn a_signature_mismatch_is_reported_not_filtered() {
        let caller = function("m", "caller", true, Linkage::Internal);
        let odd = FunctionFact {
            signature: "void (ptr)".into(),
            ..function("m", "odd", true, Linkage::Internal)
        };
        let mut base = facts(
            vec![caller.clone(), odd.clone()],
            vec![indirect_call_through(&caller, 1, Some(ops(8)))],
        );
        base.uses = vec![store_into(&odd, &caller, 20, ops(8))];
        let groups = candidates_of(&Session::new(base, Vec::new()));
        assert_eq!(groups[0].candidates.len(), 1);
        assert!(!groups[0].candidates[0].signature_matches);
    }

    #[test]
    fn one_candidate_assigned_once_is_hinted_never_applied() {
        let caller = function("m", "caller", true, Linkage::Internal);
        let h1 = function("m", "h1", true, Linkage::Internal);
        let mut base = facts(
            vec![caller.clone(), h1.clone()],
            vec![indirect_call_through(&caller, 1, Some(ops(8)))],
        );
        base.uses = vec![store_into(&h1, &caller, 20, ops(8))];
        let session = Session::new(base, Vec::new());
        assert!(candidates_of(&session)[0].single_candidate);
        assert!(session.reach("caller", "h1").path.is_none());
    }

    #[test]
    fn sites_without_a_field_group_by_signature_with_address_taken_candidates() {
        let session = session_with_address_taken_function();
        let groups = candidates_of(&session);
        assert_eq!(groups.len(), 1);
        assert_eq!(groups[0].field, None);
        assert_eq!(groups[0].signature, "i32 (i32, i32)");
        let symbols: Vec<_> = groups[0]
            .candidates
            .iter()
            .map(|candidate| candidate.function.symbol.as_str())
            .collect();
        assert_eq!(symbols, ["add"]);
        assert!(groups[0].candidates[0].signature_matches);
    }

    #[test]
    fn the_field_name_falls_back_to_an_assignment_when_the_site_has_none() {
        let caller = function("m", "caller", true, Linkage::Internal);
        let h1 = function("m", "h1", true, Linkage::Internal);
        let mut base = facts(
            vec![caller.clone(), h1.clone()],
            vec![indirect_call_through(&caller, 1, Some(ops(8)))],
        );
        let mut store = store_into(&h1, &caller, 20, ops(8));
        store.field.as_mut().unwrap().name = Some("on_event".into());
        base.uses = vec![store];
        let groups = candidates_of(&Session::new(base, Vec::new()));
        assert_eq!(groups[0].field_name.as_deref(), Some("on_event"));
    }

    /// Walks over the overlay: an agent edge is used only when the query
    /// asks, and every answer that used one says so.
    mod overlay_walks {
        use super::*;
        use crate::overlay::{Confidence, EdgeKey, Overlay, Record, TargetSpec, Verdict};

        fn session() -> Session {
            Session::new(facts_with_overlay_sites(), Vec::new())
        }

        fn add(to: &str, confidence: Confidence) -> Record {
            Record::Add {
                via_field: Some(ops(8)),
                site: None,
                to: TargetSpec::Symbol(to.into()),
                confidence,
                provenance: vec!["init: o->on_event = h3".into()],
                source: "agent".into(),
            }
        }

        fn overlay_of(session: &Session, records: Vec<Record>) -> Overlay {
            let mut overlay = Overlay::empty(session, None).unwrap();
            overlay.record(session, records).unwrap();
            overlay
        }

        fn reach(include_overlay: bool, min_confidence: Option<Confidence>) -> Query {
            Query::Reach {
                from: "dispatch".into(),
                to: "h3".into(),
                include_overlay,
                min_confidence,
            }
        }

        fn closure_in(name: &str, include_overlay: bool) -> Query {
            Query::Closure {
                name: name.into(),
                direction: Direction::In,
                include_overlay,
                min_confidence: None,
            }
        }

        fn path_of(result: &QueryResult) -> Option<&Vec<PathStep>> {
            match &result.results {
                QueryResults::Reach(path) => path.as_ref(),
                other => panic!("expected a reach answer, got {other:?}"),
            }
        }

        fn closure_of(result: &QueryResult) -> Vec<&str> {
            let QueryResults::Closure(ids) = &result.results else {
                panic!("expected a closure answer");
            };
            let mut symbols: Vec<&str> = ids.iter().map(|id| id.symbol.as_str()).collect();
            symbols.sort_unstable();
            symbols
        }

        #[test]
        fn the_overlay_is_ignored_unless_asked() {
            let session = session();
            let without = run(&session, &reach(false, None)).unwrap();
            assert!(path_of(&without).is_none());

            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);
            let unasked = run_with_overlay(&session, Some(&overlay), &reach(false, None)).unwrap();
            assert!(
                path_of(&unasked).is_none(),
                "a loaded overlay is not walked unless the query asks"
            );
            assert_eq!(unasked.uncertainty.agent_path_steps, 0);
            assert!(unasked.uncertainty.overlay.is_none());

            // A walk that did not ask serializes exactly as before.
            let json = serde_json::to_value(&unasked).unwrap();
            assert_eq!(
                json["query"],
                serde_json::json!({"kind": "reach", "from": "dispatch", "to": "h3"})
            );
            assert!(json["uncertainty"].get("overlay").is_none());
            assert!(json["uncertainty"].get("agent_reached").is_none());
        }

        #[test]
        fn an_agent_edge_completes_a_path_and_is_labeled() {
            let session = session();
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);
            let result = run_with_overlay(&session, Some(&overlay), &reach(true, None)).unwrap();
            let path = path_of(&result).expect("the agent edge completes the path");
            assert!(
                matches!(
                    path.last(),
                    Some(PathStep::Agent {
                        confidence: Confidence::High,
                        verdict: None,
                        chosen,
                        site,
                        provenance,
                        ..
                    }) if chosen.symbol == "h3"
                        && site.function.symbol == "dispatch"
                        && provenance == &["init: o->on_event = h3"]
                ),
                "{path:?}"
            );
            let json = serde_json::to_value(&result).unwrap();
            assert_eq!(
                json["results"].as_array().unwrap().last().unwrap()["provenance"],
                serde_json::json!(["init: o->on_event = h3"]),
                "the grounds reach a JSON reader too"
            );
            assert_eq!(result.uncertainty.agent_path_steps, 1);
            assert_eq!(result.uncertainty.conditional_path_steps, 0);
            let coverage = result.uncertainty.overlay.as_ref().expect("coverage");
            assert_eq!(coverage.covered_sites, 1);
            assert_eq!(coverage.unresolved_sites, 2);
        }

        #[test]
        fn a_refuted_edge_is_never_walked() {
            let session = session();
            let verify = Record::Verify {
                edge: EdgeKey::Field {
                    via_field: ops(8),
                    to: FunctionId {
                        module_id: "mod_a".into(),
                        symbol: "h3".into(),
                    },
                },
                tool: "reread".into(),
                verdict: Verdict::Refuted,
                at: None,
            };
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High), verify]);
            let result = run_with_overlay(&session, Some(&overlay), &reach(true, None)).unwrap();
            assert!(path_of(&result).is_none());
            assert_eq!(result.uncertainty.agent_path_steps, 0);
            assert_eq!(
                result.uncertainty.overlay.as_ref().unwrap().covered_sites,
                0,
                "a refuted edge covers nothing"
            );
        }

        #[test]
        fn min_confidence_drops_weaker_edges() {
            let session = session();
            let overlay = overlay_of(&session, vec![add("h3", Confidence::Low)]);
            let strict = run_with_overlay(
                &session,
                Some(&overlay),
                &reach(true, Some(Confidence::Medium)),
            )
            .unwrap();
            assert!(path_of(&strict).is_none());

            let lenient = run_with_overlay(&session, Some(&overlay), &reach(true, None)).unwrap();
            assert!(
                path_of(&lenient).is_some(),
                "no minimum means low, which includes every non-refuted edge"
            );
        }

        #[test]
        fn closure_marks_what_only_agent_edges_reach() {
            let session = session();
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);

            let direct =
                run_with_overlay(&session, Some(&overlay), &closure_in("h3", false)).unwrap();
            assert_eq!(closure_of(&direct), ["init"]);
            assert!(direct.uncertainty.agent_reached.is_empty());

            let with = run_with_overlay(&session, Some(&overlay), &closure_in("h3", true)).unwrap();
            assert_eq!(closure_of(&with), ["dispatch", "init"]);
            let agent_only: Vec<&str> = with
                .uncertainty
                .agent_reached
                .iter()
                .map(|id| id.symbol.as_str())
                .collect();
            assert_eq!(agent_only, ["dispatch"]);
        }

        #[test]
        fn including_the_overlay_without_one_is_an_argument_error() {
            let session = session();
            for query in [reach(true, None), closure_in("h3", true)] {
                match run_with_overlay(&session, None, &query) {
                    Err(Error::InvalidArguments(message)) => {
                        assert!(message.contains("include_overlay"), "{message}")
                    }
                    other => panic!("expected an argument error, got {other:?}"),
                }
                assert!(run(&session, &query).is_err(), "`run` has no overlay");
            }
        }

        #[test]
        fn a_minimum_confidence_without_the_overlay_is_an_argument_error() {
            let query = reach(false, Some(Confidence::High));
            assert!(query.validate().is_err());
            assert!(run(&session(), &query).is_err());
        }

        #[test]
        fn a_direct_path_wins_over_an_agent_edge_at_equal_depth() {
            let mut base = facts_with_overlay_sites();
            let dispatch = function("mod_a", "dispatch", true, Linkage::External);
            let h3 = function("mod_a", "h3", true, Linkage::Internal);
            base.call_sites.push(direct_call(&dispatch, &h3, 10));
            let session = Session::new(base, Vec::new());
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);
            let result = run_with_overlay(&session, Some(&overlay), &reach(true, None)).unwrap();
            assert!(
                matches!(
                    path_of(&result).map(Vec::as_slice),
                    Some([PathStep::Call(_)])
                ),
                "{:?}",
                path_of(&result)
            );
            assert_eq!(result.uncertainty.agent_path_steps, 0);
        }

        fn slice(include_overlay: bool) -> Query {
            Query::Slice {
                from: "dispatch".into(),
                to: "h3".into(),
                include_overlay,
                min_confidence: None,
            }
        }

        fn slice_of(result: &QueryResult) -> &SliceResult {
            match &result.results {
                QueryResults::Slice(slice) => slice,
                other => panic!("expected a slice answer, got {other:?}"),
            }
        }

        #[test]
        fn an_agent_edge_widens_the_slice_only_when_asked() {
            let session = session();
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);

            let unasked = run_with_overlay(&session, Some(&overlay), &slice(false)).unwrap();
            assert!(slice_of(&unasked).functions.is_empty());
            assert!(unasked.results.is_empty());
            assert_eq!(unasked.uncertainty.agent_path_steps, 0);
            assert!(unasked.uncertainty.overlay.is_none());

            let asked = run_with_overlay(&session, Some(&overlay), &slice(true)).unwrap();
            let widened = slice_of(&asked);
            let members: Vec<&str> = widened
                .functions
                .iter()
                .map(|id| id.symbol.as_str())
                .collect();
            assert_eq!(members, ["dispatch", "h3"]);
            assert!(
                matches!(
                    widened.edges.as_slice(),
                    [SliceEdge { from, to, step: PathStep::Agent { .. } }]
                        if from.symbol == "dispatch" && to.symbol == "h3"
                ),
                "{:?}",
                widened.edges
            );
            assert_eq!(asked.uncertainty.agent_path_steps, 1);
            assert!(asked.uncertainty.overlay.is_some());
            assert!(asked.symbols.is_empty(), "a C answer has no readings");

            assert!(
                run(&session, &slice(true)).is_err(),
                "asking for an overlay that is not there is an error"
            );
        }

        #[test]
        fn a_field_edge_applies_to_every_site_through_the_field() {
            let mut base = facts_with_overlay_sites();
            let second = function("mod_a", "dispatch_again", true, Linkage::External);
            base.call_sites
                .push(indirect_call_through(&second, 9, Some(ops(8))));
            base.functions.push(second);
            let session = Session::new(base, Vec::new());
            let overlay = overlay_of(&session, vec![add("h3", Confidence::High)]);

            let result =
                run_with_overlay(&session, Some(&overlay), &closure_in("h3", true)).unwrap();
            assert_eq!(closure_of(&result), ["dispatch", "dispatch_again", "init"]);
            assert_eq!(result.uncertainty.agent_reached.len(), 2);
            assert_eq!(
                result.uncertainty.overlay.as_ref().unwrap().covered_sites,
                2
            );
        }
    }
}