nyx-scanner 0.6.0

A multi-language static analysis tool for detecting security vulnerabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
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
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
use super::*;
use smallvec::smallvec;

/// Test helper: build a [`SmallVec`] of one cap-only [`SinkSite`] for a
/// parameter, matching the pre-`SinkSite` shape `(idx, Cap)`.  Source
/// coordinates stay default (`line=0, col=0`) since tests do not
/// exercise the primary-location attribution path at this layer.
fn cap_sites(cap: Cap) -> SmallVec<[SinkSite; 1]> {
    smallvec![SinkSite::cap_only(cap)]
}

fn make(name: &str, src: u16, san: u16, sink: u16) -> FuncSummary {
    FuncSummary {
        name: name.into(),
        file_path: "test.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: src,
        sanitizer_caps: san,
        sink_caps: sink,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    }
}

#[test]
fn merge_unions_conservatively() {
    let a = make("foo", 0x01, 0x00, 0x00);
    let b = FuncSummary {
        sink_caps: 0x04,
        propagating_params: vec![0],
        tainted_sink_params: vec![0],
        callees: vec!["bar".into()],
        ..make("foo", 0x00, 0x02, 0x00)
    };

    let merged = merge_summaries(vec![a, b], None);
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "test.rs".into(),
        name: "foo".into(),
        arity: Some(0),
        ..Default::default()
    };
    let foo = merged.get(&key).unwrap();

    assert_eq!(foo.source_caps, 0x01);
    assert_eq!(foo.sanitizer_caps, 0x02);
    assert_eq!(foo.sink_caps, 0x04);
    assert!(foo.propagates_any());
    assert_eq!(foo.propagating_params, vec![0]);
    assert_eq!(foo.tainted_sink_params, vec![0]);
    assert_eq!(foo.callees.len(), 1);
    assert_eq!(foo.callees[0].name, "bar");
}

#[test]
fn same_lang_different_namespace_no_merge() {
    let a = FuncSummary {
        name: "helper".into(),
        file_path: "file_a.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: Cap::all().bits(),
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };
    let b = FuncSummary {
        name: "helper".into(),
        file_path: "file_b.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 0,
        sanitizer_caps: 0,
        sink_caps: Cap::SHELL_ESCAPE.bits(),
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };

    let global = merge_summaries(vec![a, b], None);

    // They should be stored under different FuncKeys
    let key_a = FuncKey {
        lang: Lang::Rust,
        namespace: "file_a.rs".into(),
        name: "helper".into(),
        arity: Some(0),
        ..Default::default()
    };
    let key_b = FuncKey {
        lang: Lang::Rust,
        namespace: "file_b.rs".into(),
        name: "helper".into(),
        arity: Some(0),
        ..Default::default()
    };
    assert!(global.get(&key_a).is_some());
    assert!(global.get(&key_b).is_some());
    // source_caps NOT merged
    assert_eq!(global.get(&key_a).unwrap().source_caps, Cap::all().bits());
    assert_eq!(global.get(&key_b).unwrap().source_caps, 0);
}

#[test]
fn same_lang_same_namespace_merges() {
    let a = FuncSummary {
        name: "helper".into(),
        file_path: "lib.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 0x01,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };
    let b = FuncSummary {
        name: "helper".into(),
        file_path: "lib.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 0,
        sanitizer_caps: 0x02,
        sink_caps: 0,
        propagating_params: vec![0],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };

    let global = merge_summaries(vec![a, b], None);
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "lib.rs".into(),
        name: "helper".into(),
        arity: Some(0),
        ..Default::default()
    };
    let merged = global.get(&key).unwrap();
    assert_eq!(merged.source_caps, 0x01);
    assert_eq!(merged.sanitizer_caps, 0x02);
    assert!(merged.propagates_any());
    assert_eq!(merged.propagating_params, vec![0]);
}

#[test]
fn cross_lang_name_collision_stays_separate() {
    let py = FuncSummary {
        name: "process_data".into(),
        file_path: "handler.py".into(),
        lang: "python".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: Cap::all().bits(),
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };
    let c = FuncSummary {
        name: "process_data".into(),
        file_path: "handler.c".into(),
        lang: "c".into(),
        param_count: 1,
        param_names: vec!["s".into()],
        source_caps: 0,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![0],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };

    let global = merge_summaries(vec![py, c], None);

    let py_key = FuncKey {
        lang: Lang::Python,
        namespace: "handler.py".into(),
        name: "process_data".into(),
        arity: Some(0),
        ..Default::default()
    };
    let c_key = FuncKey {
        lang: Lang::C,
        namespace: "handler.c".into(),
        name: "process_data".into(),
        arity: Some(1),
        ..Default::default()
    };

    assert!(global.get(&py_key).is_some());
    assert!(global.get(&c_key).is_some());
    // Python's source_caps NOT merged into C
    assert_eq!(global.get(&c_key).unwrap().source_caps, 0);
    assert_eq!(global.get(&py_key).unwrap().source_caps, Cap::all().bits());
}

#[test]
fn lookup_same_lang_returns_all_matches() {
    let a = FuncSummary {
        name: "helper".into(),
        file_path: "a.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 1,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };
    let b = FuncSummary {
        name: "helper".into(),
        file_path: "b.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 2,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };

    let global = merge_summaries(vec![a, b], None);
    let matches = global.lookup_same_lang(Lang::Rust, "helper");
    assert_eq!(matches.len(), 2);

    // No cross-language matches
    let py_matches = global.lookup_same_lang(Lang::Python, "helper");
    assert!(py_matches.is_empty());
}

#[test]
fn u16_caps_round_trip_serde() {
    let summary = FuncSummary {
        name: "dangerous".into(),
        file_path: "test.rs".into(),
        lang: "rust".into(),
        param_count: 1,
        param_names: vec!["input".into()],
        source_caps: (Cap::SQL_QUERY | Cap::CODE_EXEC).bits(),
        sanitizer_caps: Cap::CRYPTO.bits(),
        sink_caps: (Cap::SSRF | Cap::DESERIALIZE).bits(),
        propagating_params: vec![0],
        propagates_taint: false,
        tainted_sink_params: vec![0],
        callees: vec!["query".into()],
        ..Default::default()
    };

    let json = serde_json::to_string(&summary).unwrap();
    let back: FuncSummary = serde_json::from_str(&json).unwrap();

    assert_eq!(back.source_caps, (Cap::SQL_QUERY | Cap::CODE_EXEC).bits());
    assert_eq!(back.sanitizer_caps, Cap::CRYPTO.bits());
    assert_eq!(back.sink_caps, (Cap::SSRF | Cap::DESERIALIZE).bits());
    assert!(back.propagates_any());
    assert_eq!(back.propagating_params, vec![0]);
    // propagates_taint should NOT appear in serialized output
    assert!(!json.contains("propagates_taint"));
}

#[test]
fn backward_compat_u8_json_deserializes() {
    // Old u8-range values still deserialize correctly into u16 fields
    let json = r#"{
        "name": "old_func",
        "file_path": "legacy.py",
        "lang": "python",
        "param_count": 0,
        "param_names": [],
        "source_caps": 127,
        "sanitizer_caps": 2,
        "sink_caps": 4,
        "propagates_taint": false,
        "tainted_sink_params": [],
        "callees": []
    }"#;

    let summary: FuncSummary = serde_json::from_str(json).unwrap();
    assert_eq!(summary.source_caps, 127);
    assert_eq!(summary.sanitizer_caps, 2);
    assert_eq!(summary.sink_caps, 4);
}

#[test]
fn merge_propagating_params_union() {
    let a = FuncSummary {
        propagating_params: vec![0],
        ..make("foo", 0, 0, 0)
    };
    let b = FuncSummary {
        propagating_params: vec![1],
        ..make("foo", 0, 0, 0)
    };

    let merged = merge_summaries(vec![a, b], None);
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "test.rs".into(),
        name: "foo".into(),
        arity: Some(0),
        ..Default::default()
    };
    let foo = merged.get(&key).unwrap();
    assert_eq!(foo.propagating_params, vec![0, 1]);
    assert!(foo.propagates_any());
}

#[test]
fn backward_compat_legacy_propagates_taint_json() {
    // Old JSON with propagates_taint: true but no propagating_params
    let json = r#"{
        "name": "old_func",
        "file_path": "legacy.py",
        "lang": "python",
        "param_count": 1,
        "param_names": ["x"],
        "source_caps": 0,
        "sanitizer_caps": 0,
        "sink_caps": 0,
        "propagates_taint": true,
        "tainted_sink_params": [],
        "callees": []
    }"#;

    let summary: FuncSummary = serde_json::from_str(json).unwrap();
    assert!(summary.propagates_taint);
    assert!(summary.propagating_params.is_empty());
    assert!(summary.propagates_any());
}

#[test]
fn propagating_params_round_trip_serde() {
    let summary = FuncSummary {
        propagating_params: vec![0, 2],
        ..make("foo", 0, 0, 0)
    };

    let json = serde_json::to_string(&summary).unwrap();
    let back: FuncSummary = serde_json::from_str(&json).unwrap();

    assert_eq!(back.propagating_params, vec![0, 2]);
    assert!(back.propagates_any());
    // propagates_taint must NOT appear in serialized output
    assert!(!json.contains("propagates_taint"));
}

#[test]
fn snapshot_caps_detects_change() {
    let a = FuncSummary {
        source_caps: 0x01,
        propagating_params: vec![0],
        ..make("foo", 0, 0, 0)
    };
    let b = make("bar", 0, 0, 0x04);

    let mut gs = merge_summaries(vec![a, b], None);

    let snap1 = gs.snapshot_caps();

    // Mutate one summary by inserting a changed version.
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "test.rs".into(),
        name: "bar".into(),
        arity: Some(0),
        ..Default::default()
    };
    let updated = FuncSummary {
        sink_caps: 0x08,
        ..make("bar", 0, 0, 0)
    };
    gs.insert(key, updated);

    let snap2 = gs.snapshot_caps();

    assert_ne!(snap1, snap2, "snapshot should detect changed caps");

    // Without further changes, snapshot should be stable.
    let snap3 = gs.snapshot_caps();
    assert_eq!(snap2, snap3, "snapshot should be stable without changes");
}

// ── SSA summary tests ───────────────────────────────────────────────────

use super::ssa_summary::{SsaFuncSummary, TaintTransform};

#[test]
fn ssa_summary_serde_round_trip_identity() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
}

#[test]
fn ssa_summary_serde_round_trip_strip_bits() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(
            0,
            TaintTransform::StripBits(Cap::HTML_ESCAPE | Cap::URL_ENCODE),
        )],
        param_to_sink: vec![(1, cap_sites(Cap::SQL_QUERY))],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
}

#[test]
fn ssa_summary_serde_round_trip_add_bits() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(2, TaintTransform::AddBits(Cap::CODE_EXEC))],
        param_to_sink: vec![],
        source_caps: Cap::ENV_VAR | Cap::FILE_IO,
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
}

#[test]
fn ssa_summary_serde_round_trip_all_variants() {
    let summary = SsaFuncSummary {
        param_to_return: vec![
            (0, TaintTransform::Identity),
            (1, TaintTransform::StripBits(Cap::SHELL_ESCAPE)),
            (2, TaintTransform::AddBits(Cap::SSRF)),
        ],
        param_to_sink: vec![
            (0, cap_sites(Cap::SQL_QUERY)),
            (1, cap_sites(Cap::CODE_EXEC | Cap::CRYPTO)),
        ],
        source_caps: Cap::all(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
}

#[test]
fn global_summaries_insert_ssa_exact_key_replacement() {
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: Lang::Python,
        namespace: "app.py".into(),
        name: "process".into(),
        arity: Some(1),
        ..Default::default()
    };

    let v1 = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    gs.insert_ssa(key.clone(), v1.clone());
    assert_eq!(gs.get_ssa(&key), Some(&v1));

    // Replace with a different summary, exact replacement, not union
    let v2 = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::StripBits(Cap::HTML_ESCAPE))],
        param_to_sink: vec![(0, cap_sites(Cap::SQL_QUERY))],
        source_caps: Cap::ENV_VAR,
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    gs.insert_ssa(key.clone(), v2.clone());
    assert_eq!(gs.get_ssa(&key), Some(&v2));
}

#[test]
fn global_summaries_merge_with_ssa_entries() {
    let mut gs1 = GlobalSummaries::new();
    let mut gs2 = GlobalSummaries::new();

    let key_a = FuncKey {
        lang: Lang::Python,
        namespace: "a.py".into(),
        name: "foo".into(),
        arity: Some(1),
        ..Default::default()
    };
    let key_b = FuncKey {
        lang: Lang::Python,
        namespace: "b.py".into(),
        name: "bar".into(),
        arity: Some(2),
        ..Default::default()
    };

    let sum_a = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let sum_b = SsaFuncSummary {
        param_to_return: vec![],
        param_to_sink: vec![(0, cap_sites(Cap::CODE_EXEC))],
        source_caps: Cap::ENV_VAR,
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };

    gs1.insert_ssa(key_a.clone(), sum_a.clone());
    gs2.insert_ssa(key_b.clone(), sum_b.clone());

    gs1.merge(gs2);

    assert_eq!(gs1.get_ssa(&key_a), Some(&sum_a));
    assert_eq!(gs1.get_ssa(&key_b), Some(&sum_b));
}

#[test]
fn global_summaries_is_empty_considers_ssa() {
    let mut gs = GlobalSummaries::new();
    assert!(gs.is_empty());

    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "lib.rs".into(),
        name: "f".into(),
        arity: Some(1),
        ..Default::default()
    };
    gs.insert_ssa(
        key,
        SsaFuncSummary {
            param_to_return: vec![(0, TaintTransform::Identity)],
            param_to_sink: vec![],
            source_caps: Cap::empty(),
            param_to_sink_param: vec![],
            param_container_to_return: vec![],
            param_to_container_store: vec![],
            return_type: None,
            return_abstract: None,
            source_to_callback: vec![],

            receiver_to_return: None,

            receiver_to_sink: Cap::empty(),

            abstract_transfer: vec![],
            param_return_paths: vec![],
            points_to: Default::default(),
            field_points_to: Default::default(),
            return_path_facts: smallvec::SmallVec::new(),
            typed_call_receivers: vec![],
            validated_params_to_return: smallvec::SmallVec::new(),
            param_to_gate_filters: vec![],
        },
    );

    assert!(!gs.is_empty());
}

#[test]
fn ssa_summary_serde_round_trip_param_to_sink_param() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![(0, cap_sites(Cap::SQL_QUERY))],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![(0, 0, Cap::SQL_QUERY), (1, 0, Cap::CODE_EXEC)],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
    assert_eq!(back.param_to_sink_param.len(), 2);
    assert_eq!(back.param_to_sink_param[0], (0, 0, Cap::SQL_QUERY));
    assert_eq!(back.param_to_sink_param[1], (1, 0, Cap::CODE_EXEC));
}

#[test]
fn ssa_summary_backward_compat_missing_param_to_sink_param() {
    // Old JSON without param_to_sink_param should deserialize with empty vec
    let json = r#"{
        "param_to_return": [[0, "Identity"]],
        "param_to_sink": [],
        "source_caps": 0
    }"#;
    let summary: SsaFuncSummary = serde_json::from_str(json).unwrap();
    assert!(summary.param_to_sink_param.is_empty());
}

#[test]
fn ssa_summary_serde_round_trip_container_fields() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![0],
        param_to_container_store: vec![(1, 0)],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
    assert_eq!(back.param_container_to_return, vec![0]);
    assert_eq!(back.param_to_container_store, vec![(1, 0)]);
}

#[test]
fn ssa_summary_backward_compat_missing_container_fields() {
    // Old JSON without container fields should deserialize with empty vecs
    let json = r#"{
        "param_to_return": [[0, "Identity"]],
        "param_to_sink": [],
        "source_caps": 0
    }"#;
    let summary: SsaFuncSummary = serde_json::from_str(json).unwrap();
    assert!(summary.param_container_to_return.is_empty());
    assert!(summary.param_to_container_store.is_empty());
}

#[test]
fn ssa_summary_serde_round_trip_return_abstract() {
    use crate::abstract_interp::{AbstractValue, BitFact, IntervalFact, PathFact, StringFact};

    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: Some(AbstractValue {
            interval: IntervalFact {
                lo: Some(-2_147_483_648),
                hi: Some(2_147_483_647),
            },
            string: StringFact::top(),
            bits: BitFact::top(),
            path: PathFact::top(),
        }),
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
    assert!(back.return_abstract.is_some());
    let abs = back.return_abstract.unwrap();
    assert_eq!(abs.interval.lo, Some(-2_147_483_648));
    assert_eq!(abs.interval.hi, Some(2_147_483_647));
    assert!(abs.string.is_top());
}

#[test]
fn ssa_summary_backward_compat_missing_return_abstract() {
    // Old JSON without return_abstract should deserialize with None
    let json = r#"{
        "param_to_return": [],
        "param_to_sink": [],
        "source_caps": 0
    }"#;
    let summary: SsaFuncSummary = serde_json::from_str(json).unwrap();
    assert_eq!(summary.return_abstract, None);
}

// ── CalleeSsaBody serde + GlobalSummaries body resolution ───────────────

/// Helper: build a minimal CalleeSsaBody with a given number of blocks.
#[allow(dead_code)] // used by tests below
fn make_callee_body(
    num_blocks: usize,
    param_count: usize,
) -> crate::taint::ssa_transfer::CalleeSsaBody {
    use crate::ssa::ir::*;
    use smallvec::smallvec;

    let mut blocks = Vec::new();
    for i in 0..num_blocks {
        blocks.push(SsaBlock {
            id: BlockId(i as u32),
            phis: vec![],
            body: vec![SsaInst {
                value: SsaValue(i as u32),
                op: SsaOp::Const(Some("0".into())),
                cfg_node: petgraph::graph::NodeIndex::new(0),
                var_name: None,
                span: (0, 0),
            }],
            terminator: if i + 1 < num_blocks {
                Terminator::Goto(BlockId((i + 1) as u32))
            } else {
                Terminator::Return(Some(SsaValue(0)))
            },
            preds: smallvec![],
            succs: smallvec![],
        });
    }

    let value_defs: Vec<ValueDef> = (0..num_blocks)
        .map(|i| ValueDef {
            var_name: None,
            cfg_node: petgraph::graph::NodeIndex::new(0),
            block: BlockId(i as u32),
        })
        .collect();

    crate::taint::ssa_transfer::CalleeSsaBody {
        ssa: SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs,
            cfg_node_map: std::collections::HashMap::new(),
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::default(),
            field_writes: std::collections::HashMap::new(),

            synthetic_externals: std::collections::HashSet::new(),
        },
        opt: crate::ssa::OptimizeResult {
            const_values: std::collections::HashMap::new(),
            type_facts: crate::ssa::type_facts::TypeFactResult {
                facts: std::collections::HashMap::new(),
            },
            alias_result: crate::ssa::alias::BaseAliasResult::empty(),
            points_to: crate::ssa::heap::PointsToResult::empty(),
            module_aliases: std::collections::HashMap::new(),
            branches_pruned: 0,
            copies_eliminated: 0,
            dead_defs_removed: 0,
        },
        param_count,
        node_meta: std::collections::HashMap::new(),
        body_graph: None,
    }
}

#[test]
fn callee_body_serde_round_trip_empty() {
    let body = make_callee_body(1, 0);
    let json = serde_json::to_string(&body).unwrap();
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();
    assert_eq!(back.param_count, 0);
    assert_eq!(back.ssa.blocks.len(), 1);
    assert!(back.node_meta.is_empty());
}

#[test]
fn callee_body_serde_round_trip_multi_block() {
    let body = make_callee_body(5, 2);
    let json = serde_json::to_string(&body).unwrap();
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();
    assert_eq!(back.param_count, 2);
    assert_eq!(back.ssa.blocks.len(), 5);
    // Verify block structure survived round-trip
    assert_eq!(back.ssa.entry, crate::ssa::ir::BlockId(0));
    assert_eq!(back.ssa.value_defs.len(), 5);
}

#[test]
fn callee_body_serde_round_trip_with_node_meta() {
    use crate::cfg::{NodeInfo, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::taint::ssa_transfer::CrossFileNodeMeta;

    let mut body = make_callee_body(2, 1);
    body.node_meta.insert(
        0,
        CrossFileNodeMeta {
            info: NodeInfo {
                bin_op: Some(crate::cfg::BinOp::Add),
                taint: TaintMeta {
                    labels: smallvec::smallvec![DataLabel::Sink(Cap::HTML_ESCAPE)],
                    ..Default::default()
                },
                ..Default::default()
            },
        },
    );
    body.node_meta.insert(
        1,
        CrossFileNodeMeta {
            info: NodeInfo::default(),
        },
    );

    let json = serde_json::to_string(&body).unwrap();
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();

    assert_eq!(back.node_meta.len(), 2);
    let meta0 = &back.node_meta[&0];
    assert_eq!(meta0.info.bin_op, Some(crate::cfg::BinOp::Add));
    assert_eq!(meta0.info.taint.labels.len(), 1);
    assert!(matches!(meta0.info.taint.labels[0], DataLabel::Sink(cap) if cap == Cap::HTML_ESCAPE));
    assert!(back.node_meta[&1].info.taint.labels.is_empty());
}

#[test]
fn callee_body_serde_node_meta_skipped_when_empty() {
    // Verify #[serde(skip_serializing_if)] works: empty node_meta not in JSON
    let body = make_callee_body(1, 0);
    let json = serde_json::to_string(&body).unwrap();
    assert!(
        !json.contains("node_meta"),
        "empty node_meta should be omitted from JSON"
    );

    // But it should deserialize fine from JSON without node_meta field
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();
    assert!(back.node_meta.is_empty());
}

#[test]
fn callee_body_serde_with_all_ssa_op_variants() {
    use crate::ssa::ir::*;
    use smallvec::smallvec;

    let mut body = make_callee_body(1, 0);
    // Replace the single block's body with all SsaOp variants
    let node = petgraph::graph::NodeIndex::new(0);
    body.ssa.blocks[0].body = vec![
        SsaInst {
            value: SsaValue(0),
            op: SsaOp::Const(Some("hello".into())),
            cfg_node: node,
            var_name: None,
            span: (0, 5),
        },
        SsaInst {
            value: SsaValue(1),
            op: SsaOp::Const(None),
            cfg_node: node,
            var_name: None,
            span: (0, 0),
        },
        SsaInst {
            value: SsaValue(2),
            op: SsaOp::Source,
            cfg_node: node,
            var_name: Some("src".into()),
            span: (6, 10),
        },
        SsaInst {
            value: SsaValue(3),
            op: SsaOp::Param { index: 0 },
            cfg_node: node,
            var_name: Some("p0".into()),
            span: (0, 0),
        },
        SsaInst {
            value: SsaValue(4),
            op: SsaOp::CatchParam,
            cfg_node: node,
            var_name: None,
            span: (0, 0),
        },
        SsaInst {
            value: SsaValue(5),
            op: SsaOp::Nop,
            cfg_node: node,
            var_name: None,
            span: (0, 0),
        },
        SsaInst {
            value: SsaValue(6),
            op: SsaOp::Assign(smallvec![SsaValue(0), SsaValue(1)]),
            cfg_node: node,
            var_name: None,
            span: (0, 0),
        },
        SsaInst {
            value: SsaValue(7),
            op: SsaOp::Call {
                callee: "foo".into(),
                callee_text: None,
                args: vec![smallvec![SsaValue(0)], smallvec![SsaValue(1)]],
                receiver: Some(SsaValue(2)),
            },
            cfg_node: node,
            var_name: None,
            span: (11, 20),
        },
    ];
    body.ssa.blocks[0].phis = vec![SsaInst {
        value: SsaValue(8),
        op: SsaOp::Phi(smallvec![
            (BlockId(0), SsaValue(0)),
            (BlockId(1), SsaValue(1))
        ]),
        cfg_node: node,
        var_name: None,
        span: (0, 0),
    }];

    let json = serde_json::to_string(&body).unwrap();
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();

    assert_eq!(back.ssa.blocks[0].body.len(), 8);
    assert_eq!(back.ssa.blocks[0].phis.len(), 1);

    // Spot check: Call op preserved
    match &back.ssa.blocks[0].body[7].op {
        SsaOp::Call {
            callee,
            args,
            receiver,
            ..
        } => {
            assert_eq!(callee, "foo");
            assert_eq!(args.len(), 2);
            assert_eq!(*receiver, Some(SsaValue(2)));
        }
        other => panic!("expected Call, got {:?}", other),
    }
    // Spot check: Phi op preserved
    match &back.ssa.blocks[0].phis[0].op {
        SsaOp::Phi(ops) => {
            assert_eq!(ops.len(), 2);
            assert_eq!(ops[0], (BlockId(0), SsaValue(0)));
        }
        other => panic!("expected Phi, got {:?}", other),
    }
}

#[test]
fn callee_body_serde_with_branch_terminator() {
    use crate::constraint::lower::ConditionExpr;
    use crate::ssa::ir::*;

    let mut body = make_callee_body(3, 0);
    // Set a Branch terminator with a condition
    body.ssa.blocks[0].terminator = Terminator::Branch {
        cond: petgraph::graph::NodeIndex::new(0),
        true_blk: BlockId(1),
        false_blk: BlockId(2),
        condition: Some(Box::new(ConditionExpr::BoolTest { var: SsaValue(0) })),
    };

    let json = serde_json::to_string(&body).unwrap();
    let back: crate::taint::ssa_transfer::CalleeSsaBody = serde_json::from_str(&json).unwrap();

    match &back.ssa.blocks[0].terminator {
        Terminator::Branch {
            true_blk,
            false_blk,
            condition,
            ..
        } => {
            assert_eq!(*true_blk, BlockId(1));
            assert_eq!(*false_blk, BlockId(2));
            assert!(condition.is_some());
            match condition.as_deref() {
                Some(ConditionExpr::BoolTest { var }) => {
                    assert_eq!(*var, SsaValue(0));
                }
                other => panic!("expected BoolTest, got {:?}", other),
            }
        }
        other => panic!("expected Branch, got {:?}", other),
    }
}

// ── GlobalSummaries body resolution ──────────────────────────────────────

#[test]
fn global_summaries_insert_body_exact_key_replacement() {
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "helper.py".into(),
        name: "transform".into(),
        arity: Some(2),
        ..Default::default()
    };

    let body1 = make_callee_body(3, 2);
    let body2 = make_callee_body(5, 2);

    gs.insert_body(key.clone(), body1);
    assert_eq!(gs.get_body(&key).unwrap().ssa.blocks.len(), 3);

    // Second insert replaces (exact-key, no union)
    gs.insert_body(key.clone(), body2);
    assert_eq!(gs.get_body(&key).unwrap().ssa.blocks.len(), 5);
}

#[test]
fn global_summaries_get_body_not_found() {
    let gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "missing.py".into(),
        name: "nope".into(),
        arity: Some(0),
        ..Default::default()
    };
    assert!(gs.get_body(&key).is_none());
}

#[test]
fn global_summaries_merge_includes_bodies() {
    let mut gs1 = GlobalSummaries::new();
    let mut gs2 = GlobalSummaries::new();

    let key1 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "a.py".into(),
        name: "func_a".into(),
        arity: Some(1),
        ..Default::default()
    };
    let key2 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "b.py".into(),
        name: "func_b".into(),
        arity: Some(2),
        ..Default::default()
    };

    // Need to also insert regular summaries so the by_lang_name index is populated
    gs1.insert(key1.clone(), make("func_a", 0, 0, 0));
    gs1.insert_body(key1.clone(), make_callee_body(2, 1));

    gs2.insert(key2.clone(), make("func_b", 0, 0, 0));
    gs2.insert_body(key2.clone(), make_callee_body(4, 2));

    gs1.merge(gs2);

    assert!(gs1.get_body(&key1).is_some());
    assert!(gs1.get_body(&key2).is_some());
    assert_eq!(gs1.get_body(&key1).unwrap().ssa.blocks.len(), 2);
    assert_eq!(gs1.get_body(&key2).unwrap().ssa.blocks.len(), 4);
}

#[test]
fn global_summaries_resolve_callee_body_exact_match() {
    let mut gs = GlobalSummaries::new();

    let key = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "util.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };

    gs.insert(key.clone(), make("helper", 0, 0, 0));
    gs.insert_body(key.clone(), make_callee_body(3, 1));

    // Resolve with matching lang/name/arity
    let resolved = gs.resolve_callee_body(crate::symbol::Lang::Python, "helper", Some(1), "app.py");
    assert!(resolved.is_some());
    assert_eq!(resolved.unwrap().ssa.blocks.len(), 3);
}

#[test]
fn global_summaries_resolve_callee_body_not_found() {
    let gs = GlobalSummaries::new();

    let resolved =
        gs.resolve_callee_body(crate::symbol::Lang::Python, "missing", Some(1), "app.py");
    assert!(resolved.is_none());
}

#[test]
fn global_summaries_resolve_callee_body_ambiguous_returns_none() {
    let mut gs = GlobalSummaries::new();

    // Two functions with same name but different namespaces
    let key1 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "a.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };
    let key2 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "b.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };

    gs.insert(key1.clone(), make("helper", 0, 0, 0));
    gs.insert_body(key1.clone(), make_callee_body(2, 1));
    gs.insert(key2.clone(), make("helper", 0, 0, 0));
    gs.insert_body(key2.clone(), make_callee_body(4, 1));

    // Resolution from a third namespace → ambiguous → None
    let resolved = gs.resolve_callee_body(crate::symbol::Lang::Python, "helper", Some(1), "c.py");
    assert!(
        resolved.is_none(),
        "ambiguous resolution should return None"
    );
}

#[test]
fn global_summaries_resolve_callee_body_namespace_disambiguates() {
    let mut gs = GlobalSummaries::new();

    let key1 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "a.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };
    let key2 = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "b.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };

    gs.insert(key1.clone(), make("helper", 0, 0, 0));
    gs.insert_body(key1.clone(), make_callee_body(2, 1));
    gs.insert(key2.clone(), make("helper", 0, 0, 0));
    gs.insert_body(key2.clone(), make_callee_body(4, 1));

    // Resolution from a.py → namespace match → key1 (2 blocks)
    let resolved = gs.resolve_callee_body(crate::symbol::Lang::Python, "helper", Some(1), "a.py");
    assert!(resolved.is_some());
    assert_eq!(resolved.unwrap().ssa.blocks.len(), 2);
}

#[test]
fn global_summaries_resolve_body_requires_body_present() {
    let mut gs = GlobalSummaries::new();

    // Insert summary but no body
    let key = FuncKey {
        lang: crate::symbol::Lang::Python,
        namespace: "util.py".into(),
        name: "helper".into(),
        arity: Some(1),
        ..Default::default()
    };
    gs.insert(key.clone(), make("helper", 0, 0, 0));
    gs.insert_ssa(
        key.clone(),
        SsaFuncSummary {
            param_to_return: vec![],
            param_to_sink: vec![],
            source_caps: crate::labels::Cap::empty(),
            param_to_sink_param: vec![],
            param_container_to_return: vec![],
            param_to_container_store: vec![],
            return_type: None,
            return_abstract: None,
            source_to_callback: vec![],

            receiver_to_return: None,

            receiver_to_sink: Cap::empty(),

            abstract_transfer: vec![],
            param_return_paths: vec![],
            points_to: Default::default(),
            field_points_to: Default::default(),
            return_path_facts: smallvec::SmallVec::new(),
            typed_call_receivers: vec![],
            validated_params_to_return: smallvec::SmallVec::new(),
            param_to_gate_filters: vec![],
        },
    );
    // Don't insert body

    // Resolution finds the key but no body
    let resolved = gs.resolve_callee_body(crate::symbol::Lang::Python, "helper", Some(1), "app.py");
    assert!(
        resolved.is_none(),
        "should return None when key resolves but no body stored"
    );
}

// ── Identity-model regression tests ─────────────────────────────────────
// Each test below encodes one ambiguity the old `(file, name, arity)` key
// couldn't express.  They guard the new `(lang, namespace, container, name,
// arity, disambig, kind)` model and the container-aware resolver.

fn fs_with(
    namespace: &str,
    container: &str,
    name: &str,
    arity: usize,
    kind: FuncKind,
    disambig: Option<u32>,
    sink_bits: u16,
) -> (FuncKey, FuncSummary) {
    let key = FuncKey {
        lang: Lang::Java,
        namespace: namespace.into(),
        container: container.into(),
        name: name.into(),
        arity: Some(arity),
        disambig,
        kind,
    };
    let summary = FuncSummary {
        name: name.into(),
        file_path: namespace.into(),
        lang: "java".into(),
        param_count: arity,
        sink_caps: sink_bits,
        container: container.into(),
        disambig,
        kind,
        ..Default::default()
    };
    (key, summary)
}

#[test]
fn same_name_methods_on_different_classes_stay_distinct() {
    let mut gs = GlobalSummaries::new();
    let (k1, s1) = fs_with(
        "src/svc.java",
        "OrderService",
        "process",
        1,
        FuncKind::Method,
        Some(100),
        0x01,
    );
    let (k2, s2) = fs_with(
        "src/svc.java",
        "UserService",
        "process",
        1,
        FuncKind::Method,
        Some(500),
        0x02,
    );
    gs.insert(k1.clone(), s1);
    gs.insert(k2.clone(), s2);

    assert_eq!(gs.get(&k1).unwrap().sink_caps, 0x01);
    assert_eq!(gs.get(&k2).unwrap().sink_caps, 0x02);

    let order = gs.resolve_callee_key_with_container(
        "process",
        Lang::Java,
        "src/other.java",
        Some("OrderService"),
        Some(1),
    );
    assert_eq!(order, CalleeResolution::Resolved(k1));

    let user = gs.resolve_callee_key_with_container(
        "process",
        Lang::Java,
        "src/other.java",
        Some("UserService"),
        Some(1),
    );
    assert_eq!(user, CalleeResolution::Resolved(k2));
}

#[test]
fn free_function_and_method_with_same_name_resolve_separately() {
    let mut gs = GlobalSummaries::new();
    let (kf, sf) = fs_with(
        "src/app.java",
        "",
        "process",
        1,
        FuncKind::Function,
        Some(10),
        0x10,
    );
    let (km, sm) = fs_with(
        "src/app.java",
        "Worker",
        "process",
        1,
        FuncKind::Method,
        Some(200),
        0x20,
    );
    gs.insert(kf.clone(), sf);
    gs.insert(km.clone(), sm);

    let free =
        gs.resolve_callee_key_with_container("process", Lang::Java, "src/app.java", None, Some(1));
    let method = gs.resolve_callee_key_with_container(
        "process",
        Lang::Java,
        "src/app.java",
        Some("Worker"),
        Some(1),
    );
    assert_eq!(method, CalleeResolution::Resolved(km));

    // Without any qualifier, receiver, or receiver_type, a bare
    // `process()` call is syntactically a free-function invocation, a
    // method cannot be invoked that way from outside its class.  The
    // resolver's bare-call preference (step 5.5) picks the sole
    // empty-container candidate deterministically.
    assert_eq!(free, CalleeResolution::Resolved(kf));
}

#[test]
fn disambig_separates_same_name_closures_in_same_container() {
    let mut gs = GlobalSummaries::new();
    let (k1, s1) = fs_with(
        "src/f.js",
        "outer",
        "<anon>",
        0,
        FuncKind::Closure,
        Some(123),
        0x01,
    );
    let (k2, s2) = fs_with(
        "src/f.js",
        "outer",
        "<anon>",
        0,
        FuncKind::Closure,
        Some(456),
        0x02,
    );
    gs.insert(k1.clone(), s1);
    gs.insert(k2.clone(), s2);

    assert_ne!(k1, k2);
    assert_eq!(gs.get(&k1).unwrap().sink_caps, 0x01);
    assert_eq!(gs.get(&k2).unwrap().sink_caps, 0x02);
}

#[test]
fn interop_lookup_tolerates_missing_disambig() {
    // Interop edges written by external configuration don't know byte offsets.
    // `get_for_interop` should still find a single matching key when disambig
    // is None and the rest of the identity uniquely identifies a summary.
    let mut gs = GlobalSummaries::new();
    let (k, s) = fs_with(
        "lib.go",
        "",
        "fetch_env",
        0,
        FuncKind::Function,
        Some(7777),
        0x04,
    );
    // Go summaries are actually keyed with Lang::Go; use a distinct key here.
    let go_key = FuncKey {
        lang: Lang::Go,
        namespace: "lib.go".into(),
        container: String::new(),
        name: "fetch_env".into(),
        arity: Some(0),
        disambig: Some(7777),
        kind: FuncKind::Function,
    };
    let go_sum = FuncSummary {
        name: "fetch_env".into(),
        file_path: "lib.go".into(),
        lang: "go".into(),
        ..s
    };
    gs.insert(go_key, go_sum);
    let _ = k; // unused: only needed for symmetry with fs_with signature

    let interop_query = FuncKey {
        lang: Lang::Go,
        namespace: "lib.go".into(),
        container: String::new(),
        name: "fetch_env".into(),
        arity: Some(0),
        disambig: None,
        kind: FuncKind::Function,
    };
    let hit = gs
        .get_for_interop(&interop_query)
        .expect("interop lookup should tolerate missing disambig");
    assert_eq!(hit.sink_caps, 0x04);
}

#[test]
fn interop_lookup_returns_none_when_disambig_none_matches_many() {
    // If multiple summaries share (lang, ns, container, name, arity, kind)
    // and only disambig distinguishes them, the relaxed interop lookup must
    // return None rather than picking arbitrarily.
    let mut gs = GlobalSummaries::new();
    let mk = |disambig: u32, bits: u16| {
        let k = FuncKey {
            lang: Lang::Go,
            namespace: "lib.go".into(),
            container: String::new(),
            name: "dup".into(),
            arity: Some(0),
            disambig: Some(disambig),
            kind: FuncKind::Function,
        };
        let s = FuncSummary {
            name: "dup".into(),
            file_path: "lib.go".into(),
            lang: "go".into(),
            sink_caps: bits,
            disambig: Some(disambig),
            ..Default::default()
        };
        (k, s)
    };
    let (k1, s1) = mk(1, 0x01);
    let (k2, s2) = mk(2, 0x02);
    gs.insert(k1, s1);
    gs.insert(k2, s2);

    let ambiguous_query = FuncKey {
        lang: Lang::Go,
        namespace: "lib.go".into(),
        container: String::new(),
        name: "dup".into(),
        arity: Some(0),
        disambig: None,
        kind: FuncKind::Function,
    };
    assert!(
        gs.get_for_interop(&ambiguous_query).is_none(),
        "disambig=None must not pick arbitrarily when multiple keys match"
    );
}

// ── CalleeSite metadata ─────────────────────────────────────────────────

#[test]
fn callee_site_bare_constructor() {
    let site = CalleeSite::bare("helper");
    assert_eq!(site.name, "helper");
    assert_eq!(site.arity, None);
    assert_eq!(site.receiver, None);
    assert_eq!(site.qualifier, None);
    assert_eq!(site.ordinal, 0);
}

#[test]
fn callee_site_str_into_coercion() {
    // Tests that `"name".into()` still works for building callee lists in
    // test code, despite the field now being `Vec<CalleeSite>`.
    let v: Vec<CalleeSite> = vec!["foo".into(), "bar".into()];
    assert_eq!(v.len(), 2);
    assert_eq!(v[0].name, "foo");
    assert_eq!(v[1].name, "bar");
}

#[test]
fn callee_site_structured_roundtrip() {
    let summary = FuncSummary {
        name: "parent".into(),
        file_path: "x.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        callees: vec![
            CalleeSite {
                name: "obj.method".into(),
                arity: Some(2),
                receiver: Some("obj".into()),
                qualifier: None,
                ordinal: 1,
            },
            CalleeSite {
                name: "env::var".into(),
                arity: Some(1),
                receiver: None,
                qualifier: Some("env".into()),
                ordinal: 2,
            },
        ],
        ..Default::default()
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: FuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(back.callees.len(), 2);
    assert_eq!(back.callees[0].name, "obj.method");
    assert_eq!(back.callees[0].arity, Some(2));
    assert_eq!(back.callees[0].receiver.as_deref(), Some("obj"));
    assert_eq!(back.callees[0].ordinal, 1);
    assert_eq!(back.callees[1].qualifier.as_deref(), Some("env"));
}

#[test]
fn legacy_callees_string_array_deserializes() {
    // Old on-disk rows stored callees as a plain Vec<String>.
    // The custom deserializer must lift those into CalleeSite { name, .. }
    // without other metadata so persisted indexes keep working.
    let json = r#"{
        "name": "legacy",
        "file_path": "legacy.rs",
        "lang": "rust",
        "param_count": 0,
        "param_names": [],
        "source_caps": 0,
        "sanitizer_caps": 0,
        "sink_caps": 0,
        "propagating_params": [],
        "tainted_sink_params": [],
        "callees": ["foo", "bar::baz"]
    }"#;
    let s: FuncSummary = serde_json::from_str(json).unwrap();
    assert_eq!(s.callees.len(), 2);
    assert_eq!(s.callees[0].name, "foo");
    assert_eq!(s.callees[0].arity, None);
    assert_eq!(s.callees[1].name, "bar::baz");
    assert_eq!(s.callees[1].receiver, None);
}

#[test]
fn mixed_callee_form_deserializes() {
    // Interop / partial-migration rows may mix legacy strings with
    // structured entries in the same array, deserializer accepts both.
    let json = r#"{
        "name": "mixed",
        "file_path": "m.rs",
        "lang": "rust",
        "param_count": 0,
        "param_names": [],
        "source_caps": 0,
        "sanitizer_caps": 0,
        "sink_caps": 0,
        "propagating_params": [],
        "tainted_sink_params": [],
        "callees": [
            "legacy_fn",
            {"name": "new_fn", "arity": 3, "receiver": "obj"}
        ]
    }"#;
    let s: FuncSummary = serde_json::from_str(json).unwrap();
    assert_eq!(s.callees.len(), 2);
    assert_eq!(s.callees[0].name, "legacy_fn");
    assert_eq!(s.callees[0].arity, None);
    assert_eq!(s.callees[1].name, "new_fn");
    assert_eq!(s.callees[1].arity, Some(3));
    assert_eq!(s.callees[1].receiver.as_deref(), Some("obj"));
}

// ── Rust module-path resolution (qualified Rust paths) ──────────────────

/// Helper: build a Rust summary populated with module-path + use-map fields.
fn rust_summary_with_mod(
    name: &str,
    file_path: &str,
    param_count: usize,
    module_path: Option<&str>,
    use_map: &[(&str, &str)],
    wildcards: &[&str],
    callees: Vec<CalleeSite>,
) -> FuncSummary {
    let aliases: BTreeMap<String, String> = use_map
        .iter()
        .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
        .collect();
    FuncSummary {
        name: name.into(),
        file_path: file_path.into(),
        lang: "rust".into(),
        param_count,
        param_names: vec![],
        source_caps: 0,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees,
        module_path: module_path.map(str::to_string),
        rust_use_map: if aliases.is_empty() {
            None
        } else {
            Some(aliases)
        },
        rust_wildcards: if wildcards.is_empty() {
            None
        } else {
            Some(wildcards.iter().map(|s| (*s).to_string()).collect())
        },
        ..Default::default()
    }
}

#[test]
fn rust_use_map_disambiguates_same_name_across_modules() {
    // Two `validate` functions in different modules.
    let token = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/token.rs",
        1,
        Some("auth::token"),
        &[],
        &[],
        vec![],
    );
    let session = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/session.rs",
        1,
        Some("auth::session"),
        &[],
        &[],
        vec![],
    );
    // Caller imports crate::auth::token::validate and calls `validate(x)`.
    let caller = rust_summary_with_mod(
        "handler",
        "/proj/src/main.rs",
        0,
        Some(""),
        &[("validate", "crate::auth::token::validate")],
        &[],
        vec![CalleeSite {
            name: "validate".into(),
            arity: Some(1),
            ..Default::default()
        }],
    );

    let gs = merge_summaries(vec![token, session, caller], Some("/proj"));
    // Pull the token key back out and verify exact-one resolution.
    let caller_key = FuncKey {
        lang: Lang::Rust,
        namespace: "src/main.rs".into(),
        name: "handler".into(),
        arity: Some(0),
        ..Default::default()
    };
    let caller_sum = gs.get(&caller_key).expect("caller summary");
    let use_map = crate::rust_resolve::RustUseMap {
        aliases: caller_sum.rust_use_map.clone().unwrap_or_default(),
        wildcards: caller_sum.rust_wildcards.clone().unwrap_or_default(),
    };
    let resolution = gs.resolve_callee_key_rust(
        "validate",
        None,
        Some(1),
        &caller_key.namespace,
        Some(&use_map),
    );
    match resolution {
        CalleeResolution::Resolved(k) => {
            assert_eq!(k.namespace, "src/auth/token.rs");
            assert_eq!(k.name, "validate");
        }
        other => panic!(
            "expected token::validate to resolve uniquely, got {:?}",
            other
        ),
    }
}

#[test]
fn rust_use_map_qualified_call_via_module_alias() {
    // `use crate::auth::token;  token::validate(x);`
    let token = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/token.rs",
        1,
        Some("auth::token"),
        &[],
        &[],
        vec![],
    );
    let caller = rust_summary_with_mod(
        "handler",
        "/proj/src/main.rs",
        0,
        Some(""),
        &[("token", "crate::auth::token")],
        &[],
        vec![CalleeSite {
            name: "token::validate".into(),
            arity: Some(1),
            qualifier: Some("crate::auth::token".into()),
            ..Default::default()
        }],
    );

    let gs = merge_summaries(vec![token, caller], Some("/proj"));
    let um = crate::rust_resolve::RustUseMap {
        aliases: [("token".to_string(), "crate::auth::token".to_string())]
            .into_iter()
            .collect(),
        wildcards: Vec::new(),
    };
    // The site's structured qualifier is the full `crate::auth::token`; the
    // resolver's alias map matches the first segment.
    let resolution =
        gs.resolve_callee_key_rust("validate", Some("token"), Some(1), "src/main.rs", Some(&um));
    match resolution {
        CalleeResolution::Resolved(k) => {
            assert_eq!(k.namespace, "src/auth/token.rs");
        }
        other => panic!("expected unique resolution, got {:?}", other),
    }
}

#[test]
fn rust_wildcard_import_resolves_uniquely() {
    let token = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/token.rs",
        1,
        Some("auth::token"),
        &[],
        &[],
        vec![],
    );
    let caller = rust_summary_with_mod(
        "handler",
        "/proj/src/main.rs",
        0,
        Some(""),
        &[],
        &["crate::auth::token"],
        vec![CalleeSite {
            name: "validate".into(),
            arity: Some(1),
            ..Default::default()
        }],
    );

    let gs = merge_summaries(vec![token, caller], Some("/proj"));
    let um = crate::rust_resolve::RustUseMap {
        aliases: BTreeMap::new(),
        wildcards: vec!["crate::auth::token".to_string()],
    };
    let resolution =
        gs.resolve_callee_key_rust("validate", None, Some(1), "src/main.rs", Some(&um));
    match resolution {
        CalleeResolution::Resolved(k) => {
            assert_eq!(k.namespace, "src/auth/token.rs");
        }
        other => panic!("wildcard should resolve uniquely, got {:?}", other),
    }
}

#[test]
fn rust_use_map_fallback_when_absent() {
    // No use_map entry, falls through to generic same-language resolution,
    // which for an unqualified caller in the same namespace still works.
    let helper = rust_summary_with_mod("helper", "/proj/src/lib.rs", 0, Some(""), &[], &[], vec![]);
    let caller = rust_summary_with_mod(
        "caller",
        "/proj/src/lib.rs",
        0,
        Some(""),
        &[],
        &[],
        vec![CalleeSite {
            name: "helper".into(),
            arity: Some(0),
            ..Default::default()
        }],
    );

    let gs = merge_summaries(vec![helper, caller], Some("/proj"));
    let resolution = gs.resolve_callee_key_rust("helper", None, Some(0), "src/lib.rs", None);
    assert!(matches!(resolution, CalleeResolution::Resolved(_)));
}

#[test]
fn rust_use_map_ambiguous_stays_ambiguous_without_hint() {
    // Two modules define `validate`; no use-map on the caller, resolution
    // should remain Ambiguous rather than silently picking one.
    let token = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/token.rs",
        1,
        Some("auth::token"),
        &[],
        &[],
        vec![],
    );
    let session = rust_summary_with_mod(
        "validate",
        "/proj/src/auth/session.rs",
        1,
        Some("auth::session"),
        &[],
        &[],
        vec![],
    );
    let caller = rust_summary_with_mod(
        "handler",
        "/proj/src/main.rs",
        0,
        Some(""),
        &[],
        &[],
        vec![CalleeSite {
            name: "validate".into(),
            arity: Some(1),
            ..Default::default()
        }],
    );
    let gs = merge_summaries(vec![token, session, caller], Some("/proj"));
    let resolution = gs.resolve_callee_key_rust("validate", None, Some(1), "src/main.rs", None);
    assert!(matches!(resolution, CalleeResolution::Ambiguous(_)));
}

// ── Serde round-trip / backward compatibility ────────────────────────────

#[test]
fn pre_rust_fields_json_deserializes_with_defaults() {
    // A summary JSON written before the Rust `module_path`/`rust_use_map`/
    // `rust_wildcards` fields existed must still deserialise cleanly with
    // all three defaulting to `None`.
    let legacy_json = r#"{
        "name": "old",
        "file_path": "src/lib.rs",
        "lang": "rust",
        "param_count": 1,
        "param_names": ["x"],
        "source_caps": 0,
        "sanitizer_caps": 0,
        "sink_caps": 0,
        "propagating_params": [0],
        "tainted_sink_params": [],
        "callees": []
    }"#;
    let s: FuncSummary = serde_json::from_str(legacy_json).unwrap();
    assert_eq!(s.name, "old");
    assert!(s.module_path.is_none());
    assert!(s.rust_use_map.is_none());
    assert!(s.rust_wildcards.is_none());
}

#[test]
fn rust_fields_roundtrip_through_json() {
    let mut aliases = BTreeMap::new();
    aliases.insert(
        "validate".to_string(),
        "crate::auth::token::validate".to_string(),
    );
    let s = FuncSummary {
        name: "handler".into(),
        file_path: "src/main.rs".into(),
        lang: "rust".into(),
        param_count: 0,
        param_names: vec![],
        source_caps: 0,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![],
        propagates_taint: false,
        tainted_sink_params: vec![],
        callees: vec![],
        module_path: Some(String::new()),
        rust_use_map: Some(aliases.clone()),
        rust_wildcards: Some(vec!["crate::auth::session".to_string()]),
        ..Default::default()
    };

    let json = serde_json::to_string(&s).unwrap();
    let back: FuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(back.module_path.as_deref(), Some(""));
    assert_eq!(back.rust_use_map.unwrap(), aliases);
    assert_eq!(
        back.rust_wildcards.unwrap(),
        vec!["crate::auth::session".to_string()]
    );
}

// ── Qualified-first callee resolution (adversarial) ─────────────────────
//
// Each test here stages a same-leaf-name collision that the old leaf-only
// resolver would either silently pick wrong or flag as ambiguous.  Under
// the new `CalleeQuery` path, qualified identity (receiver type /
// namespace qualifier / caller container) must win before any bare-leaf
// fallback kicks in.

fn method_summary(
    namespace: &str,
    container: &str,
    name: &str,
    arity: usize,
    sink_bits: u16,
) -> (FuncKey, FuncSummary) {
    fs_with(
        namespace,
        container,
        name,
        arity,
        FuncKind::Method,
        Some((namespace.len() + container.len() + name.len()) as u32),
        sink_bits,
    )
}

fn free_summary(
    namespace: &str,
    name: &str,
    arity: usize,
    sink_bits: u16,
) -> (FuncKey, FuncSummary) {
    fs_with(
        namespace,
        "",
        name,
        arity,
        FuncKind::Function,
        Some((namespace.len() + name.len()) as u32),
        sink_bits,
    )
}

#[test]
fn query_prefers_receiver_type_over_leaf_collision() {
    // Two classes in different files both expose `send/1`.  A free
    // function also named `send/1` sits in yet another file to make the
    // leaf-name index ambiguous.  The caller lives outside all three.
    let mut gs = GlobalSummaries::new();
    let (k_http, s_http) = method_summary("src/http.java", "HttpClient", "send", 1, 0x01);
    let (k_queue, s_queue) = method_summary("src/queue.java", "MessageQueue", "send", 1, 0x02);
    let (k_free, s_free) = free_summary("src/util.java", "send", 1, 0x04);
    gs.insert(k_http.clone(), s_http);
    gs.insert(k_queue.clone(), s_queue);
    gs.insert(k_free.clone(), s_free);

    // With `receiver_type = HttpClient`, resolution MUST land on the
    // HttpClient method even though `MessageQueue::send/1` and the free
    // function `send/1` would both match the leaf name.
    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "send",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: Some("HttpClient"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(resolved, CalleeResolution::Resolved(k_http.clone()));

    // Old behaviour-parity regression: `resolve_callee_key_with_container`
    // (now a thin wrapper) used to treat `MessageQueue` as an authoritative
    // qualifier that *only* picked on exact match.  The new resolver must
    // still do that, swap to `MessageQueue` and we get its method back.
    let resolved_queue = gs.resolve_callee(&CalleeQuery {
        name: "send",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: Some("MessageQueue"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(resolved_queue, CalleeResolution::Resolved(k_queue));
    // And the leaf-name index *does* know about the free function: no
    // hint → ambiguous (not a silent mis-resolve).
    let bare = gs.resolve_callee_key("send", Lang::Java, "src/app.java", Some(1));
    match bare {
        CalleeResolution::Ambiguous(cands) => {
            assert_eq!(cands.len(), 3);
            assert!(cands.contains(&k_http));
            assert!(cands.contains(&k_free));
        }
        other => panic!("bare leaf lookup with 3 candidates must be Ambiguous, got {other:?}"),
    }
}

#[test]
fn query_authoritative_receiver_miss_does_not_fall_through_to_leaf() {
    // When `receiver_type = HttpClient` is supplied but no
    // `HttpClient::send` exists, the resolver MUST NOT silently pick a
    // same-leaf collision in another container, that would be the
    // classic "resolved by leaf name" bug the refactor aims to prevent.
    let mut gs = GlobalSummaries::new();
    let (k_queue, s_queue) = method_summary("src/queue.java", "MessageQueue", "send", 1, 0x02);
    let (k_free, s_free) = free_summary("src/util.java", "send", 1, 0x04);
    gs.insert(k_queue.clone(), s_queue);
    gs.insert(k_free.clone(), s_free);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "send",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: Some("HttpClient"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    match resolved {
        CalleeResolution::Ambiguous(cands) => {
            // Candidates list reports the leaf-name matches so callers
            // can diagnose, but we refused to pick one of them.
            assert!(cands.contains(&k_queue));
            assert!(cands.contains(&k_free));
        }
        other => panic!(
            "authoritative receiver_type miss must return Ambiguous (never silently resolve to a \
             different container), got {other:?}"
        ),
    }
}

#[test]
fn query_namespace_qualifier_resolves_env_var_style_call() {
    // Rust / C++-style namespace qualifiers should land on the module
    // that exposes the leaf, even when same-leaf functions live in
    // unrelated modules.
    let mut gs = GlobalSummaries::new();
    let (k_env, s_env) = fs_with(
        "src/env.rs",
        "env",
        "var",
        1,
        FuncKind::Function,
        Some(1),
        0x01,
    );
    // Force the insertion to use Rust lang by shadowing fs_with's Java default.
    let k_env = FuncKey {
        lang: Lang::Rust,
        ..k_env
    };
    let s_env = FuncSummary {
        lang: "rust".into(),
        ..s_env
    };
    let (k_other, s_other) = fs_with(
        "src/other.rs",
        "config",
        "var",
        1,
        FuncKind::Function,
        Some(2),
        0x02,
    );
    let k_other = FuncKey {
        lang: Lang::Rust,
        ..k_other
    };
    let s_other = FuncSummary {
        lang: "rust".into(),
        ..s_other
    };
    gs.insert(k_env.clone(), s_env);
    gs.insert(k_other.clone(), s_other);

    // `env::var` → namespace_qualifier = "env" → env::var wins.
    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "var",
        caller_lang: Lang::Rust,
        caller_namespace: "src/consumer.rs",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: Some("env"),
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(resolved, CalleeResolution::Resolved(k_env.clone()));

    // `config::var` → namespace_qualifier = "config" → config::var wins.
    let resolved_cfg = gs.resolve_callee(&CalleeQuery {
        name: "var",
        caller_lang: Lang::Rust,
        caller_namespace: "src/consumer.rs",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: Some("config"),
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(resolved_cfg, CalleeResolution::Resolved(k_other));

    // Bare `var(...)` call (no qualifier) across namespaces → Ambiguous.
    let bare = gs.resolve_callee_key("var", Lang::Rust, "src/consumer.rs", Some(1));
    assert!(matches!(bare, CalleeResolution::Ambiguous(_)));
}

#[test]
fn query_caller_container_resolves_self_call() {
    // Bare `helper()` from inside `OrderService::place` must resolve to
    // the `OrderService::helper` method rather than a same-name helper
    // exposed by an unrelated class in a different file.
    let mut gs = GlobalSummaries::new();
    let (k_order, s_order) = method_summary("src/order.java", "OrderService", "helper", 0, 0xA);
    let (k_user, s_user) = method_summary("src/user.java", "UserService", "helper", 0, 0xB);
    gs.insert(k_order.clone(), s_order);
    gs.insert(k_user.clone(), s_user);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "helper",
        caller_lang: Lang::Java,
        caller_namespace: "src/order.java",
        caller_container: Some("OrderService"),
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(0),
    });
    assert_eq!(resolved, CalleeResolution::Resolved(k_order.clone()));

    // Swap the caller to `UserService` and we should land on its helper.
    let resolved_user = gs.resolve_callee(&CalleeQuery {
        name: "helper",
        caller_lang: Lang::Java,
        caller_namespace: "src/user.java",
        caller_container: Some("UserService"),
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(0),
    });
    assert_eq!(resolved_user, CalleeResolution::Resolved(k_user));

    // With no caller-container hint (free call from module-level code),
    // the resolver must not pick either class's helper blindly.
    let no_hint = gs.resolve_callee(&CalleeQuery {
        name: "helper",
        caller_lang: Lang::Java,
        caller_namespace: "src/main.java",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(0),
    });
    assert!(matches!(no_hint, CalleeResolution::Ambiguous(_)));
}

#[test]
fn query_leaf_same_namespace_still_resolves_intra_file_calls() {
    // Two definitions share a leaf name but live in different files.
    // A same-namespace call (intra-file) must resolve to the local one
    // without requiring any structured hint, this is the common case
    // for bare top-level function calls.
    let mut gs = GlobalSummaries::new();
    let (k_a, s_a) = free_summary("src/a.js", "helper", 1, 0x01);
    let (k_b, s_b) = free_summary("src/b.js", "helper", 1, 0x02);
    gs.insert(k_a.clone(), s_a);
    gs.insert(k_b.clone(), s_b);

    // Caller in a.js → resolves to a.js::helper.
    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "helper",
        caller_lang: Lang::Java,
        caller_namespace: "src/a.js",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(resolved, CalleeResolution::Resolved(k_a));

    // Caller in a third file → ambiguous (we refuse to guess).
    let cross = gs.resolve_callee(&CalleeQuery {
        name: "helper",
        caller_lang: Lang::Java,
        caller_namespace: "src/c.js",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    match cross {
        CalleeResolution::Ambiguous(cands) => {
            assert_eq!(cands.len(), 2);
            assert!(cands.contains(&k_b));
        }
        other => panic!("cross-file bare leaf should be Ambiguous, got {other:?}"),
    }
}

#[test]
fn query_arity_filter_is_hard() {
    // Same container and leaf, different arities, resolution must
    // honour the arity filter before any qualifier-based tie-break.
    let mut gs = GlobalSummaries::new();
    let (k_1arg, s_1arg) = method_summary("src/svc.py", "Svc", "render", 1, 0x01);
    let (k_2arg, s_2arg) = method_summary("src/svc.py", "Svc", "render", 2, 0x02);
    gs.insert(k_1arg.clone(), s_1arg);
    gs.insert(k_2arg.clone(), s_2arg);

    let one = gs.resolve_callee(&CalleeQuery {
        name: "render",
        caller_lang: Lang::Java,
        caller_namespace: "src/caller.py",
        caller_container: None,
        receiver_type: Some("Svc"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(one, CalleeResolution::Resolved(k_1arg));

    let two = gs.resolve_callee(&CalleeQuery {
        name: "render",
        caller_lang: Lang::Java,
        caller_namespace: "src/caller.py",
        caller_container: None,
        receiver_type: Some("Svc"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(2),
    });
    assert_eq!(two, CalleeResolution::Resolved(k_2arg));

    // With a non-existent arity, arity filter prunes everything and we
    // get NotFound, not a "closest match" guess.
    let mismatched = gs.resolve_callee(&CalleeQuery {
        name: "render",
        caller_lang: Lang::Java,
        caller_namespace: "src/caller.py",
        caller_container: None,
        receiver_type: Some("Svc"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(5),
    });
    match mismatched {
        CalleeResolution::NotFound | CalleeResolution::Ambiguous(_) => {}
        CalleeResolution::Resolved(k) => {
            panic!("arity mismatch must not resolve; got {k:?}")
        }
    }
}

#[test]
fn query_receiver_var_is_soft_tiebreak_not_primary() {
    // Adversarial case: a variable named "obj" exists and a class
    // happens to also be called "obj".  The old resolver used the
    // variable name as container_hint #1, which could mis-pick when
    // the qualified index had a coincidental hit.  The new resolver
    // treats `receiver_var` as a *soft* tie-break, it only fires
    // after same-namespace unique-leaf resolution fails.
    let mut gs = GlobalSummaries::new();
    let (k_same_ns, s_same_ns) = free_summary("src/app.js", "method", 1, 0xAA);
    let (k_other_class, s_other_class) = method_summary("src/other.js", "obj", "method", 1, 0xBB);
    gs.insert(k_same_ns.clone(), s_same_ns);
    gs.insert(k_other_class.clone(), s_other_class);

    // Caller lives in app.js → intra-file unique-leaf wins, regardless
    // of the variable-named `obj` coincidence in other.js.
    let intra = gs.resolve_callee(&CalleeQuery {
        name: "method",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.js",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: Some("obj"),
        arity: Some(1),
    });
    assert_eq!(intra, CalleeResolution::Resolved(k_same_ns));

    // Caller in a third file where no same-namespace match exists →
    // receiver_var tie-break fires and picks `obj::method`.
    let cross = gs.resolve_callee(&CalleeQuery {
        name: "method",
        caller_lang: Lang::Java,
        caller_namespace: "src/elsewhere.js",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: Some("obj"),
        arity: Some(1),
    });
    assert_eq!(cross, CalleeResolution::Resolved(k_other_class));
}

#[test]
fn query_qualifier_miss_refuses_to_guess_leaf() {
    // `namespace_qualifier = "Missing"` does not exist as a container.
    // We have two leaf candidates.  The resolver must NOT fall back
    // and pick one of them silently.  (It may return the leaf set
    // as Ambiguous for diagnostics.)
    let mut gs = GlobalSummaries::new();
    let (k_a, s_a) = free_summary("src/a.go", "run", 1, 0x1);
    let (k_b, s_b) = free_summary("src/b.go", "run", 1, 0x2);
    gs.insert(k_a.clone(), s_a);
    gs.insert(k_b.clone(), s_b);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "run",
        caller_lang: Lang::Java,
        caller_namespace: "src/caller.go",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: Some("Missing"),
        receiver_var: None,
        arity: Some(1),
    });
    match resolved {
        CalleeResolution::Ambiguous(cands) => {
            assert_eq!(cands.len(), 2);
            assert!(cands.contains(&k_a));
            assert!(cands.contains(&k_b));
        }
        CalleeResolution::Resolved(k) => {
            panic!("unresolved qualifier must not silently pick a leaf-only match; got {k:?}")
        }
        CalleeResolution::NotFound => panic!("candidates exist — should be Ambiguous not NotFound"),
    }
}

#[test]
fn legacy_wrapper_preserves_test_contract() {
    // The old `resolve_callee_key_with_container` entry point is kept as
    // a thin wrapper.  The pre-refactor tests
    // (`same_name_methods_on_different_classes_stay_distinct` and
    // `free_function_and_method_with_same_name_resolve_separately`)
    // already cover the happy paths; this test pins the *contract* of
    // the wrapper itself so we do not drift: a container hint is
    // treated as a non-authoritative namespace qualifier and falls
    // through to leaf lookup when it misses.
    let mut gs = GlobalSummaries::new();
    let (k_a, s_a) = free_summary("src/a.java", "only", 1, 0x1);
    gs.insert(k_a.clone(), s_a);

    // container_hint doesn't match any container, but the leaf name has
    // exactly one candidate, the wrapper should still resolve.
    let resolved = gs.resolve_callee_key_with_container(
        "only",
        Lang::Java,
        "src/caller.java",
        Some("NonExistent"),
        Some(1),
    );
    assert_eq!(resolved, CalleeResolution::Resolved(k_a));
}

// ── Adversarial: same-name identity collisions in the SAME file ─────────
//
// These tests target the most error-prone identity cases: two or more
// definitions that share `(lang, namespace, name, arity)` but differ in
// `container`.  The resolver must either resolve to the exact container
// target or refuse to guess, silently falling back to a same-leaf
// collision in a different container is a correctness bug, and mis-
// ordering the resolution steps can cause either false positives (wrong
// summary picked) or false negatives (missed flow because Ambiguous
// took a confident hint off the table).

#[test]
fn same_file_two_classes_same_method_typed_receiver_picks_exact() {
    // Two classes in the SAME file, both defining `run/1` with
    // incompatible security behaviour: `Safe::run` is a sanitizer-ish
    // passthrough (no sink bits) while `Unsafe::run` is a shell sink.
    // When the caller has a typed receiver (via type inference), the
    // resolver must pick the exact class, the wrong pick would either
    // miss the Unsafe sink or wrongly flag the Safe path.
    let mut gs = GlobalSummaries::new();
    let (k_safe, s_safe) = method_summary("src/app.java", "Safe", "run", 1, 0x00);
    let (k_unsafe, s_unsafe) =
        method_summary("src/app.java", "Unsafe", "run", 1, Cap::SHELL_ESCAPE.bits());
    gs.insert(k_safe.clone(), s_safe);
    gs.insert(k_unsafe.clone(), s_unsafe);

    let unsafe_call = gs.resolve_callee(&CalleeQuery {
        name: "run",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: Some("Unsafe"),
        namespace_qualifier: None,
        receiver_var: Some("u"),
        arity: Some(1),
    });
    assert_eq!(
        unsafe_call,
        CalleeResolution::Resolved(k_unsafe.clone()),
        "typed receiver `Unsafe` MUST land on Unsafe::run, not Safe::run"
    );

    let safe_call = gs.resolve_callee(&CalleeQuery {
        name: "run",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: Some("Safe"),
        namespace_qualifier: None,
        receiver_var: Some("s"),
        arity: Some(1),
    });
    assert_eq!(
        safe_call,
        CalleeResolution::Resolved(k_safe.clone()),
        "typed receiver `Safe` MUST land on Safe::run, not Unsafe::run"
    );

    // Sink-cap sanity: if the resolver ever silently swapped them the
    // cap mismatch would show up here.
    assert_eq!(gs.get(&k_safe).unwrap().sink_caps, 0x00);
    assert_eq!(
        gs.get(&k_unsafe).unwrap().sink_caps,
        Cap::SHELL_ESCAPE.bits()
    );
}

#[test]
fn same_file_two_classes_same_method_untyped_receiver_is_ambiguous_not_wrong() {
    // Same setup as above, but the caller only has a variable-name
    // receiver (no type facts).  `receiver_var` is a SOFT hint, and in
    // the common case `s`/`u` don't match any container.  The resolver
    // MUST refuse to pick one arbitrarily; returning `Safe::run` when
    // the call was `u.run(...)` would be a silent false negative of the
    // worst kind (wrong summary pickup).
    let mut gs = GlobalSummaries::new();
    let (k_safe, s_safe) = method_summary("src/app.java", "Safe", "run", 1, 0x00);
    let (k_unsafe, s_unsafe) =
        method_summary("src/app.java", "Unsafe", "run", 1, Cap::SHELL_ESCAPE.bits());
    gs.insert(k_safe.clone(), s_safe);
    gs.insert(k_unsafe.clone(), s_unsafe);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "run",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: Some("u"),
        arity: Some(1),
    });
    match resolved {
        CalleeResolution::Ambiguous(cands) => {
            assert!(cands.contains(&k_safe));
            assert!(cands.contains(&k_unsafe));
        }
        CalleeResolution::Resolved(k) => panic!(
            "same-file same-name two-class collision with only a soft `receiver_var` MUST NOT \
             pick a specific summary — got {k:?}"
        ),
        CalleeResolution::NotFound => {
            panic!("candidates exist in the same file — must be Ambiguous, not NotFound")
        }
    }
}

#[test]
fn same_file_free_function_and_method_bare_call_prefers_free_function() {
    // Classic "I wrote a top-level helper AND a method with the same
    // name in the same file" trap.  A bare `process()` call, no
    // receiver, no qualifier, caller outside any container, is
    // syntactically a FREE function call; the method cannot be invoked
    // this way.  The resolver MUST resolve to the free function, not
    // return Ambiguous.
    //
    // NOTE: this test was FAILING under the pre-fix resolver, which
    // returned Ambiguous because step 4's same-namespace narrowing
    // still saw two candidates and step 6 had no qualified hint to
    // tie-break on.
    let mut gs = GlobalSummaries::new();
    let (k_free, s_free) = free_summary("src/app.java", "process", 1, 0x0F);
    let (k_method, s_method) = method_summary("src/app.java", "Worker", "process", 1, 0xF0);
    gs.insert(k_free.clone(), s_free);
    gs.insert(k_method.clone(), s_method);

    // Caller is a top-level free function (caller_container = None).
    let bare = gs.resolve_callee(&CalleeQuery {
        name: "process",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: None,
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(
        bare,
        CalleeResolution::Resolved(k_free.clone()),
        "bare `process()` from a top-level caller must resolve to the FREE function \
         in the same file, not get lost in Ambiguous"
    );

    // Cap sanity: if we accidentally resolved to `Worker::process` the
    // sink caps would leak and downstream taint would flag the wrong
    // flow.  Pin the exact resolution, not just Resolved-vs-Ambiguous.
    if let CalleeResolution::Resolved(k) = bare {
        assert_eq!(gs.get(&k).unwrap().sink_caps, 0x0F);
    }
}

#[test]
fn same_file_method_calling_sibling_free_function_resolves_to_free() {
    // Variant of the previous test with the caller LIVING INSIDE a
    // class whose own container does NOT define `process`.  Bare
    // `process()` inside `Runner::kick()` must still resolve to the
    // file-local free function, not get lost in Ambiguous because the
    // caller_container hint (`Runner`) misses both candidates.
    let mut gs = GlobalSummaries::new();
    let (k_free, s_free) = free_summary("src/app.java", "process", 1, 0x0F);
    let (k_method, s_method) = method_summary("src/app.java", "Worker", "process", 1, 0xF0);
    // Runner::kick exists only so caller_container("Runner") is a real
    // container name in the global summaries.  It is NOT a candidate.
    let (k_kick, s_kick) = method_summary("src/app.java", "Runner", "kick", 0, 0x00);
    gs.insert(k_free.clone(), s_free);
    gs.insert(k_method.clone(), s_method);
    gs.insert(k_kick, s_kick);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "process",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: Some("Runner"),
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    match resolved {
        CalleeResolution::Resolved(k) => {
            assert_eq!(
                k, k_free,
                "bare `process()` inside Runner::kick must land on the free function; \
                 picking Worker::process would be wrong-summary pickup"
            );
        }
        // Ambiguous is also wrong: syntactically this CANNOT be
        // Worker::process (no receiver, no this in the caller's
        // container), so the resolver has enough information to pick
        // the free function.
        other => panic!(
            "bare `process()` from Runner::kick should resolve to the free function; got {other:?}"
        ),
    }
}

#[test]
fn same_file_method_calling_own_container_sibling_prefers_self_class() {
    // Inverse of the previous: caller is INSIDE `Worker::other()` and
    // calls bare `process()`.  Both a free `process` AND `Worker::process`
    // exist in the file.  The caller's own container resolution (step 3)
    // must prefer `Worker::process`, otherwise intra-class self calls
    // would get misresolved to a free function with possibly different
    // security behaviour.
    let mut gs = GlobalSummaries::new();
    let (k_free, s_free) = free_summary("src/app.java", "process", 1, 0x0F);
    let (k_method, s_method) = method_summary("src/app.java", "Worker", "process", 1, 0xF0);
    gs.insert(k_free.clone(), s_free);
    gs.insert(k_method.clone(), s_method);

    let resolved = gs.resolve_callee(&CalleeQuery {
        name: "process",
        caller_lang: Lang::Java,
        caller_namespace: "src/app.java",
        caller_container: Some("Worker"),
        receiver_type: None,
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(
        resolved,
        CalleeResolution::Resolved(k_method),
        "self-call from Worker::other() must resolve to Worker::process, not the free function"
    );
}

#[test]
fn same_file_nested_container_same_method_disambiguates_by_container() {
    // Two nested definitions: `Outer::foo/1` and `Outer::Inner::foo/1`
    // both live in the same file.  The fully qualified container names
    // must be distinct keys and the resolver must pick each one exactly
    // when the container hint is given.  A bug that stripped nested
    // container suffixes or used only the outermost name would collapse
    // them and mis-resolve.
    let mut gs = GlobalSummaries::new();
    let (k_outer, s_outer) = method_summary("src/nested.java", "Outer", "foo", 1, 0x01);
    let (k_inner, s_inner) = method_summary("src/nested.java", "Outer::Inner", "foo", 1, 0x02);
    gs.insert(k_outer.clone(), s_outer);
    gs.insert(k_inner.clone(), s_inner);

    // Exact qualified hint "Outer::Inner" must land on the inner one.
    let inner = gs.resolve_callee(&CalleeQuery {
        name: "foo",
        caller_lang: Lang::Java,
        caller_namespace: "src/nested.java",
        caller_container: None,
        receiver_type: Some("Outer::Inner"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(
        inner,
        CalleeResolution::Resolved(k_inner.clone()),
        "`Outer::Inner` receiver_type must pick the NESTED foo — picking `Outer::foo` would be \
         wrong-summary pickup driven by prefix collapse"
    );

    // Exact qualified hint "Outer" must land on the outer one, not the
    // nested one (nested container starts with "Outer::" but is not
    // equal to "Outer").
    let outer = gs.resolve_callee(&CalleeQuery {
        name: "foo",
        caller_lang: Lang::Java,
        caller_namespace: "src/nested.java",
        caller_container: None,
        receiver_type: Some("Outer"),
        namespace_qualifier: None,
        receiver_var: None,
        arity: Some(1),
    });
    assert_eq!(
        outer,
        CalleeResolution::Resolved(k_outer),
        "`Outer` receiver_type must pick only Outer::foo — not Outer::Inner::foo via prefix match"
    );

    // Exact cap pinning, guards against merge_summaries accidentally
    // unioning caps across the two nested keys.
    assert_eq!(gs.get(&k_inner).unwrap().sink_caps, 0x02);
}

#[test]
fn same_file_same_name_different_security_behaviour_no_cap_leak() {
    // Three `validate/1` entries in the same file: a sanitizer
    // passthrough (free function), an HTML-escape sanitizer in one
    // class, and a shell-exec sink in another class.  These must end
    // up as three distinct keys with their caps preserved exactly ,
    // no merge of sink caps into the sanitizer entry, no cross-leak
    // via `by_lang_name` fallback.
    let mut gs = GlobalSummaries::new();
    let (k_free, mut s_free) = free_summary("src/val.py", "validate", 1, 0x00);
    s_free.sanitizer_caps = Cap::all().bits();
    let (k_html, mut s_html) = method_summary("src/val.py", "HtmlGuard", "validate", 1, 0x00);
    s_html.sanitizer_caps = Cap::HTML_ESCAPE.bits();
    let (k_shell, s_shell) = method_summary(
        "src/val.py",
        "ShellRunner",
        "validate",
        1,
        Cap::SHELL_ESCAPE.bits(),
    );
    gs.insert(k_free.clone(), s_free);
    gs.insert(k_html.clone(), s_html);
    gs.insert(k_shell.clone(), s_shell);

    // Each key retrieved independently must yield exactly its own caps.
    assert_eq!(gs.get(&k_free).unwrap().sink_caps, 0x00);
    assert_eq!(gs.get(&k_free).unwrap().sanitizer_caps, Cap::all().bits());
    assert_eq!(gs.get(&k_html).unwrap().sink_caps, 0x00);
    assert_eq!(
        gs.get(&k_html).unwrap().sanitizer_caps,
        Cap::HTML_ESCAPE.bits()
    );
    assert_eq!(
        gs.get(&k_shell).unwrap().sink_caps,
        Cap::SHELL_ESCAPE.bits()
    );
    assert_eq!(gs.get(&k_shell).unwrap().sanitizer_caps, 0x00);

    // Each `receiver_type` hint must land on its OWN container.
    for (hint, expected) in [("HtmlGuard", &k_html), ("ShellRunner", &k_shell)] {
        let r = gs.resolve_callee(&CalleeQuery {
            name: "validate",
            caller_lang: Lang::Java,
            caller_namespace: "src/val.py",
            caller_container: None,
            receiver_type: Some(hint),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(
            r,
            CalleeResolution::Resolved(expected.clone()),
            "receiver_type `{hint}` must pick its own container's validate"
        );
    }
}

// ── Tightened-merge regression tests ────────────────────────────────────
// These guard the identity-collision split added to `insert`, `insert_ssa`,
// and `insert_body`.  Each scenario encodes an "underspecified identity"
// (typically `disambig: None` from legacy/interop/DB-loaded summaries) where
// the old code silently collapsed structurally distinct functions.

/// Build a minimal `FuncSummary` with `disambig: None`, mirrors the shape
/// produced by legacy JSON rows / interop configs that don't know byte
/// offsets.  `file_path` is left blank so namespace normalisation doesn't
/// separate the two otherwise-identical keys.
fn legacy_summary(
    file_path: &str,
    name: &str,
    param_count: usize,
    param_names: Vec<String>,
    kind: FuncKind,
    container: &str,
    sink: u16,
) -> FuncSummary {
    FuncSummary {
        name: name.into(),
        file_path: file_path.into(),
        lang: "java".into(),
        param_count,
        param_names,
        sink_caps: sink,
        container: container.into(),
        disambig: None,
        kind,
        ..Default::default()
    }
}

#[test]
fn insert_mismatched_module_path_does_not_silently_merge() {
    // Two Rust summaries with the same leaf key but different
    // `module_path` (e.g. produced by loading a stale DB alongside a
    // freshly-scanned file, or by two different scan_root anchors).
    // `module_path` is not part of `FuncKey` but identifies the defining
    // crate module; two distinct modules with the same file path relative
    // to different scan roots must stay separate.
    let mut gs = GlobalSummaries::new();
    let a = FuncSummary {
        name: "validate".into(),
        file_path: "src/lib.rs".into(),
        lang: "rust".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        sink_caps: Cap::SHELL_ESCAPE.bits(),
        disambig: None,
        module_path: Some("auth::token".into()),
        ..Default::default()
    };
    let b = FuncSummary {
        name: "validate".into(),
        file_path: "src/lib.rs".into(),
        lang: "rust".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        sink_caps: Cap::SQL_QUERY.bits(),
        disambig: None,
        module_path: Some("billing::invoice".into()),
        ..Default::default()
    };
    let k = a.func_key(None);
    assert_eq!(
        k,
        b.func_key(None),
        "pre-fix: both summaries would land on the same key"
    );

    gs.insert(k.clone(), a);
    gs.insert(k.clone(), b);

    let hits = gs.lookup_same_lang(Lang::Rust, "validate");
    assert_eq!(
        hits.len(),
        2,
        "different module_path summaries must stay distinct — got {hits:?}"
    );
    let auth = hits
        .iter()
        .find(|(_, s)| s.module_path.as_deref() == Some("auth::token"))
        .expect("auth::token summary preserved");
    let billing = hits
        .iter()
        .find(|(_, s)| s.module_path.as_deref() == Some("billing::invoice"))
        .expect("billing::invoice summary preserved");
    // Cross-contamination guard: the two crates must not have their
    // caps unioned, that's the observable failure mode of a silent
    // merge.
    assert_eq!(auth.1.sink_caps, Cap::SHELL_ESCAPE.bits());
    assert_eq!(billing.1.sink_caps, Cap::SQL_QUERY.bits());
    assert_eq!(auth.1.sink_caps & Cap::SQL_QUERY.bits(), 0);
    assert_eq!(billing.1.sink_caps & Cap::SHELL_ESCAPE.bits(), 0);
}

#[test]
fn insert_mismatched_kind_does_not_silently_merge() {
    // A free function and a method with the same name, arity, namespace,
    // and container ("" vs "") can't actually occur, but kind alone
    // mismatching does happen in interop configs where a getter is
    // described as a function.  Make sure the two end up distinct.
    let mut gs = GlobalSummaries::new();
    let f = legacy_summary(
        "src/a.java",
        "size",
        0,
        vec![],
        FuncKind::Function,
        "Widget",
        0,
    );
    let g = legacy_summary(
        "src/a.java",
        "size",
        0,
        vec![],
        FuncKind::Getter,
        "Widget",
        Cap::SHELL_ESCAPE.bits(),
    );
    gs.insert(f.func_key(None), f);
    gs.insert(g.func_key(None), g);

    // Two distinct keys in the same-lang index.
    let hits = gs.lookup_same_lang(Lang::Java, "size");
    assert_eq!(hits.len(), 2);
    // The getter's sink caps must not have been unioned into the
    // function, that would be a security-relevant leak.
    let func_hit = hits
        .iter()
        .find(|(k, _)| k.kind == FuncKind::Function)
        .expect("function summary kept separate");
    assert_eq!(
        func_hit.1.sink_caps, 0,
        "function's sink caps must not absorb the getter's SHELL_ESCAPE"
    );
}

#[test]
fn insert_mismatched_param_names_does_not_silently_merge() {
    // Two overloads in Java/C++ with the same arity but different
    // parameter types/names, a classic case where arity-only identity
    // collapses distinct functions.  Neither summary ships a disambig
    // because it was loaded from legacy JSON.
    let mut gs = GlobalSummaries::new();
    let a = legacy_summary(
        "src/app.java",
        "handle",
        1,
        vec!["msg".into()],
        FuncKind::Function,
        "",
        0,
    );
    let b = legacy_summary(
        "src/app.java",
        "handle",
        1,
        vec!["event".into()],
        FuncKind::Function,
        "",
        Cap::SHELL_ESCAPE.bits(),
    );
    gs.insert(a.func_key(None), a);
    gs.insert(b.func_key(None), b);

    let hits = gs.lookup_same_lang(Lang::Java, "handle");
    assert_eq!(
        hits.len(),
        2,
        "same name + arity + kind but different param_names → distinct functions"
    );
    // Exactly one carries the sink cap.
    let sinky: Vec<_> = hits
        .iter()
        .filter(|(_, s)| s.sink_caps == Cap::SHELL_ESCAPE.bits())
        .collect();
    assert_eq!(sinky.len(), 1);
}

#[test]
fn insert_synthetic_disambig_bit_set_only_for_collisions() {
    // A single legacy-style insert with `disambig: None` must NOT gain a
    // synthetic disambig, we only rekey to resolve collisions, never
    // speculatively.  This prevents downstream lookups keyed with
    // `disambig: None` from spuriously missing legitimately-single
    // summaries.
    let mut gs = GlobalSummaries::new();
    let sole = legacy_summary(
        "src/only.java",
        "alone",
        0,
        vec![],
        FuncKind::Function,
        "",
        Cap::SHELL_ESCAPE.bits(),
    );
    let key = sole.func_key(None);
    gs.insert(key.clone(), sole);
    assert_eq!(key.disambig, None);
    assert!(gs.get(&key).is_some(), "unique legacy insert keeps its key");
}

#[test]
fn insert_compatible_refinement_still_unions() {
    // Two summaries describing the same function (structurally identical
    // head, differing only on behaviour fields) must still union, the
    // tightened check doesn't regress the classic parallel-fold merge.
    let mut gs = GlobalSummaries::new();
    let a = FuncSummary {
        name: "f".into(),
        file_path: "src/x.rs".into(),
        lang: "rust".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        source_caps: Cap::ENV_VAR.bits(),
        container: "".into(),
        disambig: None,
        kind: FuncKind::Function,
        ..Default::default()
    };
    let b = FuncSummary {
        name: "f".into(),
        file_path: "src/x.rs".into(),
        lang: "rust".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        sink_caps: Cap::SHELL_ESCAPE.bits(),
        container: "".into(),
        disambig: None,
        kind: FuncKind::Function,
        ..Default::default()
    };
    let k = a.func_key(None);
    gs.insert(k.clone(), a);
    gs.insert(k.clone(), b);

    let merged = gs.get(&k).expect("compatible summaries still merge");
    assert_eq!(merged.source_caps, Cap::ENV_VAR.bits());
    assert_eq!(merged.sink_caps, Cap::SHELL_ESCAPE.bits());
    // Single entry, no accidental split for the compatible case.
    let hits = gs.lookup_same_lang(Lang::Rust, "f");
    assert_eq!(hits.len(), 1);
}

#[test]
fn insert_body_param_count_mismatch_rekeys() {
    // Two CalleeSsaBody instances arrive at the same FuncKey (both
    // `disambig: None`) but claim different `param_count`.  Silently
    // replacing would lose the first body and mis-route future cross-
    // file symex resolutions to the second.
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: Lang::Python,
        namespace: "mod.py".into(),
        name: "run".into(),
        arity: Some(2),
        ..Default::default()
    };
    gs.insert_body(key.clone(), make_callee_body(2, 2));
    // Incoming body with a different param_count, must not overwrite.
    gs.insert_body(key.clone(), make_callee_body(5, 4));

    // Invariant 1: the original body stays at the original key (not
    // silently replaced by the param_count=4 body).
    let head = gs.get_body(&key).expect("original 2-param body kept");
    assert_eq!(head.param_count, 2);

    // Invariant 2: the conflicting body is preserved under a synthetic
    // disambig, not dropped.  Reconstruct the expected synth disambig
    // using the same formula as `reconcile_body_key`.
    let mut found_conflicting = false;
    let base = (4u32).wrapping_mul(0x9E37_79B9);
    for probe in 0u32..1024 {
        let synth = base.wrapping_add(probe);
        let synth_key = FuncKey {
            disambig: Some(0x8000_0000 | (synth & 0x7FFF_FFFF)),
            ..key.clone()
        };
        if let Some(body) = gs.get_body(&synth_key)
            && body.param_count == 4
        {
            found_conflicting = true;
            break;
        }
    }
    assert!(
        found_conflicting,
        "the 4-param body must be preserved under a synthetic disambig key"
    );
}

#[test]
fn insert_ssa_arity_overflow_rekeys() {
    // Key claims arity 1, but the incoming SSA summary references
    // param index 3, structurally impossible for the same function.
    // The fix must split so the key arity invariant is preserved.
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: Lang::Python,
        namespace: "mod.py".into(),
        name: "f".into(),
        arity: Some(1),
        ..Default::default()
    };

    let legit = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        ..Default::default()
    };
    gs.insert_ssa(key.clone(), legit.clone());
    assert_eq!(
        gs.get_ssa(&key).unwrap().param_to_return,
        vec![(0, TaintTransform::Identity)]
    );

    // Bad-arity incoming summary, must not overwrite the legitimate one.
    let overflowing = SsaFuncSummary {
        param_to_return: vec![(3, TaintTransform::Identity)],
        param_to_sink: vec![(2, cap_sites(Cap::SQL_QUERY))],
        ..Default::default()
    };
    gs.insert_ssa(key.clone(), overflowing);

    // Original summary still exactly intact at the original key.
    let kept = gs.get_ssa(&key).expect("legit summary not overwritten");
    assert_eq!(kept.param_to_return, vec![(0, TaintTransform::Identity)]);
    assert!(kept.param_to_sink.is_empty());
}

/// Audit gap A.2.1.G1 reproducer: a summary whose only param-index
/// references come from synthetic SSA `Param` ops for external
/// captures (free identifiers, module imports, unresolved method
/// names) lands at the original key when no existing entry occupies
/// it.
///
/// This is the case `lower_to_ssa` produces for Java instance/static
/// methods that reference free identifiers (e.g. `f.close()` where
/// `close` is treated as an external capture, the synthetic Param 0
/// then leaks into `param_to_return`/`param_to_sink`).  Without the
/// audit-gap fix, `reconcile_ssa_summary_key` would synthesise a
/// disambig and the analysis's `summaries.get_ssa(caller_key)` lookup
/// (consuming `typed_call_receivers` at the FuncSummary-aligned key)
/// would miss.
#[test]
fn insert_ssa_arity_overflow_keeps_original_key_when_no_collision() {
    // Single-file fresh insert: no prior entry at `key` to protect, so
    // the synthetic-Param overflow is treated as the function's own
    // signal and lands at the original FuncKey.
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: Lang::Java,
        namespace: "Reader.java".into(),
        container: "Reader".into(),
        name: "read".into(),
        arity: Some(0),
        ..Default::default()
    };
    let summary = SsaFuncSummary {
        // Synthetic Param-0 for the external `close` identifier inside
        // the static `read()` body, `param_count == 0` per the source-
        // level signature.
        param_to_return: vec![(0, TaintTransform::Identity)],
        typed_call_receivers: vec![(1, "FileHandle".to_string())],
        ..Default::default()
    };
    gs.insert_ssa(key.clone(), summary.clone());

    let kept = gs
        .get_ssa(&key)
        .expect("Reader::read SSA must be reachable at the FuncSummary-aligned key");
    assert_eq!(kept.typed_call_receivers, summary.typed_call_receivers);
    // The synthetic Param-0 reference is preserved verbatim, pass-2
    // analysis still aligns it with the caller's implicit-uses
    // argument group at the same index.
    assert_eq!(kept.param_to_return, summary.param_to_return);
}

/// Companion to `insert_ssa_arity_overflow_keeps_original_key_when_no_collision`:
/// when both rounds of an iterative scan produce summaries whose
/// param-index references overflow the FuncKey arity (the same
/// synthetic-Param signal each round), the second-round insert must
/// land at the original key (last-writer-wins for the same function),
/// not split off into a synthetic disambig.
#[test]
fn insert_ssa_arity_overflow_iterative_rescan_stays_at_original_key() {
    let mut gs = GlobalSummaries::new();
    let key = FuncKey {
        lang: Lang::Java,
        namespace: "Reader.java".into(),
        container: "Reader".into(),
        name: "read".into(),
        arity: Some(0),
        ..Default::default()
    };
    let round1 = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        typed_call_receivers: vec![(1, "FileHandle".to_string())],
        ..Default::default()
    };
    gs.insert_ssa(key.clone(), round1);

    // Iteration 2 of the scan loop produces the same shape with
    // refined typed_call_receivers (e.g. a new constructor type
    // discovered cross-file).
    let round2 = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        typed_call_receivers: vec![(1, "FileHandle".to_string()), (2, "Cache".to_string())],
        ..Default::default()
    };
    gs.insert_ssa(key.clone(), round2.clone());

    let kept = gs
        .get_ssa(&key)
        .expect("iterative-rescan summary must stay at the original key");
    assert_eq!(kept.typed_call_receivers, round2.typed_call_receivers);
    assert_eq!(kept.param_to_return, round2.param_to_return);
}

// ── Primary sink-location attribution, SinkSite round-trips ────────────

#[test]
fn sink_site_serde_round_trip_solo() {
    let site = SinkSite {
        file_rel: "src/auth/token.rs".into(),
        line: 42,
        col: 9,
        snippet: "Command::new(\"sh\").arg(cmd).status()".into(),
        cap: Cap::CODE_EXEC | Cap::SHELL_ESCAPE,
    };
    let json = serde_json::to_string(&site).unwrap();
    let back: SinkSite = serde_json::from_str(&json).unwrap();
    assert_eq!(site, back);
}

#[test]
fn sink_site_serde_round_trip_cap_only_defaults() {
    // Extraction paths without tree access produce cap-only sites.  The
    // `skip_serializing_if` default attributes let the JSON drop empty
    // fields, and deserialisation must recover the same value.
    let site = SinkSite::cap_only(Cap::SQL_QUERY);
    let json = serde_json::to_string(&site).unwrap();
    // Zero/empty fields are dropped by `skip_serializing_if`.
    assert!(!json.contains("\"line\""));
    assert!(!json.contains("\"col\""));
    assert!(!json.contains("\"file_rel\""));
    assert!(!json.contains("\"snippet\""));
    let back: SinkSite = serde_json::from_str(&json).unwrap();
    assert_eq!(site, back);
}

#[test]
fn ssa_summary_serde_round_trip_with_sink_sites() {
    use smallvec::smallvec;
    let site_a = SinkSite {
        file_rel: "db.py".into(),
        line: 10,
        col: 4,
        snippet: "cursor.execute(sql)".into(),
        cap: Cap::SQL_QUERY,
    };
    let site_b = SinkSite {
        file_rel: "exec.py".into(),
        line: 33,
        col: 12,
        snippet: "subprocess.call(cmd, shell=True)".into(),
        cap: Cap::CODE_EXEC | Cap::SHELL_ESCAPE,
    };
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![
            (0, smallvec![site_a.clone(), site_b.clone()]),
            (1, smallvec![site_b.clone()]),
        ],
        source_caps: Cap::empty(),
        ..Default::default()
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);

    // Cap-derivation helpers still produce the expected unions.
    let caps = back.param_to_sink_caps();
    assert_eq!(caps.len(), 2);
    assert!(
        caps.iter()
            .any(|&(i, c)| i == 0 && c == (site_a.cap | site_b.cap))
    );
    assert!(caps.iter().any(|&(i, c)| i == 1 && c == site_b.cap));
    assert_eq!(back.total_param_sink_caps(), site_a.cap | site_b.cap);
}

#[test]
fn ssa_summary_deserialize_legacy_param_to_sink_missing_defaults_empty() {
    // Legacy summaries omitted the new field entirely.  The
    // `#[serde(default)]` attribute must carry the missing field through as
    // an empty vec rather than erroring out.
    let json = r#"{
        "param_to_return": [],
        "source_caps": 0
    }"#;
    let back: SsaFuncSummary = serde_json::from_str(json).unwrap();
    assert!(back.param_to_sink.is_empty());
    assert_eq!(back.total_param_sink_caps(), Cap::empty());
}

#[test]
fn func_summary_deserialize_legacy_param_to_sink_missing_defaults_empty() {
    let json = r#"{
        "name": "legacy",
        "file_path": "app.py",
        "lang": "python",
        "param_count": 1,
        "param_names": ["data"],
        "source_caps": 0,
        "sanitizer_caps": 0,
        "sink_caps": 0,
        "tainted_sink_params": []
    }"#;
    let back: FuncSummary = serde_json::from_str(json).unwrap();
    assert!(back.param_to_sink.is_empty());
}

#[test]
fn merge_unions_sink_sites_with_dedup() {
    use smallvec::smallvec;
    let key = FuncKey {
        lang: Lang::Python,
        namespace: "svc.py".into(),
        name: "run".into(),
        arity: Some(1),
        ..Default::default()
    };

    let site_a = SinkSite {
        file_rel: "svc.py".into(),
        line: 10,
        col: 1,
        snippet: "execute(sql)".into(),
        cap: Cap::SQL_QUERY,
    };
    let site_b = SinkSite {
        file_rel: "svc.py".into(),
        line: 20,
        col: 4,
        snippet: "os.system(cmd)".into(),
        cap: Cap::CODE_EXEC,
    };

    let mut left = FuncSummary {
        name: "run".into(),
        file_path: "svc.py".into(),
        lang: "python".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        param_to_sink: vec![(0, smallvec![site_a.clone()])],
        ..Default::default()
    };
    let right = FuncSummary {
        name: "run".into(),
        file_path: "svc.py".into(),
        lang: "python".into(),
        param_count: 1,
        param_names: vec!["x".into()],
        // Mix a duplicate of site_a (same file/line/col/cap) with a new site.
        param_to_sink: vec![(0, smallvec![site_a.clone(), site_b.clone()])],
        ..Default::default()
    };

    let mut gs = GlobalSummaries::new();
    gs.insert(key.clone(), left.clone());
    gs.insert(key.clone(), right);

    let merged = gs.get(&key).unwrap();
    assert_eq!(merged.param_to_sink.len(), 1);
    let (_, sites) = &merged.param_to_sink[0];
    // Exactly two distinct sites survive; the duplicate was deduped.
    assert_eq!(sites.len(), 2);
    assert!(sites.iter().any(|s| s.dedup_key() == site_a.dedup_key()));
    assert!(sites.iter().any(|s| s.dedup_key() == site_b.dedup_key()));

    // Idempotent: re-inserting the original left introduces no new sites.
    left.param_to_sink = vec![(0, smallvec![site_a.clone()])];
    gs.insert(key.clone(), left);
    let merged = gs.get(&key).unwrap();
    assert_eq!(merged.param_to_sink[0].1.len(), 2);
}

// ── Per-return-path decomposition ───────────────────────────────────────

use super::ssa_summary::{
    MAX_RETURN_PATHS, ReturnPathTransform, merge_return_paths, union_param_return_paths,
};

fn rpt(transform: TaintTransform, hash: u64, kt: u8, kf: u8) -> ReturnPathTransform {
    ReturnPathTransform {
        transform,
        path_predicate_hash: hash,
        known_true: kt,
        known_false: kf,
        abstract_contribution: None,
    }
}

#[test]
fn cf4_return_path_transform_serde_round_trip() {
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],
        receiver_to_return: None,
        receiver_to_sink: Cap::empty(),
        abstract_transfer: vec![],
        param_return_paths: vec![(
            0,
            smallvec![
                rpt(TaintTransform::Identity, 0x1234, 0b001, 0),
                rpt(
                    TaintTransform::StripBits(Cap::HTML_ESCAPE),
                    0x5678,
                    0,
                    0b010
                ),
            ],
        )],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
    // Missing-field backwards compat: older JSON without `param_return_paths`
    // deserialises cleanly with an empty vector.
    let legacy = r#"{"param_to_return":[],"source_caps":0}"#;
    let legacy_back: SsaFuncSummary = serde_json::from_str(legacy).unwrap();
    assert!(legacy_back.param_return_paths.is_empty());
}

#[test]
fn cf4_merge_return_paths_dedup_by_key() {
    let mut existing: SmallVec<[ReturnPathTransform; 2]> = SmallVec::new();
    let incoming = [
        rpt(TaintTransform::Identity, 1, 0, 0),
        rpt(TaintTransform::StripBits(Cap::HTML_ESCAPE), 2, 0, 0),
        rpt(TaintTransform::Identity, 1, 0, 0), // dup of first
    ];
    merge_return_paths(&mut existing, &incoming);
    assert_eq!(existing.len(), 2, "duplicate path hash+transform collapsed");
    assert!(
        existing
            .iter()
            .any(|e| matches!(e.transform, TaintTransform::Identity) && e.path_predicate_hash == 1)
    );
    assert!(existing.iter().any(
        |e| matches!(&e.transform, TaintTransform::StripBits(b) if *b == Cap::HTML_ESCAPE)
            && e.path_predicate_hash == 2
    ));
}

#[test]
fn cf4_merge_return_paths_caps_at_max() {
    let mut existing: SmallVec<[ReturnPathTransform; 2]> = SmallVec::new();
    let many: Vec<ReturnPathTransform> = (0..(MAX_RETURN_PATHS as u64 + 3))
        .map(|i| rpt(TaintTransform::StripBits(Cap::HTML_ESCAPE), i + 10, 0, 0))
        .collect();
    merge_return_paths(&mut existing, &many);
    assert_eq!(
        existing.len(),
        1,
        "overflow collapses to a single Top-predicate entry"
    );
    // Joined entry has no predicate gate (hash=0) and conservatively takes
    // the intersection of all strip bits, which here is HTML_ESCAPE.
    let joined = &existing[0];
    assert_eq!(joined.path_predicate_hash, 0);
    assert!(matches!(
        &joined.transform,
        TaintTransform::StripBits(b) if *b == Cap::HTML_ESCAPE
    ));
}

#[test]
fn cf4_merge_return_paths_overflow_with_mixed_kinds() {
    let mut existing: SmallVec<[ReturnPathTransform; 2]> = SmallVec::new();
    let mut many: Vec<ReturnPathTransform> = (0..(MAX_RETURN_PATHS as u64 + 1))
        .map(|i| rpt(TaintTransform::StripBits(Cap::HTML_ESCAPE), i + 10, 0, 0))
        .collect();
    // One identity path forces the join to degrade to Identity (nothing
    // stripped on every path).
    many.push(rpt(TaintTransform::Identity, 99, 0, 0));
    merge_return_paths(&mut existing, &many);
    assert_eq!(existing.len(), 1);
    assert!(matches!(existing[0].transform, TaintTransform::Identity));
}

#[test]
fn cf4_merge_return_paths_joins_abstract_contribution_on_collision() {
    use crate::abstract_interp::{AbstractValue, BitFact, IntervalFact, PathFact, StringFact};

    let av_a = AbstractValue {
        interval: IntervalFact::exact(0),
        string: StringFact::top(),
        bits: BitFact::top(),
        path: PathFact::top(),
    };
    let av_b = AbstractValue {
        interval: IntervalFact::exact(10),
        string: StringFact::top(),
        bits: BitFact::top(),
        path: PathFact::top(),
    };

    let mut first = rpt(TaintTransform::Identity, 42, 0, 0);
    first.abstract_contribution = Some(av_a.clone());
    let mut second = rpt(TaintTransform::Identity, 42, 0, 0);
    second.abstract_contribution = Some(av_b.clone());

    let mut existing: SmallVec<[ReturnPathTransform; 2]> = SmallVec::new();
    merge_return_paths(&mut existing, &[first]);
    merge_return_paths(&mut existing, &[second]);
    assert_eq!(existing.len(), 1, "same key, merged");
    // The abstract_contribution is the join of the two inputs.
    let joined = existing[0].abstract_contribution.as_ref().unwrap();
    let expected = av_a.join(&av_b);
    assert_eq!(joined, &expected);
}

#[test]
fn cf4_union_param_return_paths_by_index() {
    let mut existing: Vec<(usize, SmallVec<[ReturnPathTransform; 2]>)> =
        vec![(0, smallvec![rpt(TaintTransform::Identity, 1, 0, 0)])];
    let incoming: Vec<(usize, SmallVec<[ReturnPathTransform; 2]>)> = vec![
        (
            0,
            smallvec![rpt(TaintTransform::StripBits(Cap::HTML_ESCAPE), 2, 0, 0)],
        ),
        (1, smallvec![rpt(TaintTransform::Identity, 3, 0, 0)]),
    ];
    union_param_return_paths(&mut existing, &incoming);
    assert_eq!(existing.len(), 2);
    let (_, p0) = existing.iter().find(|(i, _)| *i == 0).unwrap();
    assert_eq!(p0.len(), 2, "per-param merge preserves both predicates");
    let (_, p1) = existing.iter().find(|(i, _)| *i == 1).unwrap();
    assert_eq!(p1.len(), 1);
}

#[test]
fn cf4_ssa_summary_fits_arity_keeps_out_of_range_path_idx_at_original_key() {
    // A path whose param index exceeds the key's arity is treated as a
    // synthetic external-capture artefact (audit gap A.2.1.G1, see
    // `project_typed_callgraph_audit_gap_ssa_disambig.md`).  When no
    // existing entry sits at the key, `insert_ssa` keeps the (untrimmed)
    // summary at the original key so the SSA FuncKey stays aligned with
    // the matching FuncSummary FuncKey, the analysis's
    // `summaries.get_ssa(caller_key)` lookup (consuming
    // `typed_call_receivers`) depends on this alignment.
    let bad = SsaFuncSummary {
        param_return_paths: vec![(5, smallvec![rpt(TaintTransform::Identity, 1, 0, 0)])],
        ..Default::default()
    };
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "test.rs".into(),
        name: "helper".into(),
        arity: Some(2), // too small for idx 5, synthetic-Param marker
        ..Default::default()
    };
    let mut gs = GlobalSummaries::new();
    gs.insert_ssa(key.clone(), bad);
    let kept = gs
        .get_ssa(&key)
        .expect("synthetic-Param summary inserted at original key");
    assert_eq!(kept.param_return_paths.len(), 1);
    assert_eq!(kept.param_return_paths[0].0, 5);
}

// ── Parameter-granularity points-to summary ─────────────────────────────

#[test]
fn cf6_ssa_summary_serde_round_trip_with_points_to() {
    use crate::summary::points_to::{AliasKind, AliasPosition, PointsToSummary};

    let mut pts = PointsToSummary::empty();
    pts.insert(
        AliasPosition::Param(0),
        AliasPosition::Param(1),
        AliasKind::MayAlias,
    );
    pts.insert(
        AliasPosition::Param(0),
        AliasPosition::Return,
        AliasKind::MayAlias,
    );

    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        points_to: pts.clone(),
        ..Default::default()
    };
    let json = serde_json::to_string(&summary).unwrap();
    let back: SsaFuncSummary = serde_json::from_str(&json).unwrap();
    assert_eq!(summary, back);
    assert_eq!(back.points_to, pts);
}

#[test]
fn cf6_ssa_summary_legacy_json_without_points_to_deserialises() {
    // Older on-disk JSON predates points-to tracking.  The serde(default) on
    // `points_to` must let those rows load cleanly with an empty
    // alias graph.
    let legacy = r#"{
        "param_to_return": [[0, "Identity"]],
        "source_caps": 0,
        "param_to_sink": []
    }"#;
    let back: SsaFuncSummary = serde_json::from_str(legacy).unwrap();
    assert!(back.points_to.edges.is_empty());
    assert!(!back.points_to.overflow);
}

#[test]
fn cf6_ssa_summary_fits_arity_keeps_out_of_range_points_to_idx_at_original_key() {
    // Same arity-overflow handling as `cf4_ssa_summary_fits_arity_*`
    // for the points-to channel: when the summary references a
    // synthetic-Param index beyond `key.arity` and no existing entry
    // occupies the key, `insert_ssa` preserves the FuncKey-aligned
    // identity by inserting at the original key (audit gap A.2.1.G1).
    use crate::summary::points_to::{AliasKind, AliasPosition, PointsToSummary};
    let mut pts = PointsToSummary::empty();
    pts.insert(
        AliasPosition::Param(7),
        AliasPosition::Return,
        AliasKind::MayAlias,
    );
    let bad = SsaFuncSummary {
        points_to: pts,
        ..Default::default()
    };
    let key = FuncKey {
        lang: Lang::Rust,
        namespace: "test.rs".into(),
        name: "helper".into(),
        arity: Some(2),
        ..Default::default()
    };
    let mut gs = GlobalSummaries::new();
    gs.insert_ssa(key.clone(), bad);
    let kept = gs
        .get_ssa(&key)
        .expect("synthetic-Param points_to summary inserted at original key");
    assert_eq!(kept.points_to.max_param_index(), Some(7));
}

/// two `findById`
/// definitions on different containers must remain structurally
/// disjoint after [`merge_summaries`], no cap union may leak
/// across them.  The FuncKey identity model already keys on
/// `(lang, namespace, container, name, arity, ...)` so this is
/// supposed to be true today; the test pins it down so a future
/// refactor can't silently widen the merge granularity.
///
/// Concretely: `Repository::findById` is parameterised (no
/// `SQL_QUERY` sink cap), `UnsafeCache::findById` runs a string-
/// concatenated query (carries `Cap::SQL_QUERY`).  After merge,
/// each FuncKey must own only its own caps, Repository must NOT
/// inherit Cache's `SQL_QUERY` bit.
#[test]
fn cross_file_devirt_does_not_union_unrelated_findbyids() {
    use crate::labels::Cap;
    use crate::symbol::FuncKey;

    fn method_summary(name: &str, container: &str, file: &str, sink_caps: u16) -> FuncSummary {
        FuncSummary {
            name: name.into(),
            file_path: file.into(),
            lang: "rust".into(),
            param_count: 1,
            param_names: vec!["id".into()],
            source_caps: 0,
            sanitizer_caps: 0,
            sink_caps,
            propagating_params: vec![],
            propagates_taint: false,
            tainted_sink_params: if sink_caps != 0 { vec![0] } else { vec![] },
            callees: vec![],
            container: container.into(),
            ..Default::default()
        }
    }

    let safe_repo = method_summary("findById", "Repository", "src/repo.rs", 0);
    let unsafe_cache = method_summary(
        "findById",
        "UnsafeCache",
        "src/cache.rs",
        Cap::SQL_QUERY.bits(),
    );

    let gs = merge_summaries(vec![safe_repo, unsafe_cache], None);

    // Two distinct keys must coexist, no merge collision.
    let repo_key = FuncKey {
        lang: Lang::Rust,
        namespace: "src/repo.rs".into(),
        container: "Repository".into(),
        name: "findById".into(),
        arity: Some(1),
        ..Default::default()
    };
    let cache_key = FuncKey {
        lang: Lang::Rust,
        namespace: "src/cache.rs".into(),
        container: "UnsafeCache".into(),
        name: "findById".into(),
        arity: Some(1),
        ..Default::default()
    };

    let repo_sum = gs.get(&repo_key).expect("Repository::findById missing");
    let cache_sum = gs.get(&cache_key).expect("UnsafeCache::findById missing");

    // Sink caps stay on their own owner, the whole point of
    // devirtualisation.  Repository must not have inherited the
    // SQL_QUERY bit from UnsafeCache.
    assert_eq!(
        repo_sum.sink_caps, 0,
        "Repository::findById inherited a sink cap from UnsafeCache::findById — \
         the per-FuncKey identity model has been broken (sink_caps bits = {:#x})",
        repo_sum.sink_caps,
    );
    assert_eq!(
        cache_sum.sink_caps,
        Cap::SQL_QUERY.bits(),
        "UnsafeCache::findById lost its own sink cap during merge"
    );
    // Same invariant on tainted_sink_params, must not bleed across.
    assert!(
        repo_sum.tainted_sink_params.is_empty(),
        "Repository::findById inherited tainted_sink_params from UnsafeCache: {:?}",
        repo_sum.tainted_sink_params,
    );
    assert_eq!(cache_sum.tainted_sink_params, vec![0]);
}

// ── the analysis ────────────────────
//
// `GlobalSummaries::resolve_callee_widened` is the runtime counterpart of
// the call-graph builder's `TypeHierarchyIndex::resolve_with_hierarchy`.
// These tests pin the contract that *every* concrete implementer is
// reachable when the receiver type is statically a super-class / trait /
// interface, with the explicit fall-throughs that preserve today's
// behaviour when no fan-out applies.
mod hierarchy_widened_tests {
    use super::*;

    /// Build a minimal `(FuncKey, FuncSummary)` for a method on the
    /// given container with optional `hierarchy_edges` carried through.
    fn java_method(
        namespace: &str,
        container: &str,
        name: &str,
        arity: usize,
        sink_bits: u16,
        hierarchy_edges: Vec<(String, String)>,
    ) -> (FuncKey, FuncSummary) {
        let (key, mut summary) = fs_with(
            namespace,
            container,
            name,
            arity,
            FuncKind::Method,
            Some((namespace.len() + container.len() + name.len()) as u32),
            sink_bits,
        );
        summary.hierarchy_edges = hierarchy_edges;
        (key, summary)
    }

    /// A1, no hierarchy installed.  Widening collapses to today's
    /// single-result behaviour: one key in / one key out.
    #[test]
    fn widened_without_hierarchy_returns_single_resolved() {
        let mut gs = GlobalSummaries::new();
        let (k, s) = java_method("src/http.java", "HttpClient", "send", 1, 0x01, vec![]);
        gs.insert(k.clone(), s);

        // Hierarchy is intentionally NOT installed.
        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "send",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("HttpClient"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(widened, vec![k]);
    }

    /// A2, hierarchy installed but the receiver type has no recorded
    /// sub-types.  Falls through to today's single-result behaviour.
    #[test]
    fn widened_no_subtypes_returns_single() {
        let mut gs = GlobalSummaries::new();
        let (k, s) = java_method("src/http.java", "HttpClient", "send", 1, 0x01, vec![]);
        gs.insert(k.clone(), s);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "send",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("HttpClient"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(widened, vec![k]);
    }

    /// A3, hierarchy with one sub-type implementer.  Widening returns
    /// both the direct receiver match and the sub-type's match.
    #[test]
    fn widened_one_subtype_returns_two_keys() {
        let mut gs = GlobalSummaries::new();
        // Carrier: ILogger -> ConsoleLogger edge.
        let (k_iface, s_iface) = java_method(
            "src/logger.java",
            "ILogger",
            "log",
            1,
            0x00,
            vec![("ConsoleLogger".to_string(), "ILogger".to_string())],
        );
        let (k_impl, s_impl) =
            java_method("src/logger.java", "ConsoleLogger", "log", 1, 0x01, vec![]);
        gs.insert(k_iface.clone(), s_iface);
        gs.insert(k_impl.clone(), s_impl);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "log",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("ILogger"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(
            widened.len(),
            2,
            "expected ILogger + ConsoleLogger fan-out, got {widened:?}"
        );
        assert!(widened.contains(&k_iface));
        assert!(widened.contains(&k_impl));
    }

    /// A4, hierarchy with multiple sub-types: every implementer's
    /// matching method is in the result, deduplicated.
    #[test]
    fn widened_multiple_subtypes_returns_all() {
        let mut gs = GlobalSummaries::new();
        // Three impls + one interface.  The interface itself has no
        // body so we omit a method on it (that is the more common
        // shape, a pure interface plus concrete classes).
        let edges = vec![
            ("FileLogger".to_string(), "ILogger".to_string()),
            ("NetLogger".to_string(), "ILogger".to_string()),
            ("StdLogger".to_string(), "ILogger".to_string()),
        ];
        let (k_file, s_file) = java_method(
            "src/file_logger.java",
            "FileLogger",
            "log",
            1,
            0x01,
            edges.clone(),
        );
        let (k_net, s_net) =
            java_method("src/net_logger.java", "NetLogger", "log", 1, 0x02, vec![]);
        let (k_std, s_std) =
            java_method("src/std_logger.java", "StdLogger", "log", 1, 0x04, vec![]);
        gs.insert(k_file.clone(), s_file);
        gs.insert(k_net.clone(), s_net);
        gs.insert(k_std.clone(), s_std);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "log",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("ILogger"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(widened.len(), 3, "expected three impls, got {widened:?}");
        assert!(widened.contains(&k_file));
        assert!(widened.contains(&k_net));
        assert!(widened.contains(&k_std));
    }

    /// A5, the arity filter must apply across the whole fan-out, not
    /// just the direct-receiver leg.  An implementer with a different
    /// arity must not leak into the result.
    #[test]
    fn widened_arity_filter_applies_across_fanout() {
        let mut gs = GlobalSummaries::new();
        let edges = vec![
            ("OneArg".to_string(), "IBase".to_string()),
            ("TwoArg".to_string(), "IBase".to_string()),
        ];
        let (k_one, s_one) = java_method("src/one.java", "OneArg", "do_it", 1, 0x01, edges.clone());
        let (k_two, s_two) = java_method("src/two.java", "TwoArg", "do_it", 2, 0x02, vec![]);
        gs.insert(k_one.clone(), s_one);
        gs.insert(k_two.clone(), s_two);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "do_it",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("IBase"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(1),
        });
        assert_eq!(widened, vec![k_one], "arity-2 impl must be filtered out");
    }

    /// A6, fan-out is bounded at `MAX_HIERARCHY_FANOUT`.  Build a
    /// hierarchy with more impls than the cap allows and assert the
    /// result is exactly capped (and that early impls are preserved
    ///, the cap drops the *tail*, not the head).
    #[test]
    fn widened_caps_at_max_hierarchy_fanout() {
        let cap = GlobalSummaries::MAX_HIERARCHY_FANOUT;
        let mut gs = GlobalSummaries::new();

        // Build cap+3 impls so we can assert the tail truncates and a
        // deterministic prefix remains.
        let extra = 3;
        let total = cap + extra;
        let edges: Vec<(String, String)> = (0..total)
            .map(|i| (format!("Impl{i:02}"), "IBase".to_string()))
            .collect();

        // Carrier, first impl carries every edge so the index is
        // populated in one shot.
        let (k0, s0) = java_method("src/impl00.java", "Impl00", "run", 0, 0x01, edges);
        gs.insert(k0.clone(), s0);
        for i in 1..total {
            let (k, s) = java_method(
                &format!("src/impl{i:02}.java"),
                &format!("Impl{i:02}"),
                "run",
                0,
                0x01,
                vec![],
            );
            gs.insert(k, s);
        }
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "run",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("IBase"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(
            widened.len(),
            cap,
            "fan-out must cap at MAX_HIERARCHY_FANOUT={cap}, got {}",
            widened.len()
        );
    }

    /// A7, when hierarchy widening produces no candidates AND the
    /// receiver_type lookup is authoritative (Step 1), the secondary
    /// fall-through goes through `resolve_callee` which returns
    /// Ambiguous/NotFound rather than silently picking an unrelated
    /// leaf, exactly the "subset of today's targets, never a
    /// superset" rule.  Test asserts the empty result is preserved.
    #[test]
    fn widened_empty_does_not_silently_pick_unrelated_leaf() {
        let mut gs = GlobalSummaries::new();
        // Edge: IUnused has a sub Used, but neither declares
        // `something`.  An unrelated free function `something` exists
        // in the same namespace, under today's authoritative
        // receiver_type rules, that function MUST NOT be picked when
        // the call is annotated with receiver_type "IUnused".
        let edges = vec![("Used".to_string(), "IUnused".to_string())];
        let (k_carrier, s_carrier) =
            java_method("src/util.java", "Used", "carrier", 0, 0x00, edges);
        let (k_free, s_free) = free_summary("src/app.java", "something", 0, 0x01);
        gs.insert(k_carrier, s_carrier);
        gs.insert(k_free, s_free);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "something",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("IUnused"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert!(
            widened.is_empty(),
            "receiver_type IUnused with no matching method must NOT silently \
             pick an unrelated free function — got {widened:?}"
        );
    }

    /// A7b, when hierarchy widening produces nothing AND today's
    /// `resolve_callee` *does* resolve (no receiver_type, just bare
    /// leaf or qualifier hint), the fallback returns the single key.
    /// This pins the secondary-fallback contract on the path where it
    /// actually matters (no authoritative receiver_type).
    #[test]
    fn widened_falls_through_when_resolve_callee_resolves() {
        let mut gs = GlobalSummaries::new();
        let (k_free, s_free) = free_summary("src/app.java", "helper", 0, 0x01);
        gs.insert(k_free.clone(), s_free);
        gs.install_hierarchy();

        // No receiver_type → first branch of `resolve_callee_widened`
        // is the single-result fallback path.
        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "helper",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: None,
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(widened, vec![k_free]);
    }

    /// A8, receiver_type is None → no widening; behaves identically
    /// to `resolve_callee` (single-result wrap).
    #[test]
    fn widened_no_receiver_type_collapses_to_resolve_callee() {
        let mut gs = GlobalSummaries::new();
        let (k_free, s_free) = free_summary("src/app.java", "helper", 0, 0x01);
        gs.insert(k_free.clone(), s_free);
        gs.install_hierarchy();

        let widened = gs.resolve_callee_widened(&CalleeQuery {
            name: "helper",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: None,
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(widened, vec![k_free]);
    }

    /// A9, `merge()` must invalidate the cached hierarchy index so a
    /// post-merge call to `resolve_callee_widened` doesn't look up a
    /// stale view.  Since `install_hierarchy` is required after merges,
    /// the test asserts: post-merge, before reinstall, fan-out must
    /// fall through to single-result behaviour.
    #[test]
    fn merge_invalidates_hierarchy_cache() {
        let mut gs_a = GlobalSummaries::new();
        let edges = vec![("Sub".to_string(), "Super".to_string())];
        let (k_super, s_super) = java_method("src/super.java", "Super", "m", 0, 0x00, edges);
        let (k_sub, s_sub) = java_method("src/sub.java", "Sub", "m", 0, 0x01, vec![]);
        gs_a.insert(k_super.clone(), s_super);
        gs_a.insert(k_sub.clone(), s_sub);
        gs_a.install_hierarchy();
        // Before merge: fan-out works.
        let pre_merge = gs_a.resolve_callee_widened(&CalleeQuery {
            name: "m",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("Super"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(pre_merge.len(), 2);

        // Merge in an empty `gs_b`, should invalidate the cached
        // hierarchy.
        gs_a.merge(GlobalSummaries::new());
        assert!(
            gs_a.hierarchy().is_none(),
            "merge() must clear the cached hierarchy"
        );

        // After merge, before reinstall: the resolver must fall back
        // to single-result behaviour (no fan-out).
        let post_merge_no_install = gs_a.resolve_callee_widened(&CalleeQuery {
            name: "m",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("Super"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(post_merge_no_install.len(), 1);
        assert_eq!(post_merge_no_install[0], k_super);

        // After reinstall: fan-out is restored.
        gs_a.install_hierarchy();
        let post_merge_reinstalled = gs_a.resolve_callee_widened(&CalleeQuery {
            name: "m",
            caller_lang: Lang::Java,
            caller_namespace: "src/app.java",
            caller_container: None,
            receiver_type: Some("Super"),
            namespace_qualifier: None,
            receiver_var: None,
            arity: Some(0),
        });
        assert_eq!(post_merge_reinstalled.len(), 2);
        assert!(post_merge_reinstalled.contains(&k_super));
        assert!(post_merge_reinstalled.contains(&k_sub));
    }
}