rllvm-query 0.7.2

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
//! 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},
    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};

pub mod mcp;

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

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

/// One of the ten 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 },
    /// The set that can reach the target (`In`) or that it can reach
    /// (`Out`).
    Closure { name: String, direction: Direction },
    /// 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 },
}

/// 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>,
}

/// 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>>),
    Closure(Vec<FunctionId>),
    Externals(Vec<SymbolBinding>),
    FfiExports(Vec<DefEntry>),
    IndirectTargets(Vec<IndirectTargetsResult>),
}

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::Closure(items) => items.is_empty(),
            QueryResults::Externals(items) => items.is_empty(),
            QueryResults::FfiExports(items) => items.is_empty(),
            QueryResults::IndirectTargets(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 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,
    /// `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> {
    let mut reach_frontier: Option<Vec<SymbolBinding>> = None;
    let mut conditional_path_steps = 0;
    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(from, to);
            reach_frontier = Some(reach.frontier);
            conditional_path_steps = reach
                .path
                .iter()
                .flatten()
                .filter(|step| matches!(step, PathStep::BoundedIndirect { .. }))
                .count();
            QueryResults::Reach(reach.path)
        }
        Query::Closure { name, direction } => {
            QueryResults::Closure(session.closure(name, *direction))
        }
        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)?)
        }
    };

    // 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 {
            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(),
        },
    })
}

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::Closure(ids) => {
                for id in ids {
                    collect_function(id, into);
                }
            }
            QueryResults::Externals(bindings) => {
                for binding in bindings {
                    collect_binding(binding, 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);
        }
    }
}

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
}

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 } => vec![from, to],
            // These take a location or nothing at all.
            Query::At { .. }
            | Query::Externals
            | Query::FfiExports
            | Query::IndirectTargets { .. } => 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> {
        match self {
            Query::IndirectTargets { at, .. } => parse_location(at).map(|_| ()),
            _ => Ok(()),
        }
    }
}

/// 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` 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(),
            },
        )
        .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(),
            },
        )
        .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(),
            },
        )
        .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(),
            },
        )
        .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(),
            },
        )
        .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(),
            },
        )
        .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(),
            },
        )
        .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
    }
}