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
// ── populate_node_meta + CrossFileNodeMeta tests ─────────────────────────

#[cfg(test)]
mod cross_file_tests {
    use super::super::*;
    use crate::cfg::{AstMeta, BinOp, CallMeta, EdgeKind, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::DataLabel;

    use petgraph::prelude::*;
    use smallvec::smallvec;

    fn make_test_cfg() -> crate::cfg::Cfg {
        let mut cfg = Graph::new();
        let n0 = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (0, 10),
                ..Default::default()
            },
            taint: TaintMeta {
                labels: smallvec![DataLabel::Source(crate::labels::Cap::all())],
                defines: Some("x".into()),
                ..Default::default()
            },
            call: CallMeta::default(),
            bin_op: Some(BinOp::Add),
            ..Default::default()
        });
        let n1 = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (10, 20),
                ..Default::default()
            },
            taint: TaintMeta {
                defines: Some("y".into()),
                ..Default::default()
            },
            ..Default::default()
        });
        cfg.add_edge(n0, n1, EdgeKind::Seq);
        cfg
    }

    fn make_body_referencing_nodes(n0: NodeIndex, n1: NodeIndex) -> CalleeSsaBody {
        CalleeSsaBody {
            ssa: SsaBody {
                blocks: vec![SsaBlock {
                    id: BlockId(0),
                    phis: vec![],
                    body: vec![
                        SsaInst {
                            value: SsaValue(0),
                            op: SsaOp::Source,
                            cfg_node: n0,
                            var_name: Some("x".into()),
                            span: (0, 5),
                        },
                        SsaInst {
                            value: SsaValue(1),
                            op: SsaOp::Assign(smallvec![SsaValue(0)]),
                            cfg_node: n1,
                            var_name: Some("y".into()),
                            span: (5, 10),
                        },
                    ],
                    terminator: Terminator::Return(Some(SsaValue(1))),
                    preds: smallvec![],
                    succs: smallvec![],
                }],
                entry: BlockId(0),
                value_defs: vec![
                    ValueDef {
                        var_name: Some("x".into()),
                        cfg_node: n0,
                        block: BlockId(0),
                    },
                    ValueDef {
                        var_name: Some("y".into()),
                        cfg_node: n1,
                        block: BlockId(0),
                    },
                ],
                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: 0,
            node_meta: std::collections::HashMap::new(),
            body_graph: None,
        }
    }

    #[test]
    fn populate_node_meta_extracts_bin_op_and_labels() {
        let cfg = make_test_cfg();
        let n0 = NodeIndex::new(0);
        let n1 = NodeIndex::new(1);
        let mut body = make_body_referencing_nodes(n0, n1);

        assert!(body.node_meta.is_empty());
        let ok = populate_node_meta(&mut body, &cfg);
        assert!(ok, "should succeed for valid nodes");

        assert_eq!(body.node_meta.len(), 2);

        // Node 0: has bin_op=Add and Source label
        let meta0 = &body.node_meta[&0];
        assert_eq!(meta0.info.bin_op, Some(BinOp::Add));
        assert_eq!(meta0.info.taint.labels.len(), 1);
        assert!(matches!(meta0.info.taint.labels[0], DataLabel::Source(_)));
        // Full NodeInfo round-trip: span, defines, and kind are preserved.
        assert_eq!(meta0.info.ast.span, (0, 10));
        assert_eq!(meta0.info.taint.defines.as_deref(), Some("x"));

        // Node 1: no bin_op, no labels
        let meta1 = &body.node_meta[&1];
        assert_eq!(meta1.info.bin_op, None);
        assert!(meta1.info.taint.labels.is_empty());
        assert_eq!(meta1.info.taint.defines.as_deref(), Some("y"));
    }

    #[test]
    fn populate_node_meta_fails_on_invalid_node() {
        let cfg = make_test_cfg(); // only has 2 nodes (0, 1)
        let bad_node = NodeIndex::new(999);
        let n0 = NodeIndex::new(0);

        let mut body = make_body_referencing_nodes(n0, bad_node);

        let ok = populate_node_meta(&mut body, &cfg);
        assert!(!ok, "should fail for out-of-bounds NodeIndex");
    }

    #[test]
    fn populate_node_meta_idempotent() {
        let cfg = make_test_cfg();
        let n0 = NodeIndex::new(0);
        let n1 = NodeIndex::new(1);
        let mut body = make_body_referencing_nodes(n0, n1);

        populate_node_meta(&mut body, &cfg);
        let first_pass = body.node_meta.clone();

        populate_node_meta(&mut body, &cfg);
        assert_eq!(
            body.node_meta, first_pass,
            "second call should be idempotent"
        );
    }

    #[test]
    fn cross_file_node_meta_default() {
        let meta = CrossFileNodeMeta::default();
        assert_eq!(meta.info.bin_op, None);
        assert!(meta.info.taint.labels.is_empty());
    }

    // ── rebuild_body_graph ──────────────────────────────────────────────

    #[test]
    fn rebuild_body_graph_synthesizes_proxy_cfg() {
        let cfg = make_test_cfg();
        let n0 = NodeIndex::new(0);
        let n1 = NodeIndex::new(1);
        let mut body = make_body_referencing_nodes(n0, n1);
        populate_node_meta(&mut body, &cfg);
        // Simulate the indexed-scan load: body_graph is skipped by serde.
        body.body_graph = None;

        let rebuilt = rebuild_body_graph(&mut body);
        assert!(rebuilt, "rebuild should install a fresh graph");
        let graph = body.body_graph.as_ref().expect("graph rebuilt");
        assert_eq!(graph.node_count(), 2);
        let info0 = &graph[n0];
        assert_eq!(info0.bin_op, Some(BinOp::Add));
        assert_eq!(info0.taint.labels.len(), 1);
        assert!(matches!(info0.taint.labels[0], DataLabel::Source(_)));
    }

    #[test]
    fn rebuild_body_graph_is_idempotent() {
        let cfg = make_test_cfg();
        let n0 = NodeIndex::new(0);
        let n1 = NodeIndex::new(1);
        let mut body = make_body_referencing_nodes(n0, n1);
        populate_node_meta(&mut body, &cfg);
        body.body_graph = None;

        assert!(rebuild_body_graph(&mut body));
        assert!(!rebuild_body_graph(&mut body), "second call must no-op");
    }

    #[test]
    fn rebuild_body_graph_noop_without_meta() {
        // Intra-file body: node_meta empty, body_graph comes from pass 1.
        let n0 = NodeIndex::new(0);
        let n1 = NodeIndex::new(1);
        let mut body = make_body_referencing_nodes(n0, n1);
        assert!(body.node_meta.is_empty());
        assert!(body.body_graph.is_none());
        assert!(!rebuild_body_graph(&mut body));
        assert!(body.body_graph.is_none());
    }
}

#[cfg(test)]
mod inline_cache_epoch_tests {
    //! Hooks for cross-file SCC joint fixed-point iteration.
    //!
    //! These do not exercise the full inline pipeline, they lock down the
    //! semantic contract of [`inline_cache_clear_epoch`] and
    //! [`inline_cache_fingerprint`] so the SCC orchestrator can rely on:
    //!
    //! * `clear_epoch` drops every entry, leaving the cache empty.
    //! * `fingerprint` is deterministic across equivalent caches (same
    //!   keys → same bytes).  Two caches with identical entries produce
    //!   identical fingerprints regardless of insertion order.
    //! * `fingerprint` changes when return caps change, the signal the
    //!   orchestrator will use to detect inline-cache convergence.

    use super::super::*;
    use crate::labels::Cap;
    use crate::symbol::FuncKey;
    use crate::taint::domain::VarTaint;
    use smallvec::SmallVec;

    fn key(name: &str) -> FuncKey {
        FuncKey {
            name: name.into(),
            ..Default::default()
        }
    }

    fn sig() -> ArgTaintSig {
        ArgTaintSig(SmallVec::new())
    }

    fn shape(caps_bits: u16) -> CachedInlineShape {
        CachedInlineShape(Some(ReturnShape {
            caps: Cap::from_bits_retain(caps_bits),
            internal_origins: SmallVec::new(),
            param_provenance: 0,
            receiver_provenance: false,
            uses_summary: false,
            return_path_fact: crate::abstract_interp::PathFact::top(),
            return_path_facts: SmallVec::new(),
        }))
    }

    #[test]
    fn clear_epoch_drops_all_entries() {
        let mut c: InlineCache = HashMap::new();
        c.insert((key("a"), sig()), shape(1));
        c.insert((key("b"), sig()), shape(2));
        assert_eq!(c.len(), 2);

        inline_cache_clear_epoch(&mut c);
        assert!(c.is_empty());
    }

    #[test]
    fn fingerprint_is_order_independent() {
        let mut a: InlineCache = HashMap::new();
        a.insert((key("alpha"), sig()), shape(3));
        a.insert((key("beta"), sig()), shape(5));

        let mut b: InlineCache = HashMap::new();
        b.insert((key("beta"), sig()), shape(5));
        b.insert((key("alpha"), sig()), shape(3));

        assert_eq!(inline_cache_fingerprint(&a), inline_cache_fingerprint(&b));
    }

    #[test]
    fn fingerprint_changes_when_return_caps_change() {
        let mut c: InlineCache = HashMap::new();
        c.insert((key("f"), sig()), shape(0));
        let before = inline_cache_fingerprint(&c);

        c.insert((key("f"), sig()), shape(1));
        let after = inline_cache_fingerprint(&c);

        assert_ne!(before, after, "cap refinement must change fingerprint");
    }

    #[test]
    fn fingerprint_tracks_missing_return_taint_as_zero() {
        // A cached miss (no return taint) fingerprints as zero caps so
        // two converged iterations both producing "no return taint" are
        // recognised as equal.
        let mut c: InlineCache = HashMap::new();
        c.insert((key("f"), sig()), CachedInlineShape(None));
        let fp = inline_cache_fingerprint(&c);
        assert_eq!(*fp.get(&(key("f"), sig())).unwrap(), 0);
    }

    // ── apply_cached_shape: origin re-attribution ──────────────────────

    use crate::labels::SourceKind;
    use petgraph::graph::NodeIndex;

    fn origin_at(node: usize, kind: SourceKind, span: Option<(usize, usize)>) -> TaintOrigin {
        TaintOrigin {
            node: NodeIndex::new(node),
            source_kind: kind,
            source_span: span,
        }
    }

    #[test]
    fn apply_reattributes_param_origins_per_call_site() {
        // Shared cached shape: cap bit set, Param(0) marked as provenance source.
        let cached = CachedInlineShape(Some(ReturnShape {
            caps: Cap::SHELL_ESCAPE,
            internal_origins: SmallVec::new(),
            param_provenance: 1u64 << 0,
            receiver_provenance: false,
            uses_summary: true,
            return_path_fact: crate::abstract_interp::PathFact::top(),
            return_path_facts: SmallVec::new(),
        }));

        // Caller A: argument carries an env-source origin.
        let mut state_a = SsaTaintState::initial();
        state_a.set(
            SsaValue(1),
            VarTaint {
                caps: Cap::SHELL_ESCAPE,
                origins: SmallVec::from_vec(vec![origin_at(
                    10,
                    SourceKind::EnvironmentConfig,
                    Some((100, 120)),
                )]),
                uses_summary: false,
            },
        );
        let args_a: Vec<SmallVec<[SsaValue; 2]>> = vec![SmallVec::from_vec(vec![SsaValue(1)])];
        let res_a = apply_cached_shape(&cached, &args_a, &None, &state_a, NodeIndex::new(200));
        let vt_a = res_a.return_taint.expect("apply a");
        assert_eq!(vt_a.origins.len(), 1);
        assert_eq!(vt_a.origins[0].source_kind, SourceKind::EnvironmentConfig);
        assert_eq!(vt_a.origins[0].source_span, Some((100, 120)));

        // Caller B: same caps, different origin (filesystem read).
        let mut state_b = SsaTaintState::initial();
        state_b.set(
            SsaValue(2),
            VarTaint {
                caps: Cap::SHELL_ESCAPE,
                origins: SmallVec::from_vec(vec![origin_at(
                    20,
                    SourceKind::FileSystem,
                    Some((300, 320)),
                )]),
                uses_summary: false,
            },
        );
        let args_b: Vec<SmallVec<[SsaValue; 2]>> = vec![SmallVec::from_vec(vec![SsaValue(2)])];
        let res_b = apply_cached_shape(&cached, &args_b, &None, &state_b, NodeIndex::new(201));
        let vt_b = res_b.return_taint.expect("apply b");
        assert_eq!(vt_b.origins.len(), 1);
        assert_eq!(
            vt_b.origins[0].source_kind,
            SourceKind::FileSystem,
            "second caller must see its own source, not caller A's cached origin"
        );
        assert_eq!(vt_b.origins[0].source_span, Some((300, 320)));
    }

    #[test]
    fn apply_remaps_internal_origins_to_call_site() {
        // Cached shape with a single callee-internal origin.
        let internal_origin = TaintOrigin {
            node: NodeIndex::end(), // placeholder written by extract
            source_kind: SourceKind::UserInput,
            source_span: Some((55, 77)),
        };
        let mut internal_origins: SmallVec<[TaintOrigin; 2]> = SmallVec::new();
        internal_origins.push(internal_origin);
        let cached = CachedInlineShape(Some(ReturnShape {
            caps: Cap::HTML_ESCAPE,
            internal_origins,
            param_provenance: 0,
            receiver_provenance: false,
            uses_summary: true,
            return_path_fact: crate::abstract_interp::PathFact::top(),
            return_path_facts: SmallVec::new(),
        }));

        let state = SsaTaintState::initial();
        let args: Vec<SmallVec<[SsaValue; 2]>> = vec![];
        let call_site = NodeIndex::new(777);
        let res = apply_cached_shape(&cached, &args, &None, &state, call_site);
        let vt = res.return_taint.expect("apply");
        assert_eq!(vt.origins.len(), 1);
        assert_eq!(vt.origins[0].node, call_site);
        assert_eq!(vt.origins[0].source_span, Some((55, 77)));
    }
}

#[cfg(test)]
mod binding_key_tests {
    use super::super::*;
    use crate::cfg::BodyId;
    use crate::taint::domain::VarTaint;
    use smallvec::smallvec;
    use std::collections::HashMap;

    // ── PartialEq / Hash ───────────────────────────────────────────────

    #[test]
    fn same_name_same_body_id_matches() {
        let a = BindingKey::new("x", BodyId(1));
        let b = BindingKey::new("x", BodyId(1));
        assert_eq!(a, b);
    }

    #[test]
    fn same_name_different_body_id_no_match() {
        let a = BindingKey::new("x", BodyId(1));
        let b = BindingKey::new("x", BodyId(2));
        assert_ne!(a, b);
    }

    #[test]
    fn different_name_no_match() {
        assert_ne!(
            BindingKey::new("x", BodyId(1)),
            BindingKey::new("y", BodyId(1))
        );
    }

    // ── seed_lookup ────────────────────────────────────────────────────

    fn taint(caps: u16) -> VarTaint {
        VarTaint {
            caps: Cap::from_bits_truncate(caps),
            origins: smallvec![],
            uses_summary: false,
        }
    }

    #[test]
    fn seed_lookup_exact_match() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(1)), taint(1));
        let key = BindingKey::new("x", BodyId(1));
        assert_eq!(
            seed_lookup(&seed, &key).map(|t| t.caps),
            Some(Cap::from_bits_truncate(1))
        );
    }

    #[test]
    fn seed_lookup_different_body_ids_distinct() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(1)), taint(1));
        seed.insert(BindingKey::new("x", BodyId(2)), taint(2));
        assert_eq!(
            seed_lookup(&seed, &BindingKey::new("x", BodyId(1))).map(|t| t.caps),
            Some(Cap::from_bits_truncate(1))
        );
        assert_eq!(
            seed_lookup(&seed, &BindingKey::new("x", BodyId(2))).map(|t| t.caps),
            Some(Cap::from_bits_truncate(2))
        );
        // BodyId(3) has no entry and there is no wildcard fallback.
        assert!(seed_lookup(&seed, &BindingKey::new("x", BodyId(3))).is_none());
    }

    #[test]
    fn seed_lookup_miss_different_name() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(0)), taint(1));
        assert!(seed_lookup(&seed, &BindingKey::new("y", BodyId(0))).is_none());
    }

    // ── join_seed_maps ─────────────────────────────────────────────────

    #[test]
    fn join_seed_maps_does_not_merge_different_body_ids() {
        let mut a = HashMap::new();
        a.insert(BindingKey::new("x", BodyId(1)), taint(1));
        let mut b = HashMap::new();
        b.insert(BindingKey::new("x", BodyId(2)), taint(2));
        let joined = join_seed_maps(&a, &b);
        assert_eq!(joined.len(), 2);
        assert_eq!(
            joined.get(&BindingKey::new("x", BodyId(1))).unwrap().caps,
            Cap::from_bits_truncate(1)
        );
        assert_eq!(
            joined.get(&BindingKey::new("x", BodyId(2))).unwrap().caps,
            Cap::from_bits_truncate(2)
        );
    }

    #[test]
    fn join_seed_maps_merges_same_body_id() {
        let mut a = HashMap::new();
        a.insert(BindingKey::new("x", BodyId(1)), taint(1));
        let mut b = HashMap::new();
        b.insert(BindingKey::new("x", BodyId(1)), taint(2));
        let joined = join_seed_maps(&a, &b);
        assert_eq!(joined.len(), 1);
        let caps = joined.get(&BindingKey::new("x", BodyId(1))).unwrap().caps;
        assert!(caps.contains(Cap::from_bits_truncate(1)));
        assert!(caps.contains(Cap::from_bits_truncate(2)));
    }

    // ── filter_seed_to_toplevel ────────────────────────────────────────

    #[test]
    fn filter_seed_retains_matching_names_and_rekeys_to_toplevel() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(1)), taint(1));
        seed.insert(BindingKey::new("y", BodyId(2)), taint(2));

        let mut toplevel = HashSet::new();
        toplevel.insert(BindingKey::new("x", BodyId(0)));
        let filtered = filter_seed_to_toplevel(&seed, &toplevel);
        assert_eq!(filtered.len(), 1);
        // Every surviving entry is re-keyed onto BodyId(0).
        assert!(filtered.contains_key(&BindingKey::new("x", BodyId(0))));
        for key in filtered.keys() {
            assert_eq!(key.body_id, BodyId(0));
        }
    }

    #[test]
    fn filter_seed_excludes_non_toplevel() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(1)), taint(1));
        seed.insert(BindingKey::new("y", BodyId(1)), taint(2));

        let mut toplevel = HashSet::new();
        toplevel.insert(BindingKey::new("x", BodyId(0)));
        let filtered = filter_seed_to_toplevel(&seed, &toplevel);
        assert_eq!(filtered.len(), 1);
        assert!(filtered.contains_key(&BindingKey::new("x", BodyId(0))));
    }

    /// When two sibling bodies both contribute the same top-level name
    /// (typical JS/TS pass-2 `combined_exit` shape), the filtered map
    /// merges them under `BodyId(0)` via the join code path.
    #[test]
    fn filter_seed_merges_same_name_across_bodies() {
        let mut seed = HashMap::new();
        seed.insert(BindingKey::new("x", BodyId(1)), taint(0b0001));
        seed.insert(BindingKey::new("x", BodyId(2)), taint(0b0010));
        let mut toplevel = HashSet::new();
        toplevel.insert(BindingKey::new("x", BodyId(0)));
        let filtered = filter_seed_to_toplevel(&seed, &toplevel);
        assert_eq!(filtered.len(), 1);
        let merged = filtered.get(&BindingKey::new("x", BodyId(0))).unwrap();
        assert_eq!(merged.caps, Cap::from_bits_truncate(0b0011));
    }
}

#[cfg(test)]
mod worklist_tests {
    use std::collections::{HashSet, VecDeque};

    /// Simulate the O(1) worklist membership pattern from run_ssa_taint_internal.
    /// Verifies that the HashSet stays in sync with the VecDeque.
    fn worklist_push(wl: &mut VecDeque<usize>, in_wl: &mut HashSet<usize>, idx: usize) -> bool {
        if in_wl.insert(idx) {
            wl.push_back(idx);
            true
        } else {
            false
        }
    }

    fn worklist_pop(wl: &mut VecDeque<usize>, in_wl: &mut HashSet<usize>) -> Option<usize> {
        let val = wl.pop_front()?;
        in_wl.remove(&val);
        Some(val)
    }

    #[test]
    fn duplicate_enqueue_produces_single_entry() {
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();
        assert!(worklist_push(&mut wl, &mut in_wl, 0));
        assert!(!worklist_push(&mut wl, &mut in_wl, 0)); // duplicate
        assert_eq!(wl.len(), 1);
        assert_eq!(in_wl.len(), 1);
    }

    #[test]
    fn pop_removes_from_set() {
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();
        worklist_push(&mut wl, &mut in_wl, 5);
        worklist_push(&mut wl, &mut in_wl, 10);
        let val = worklist_pop(&mut wl, &mut in_wl);
        assert_eq!(val, Some(5));
        assert!(!in_wl.contains(&5));
        assert!(in_wl.contains(&10));
    }

    #[test]
    fn re_enqueue_after_pop() {
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();
        worklist_push(&mut wl, &mut in_wl, 0);
        let _ = worklist_pop(&mut wl, &mut in_wl);
        // After popping, we should be able to re-enqueue
        assert!(worklist_push(&mut wl, &mut in_wl, 0));
        assert_eq!(wl.len(), 1);
    }

    #[test]
    fn empty_worklist() {
        let mut wl: VecDeque<usize> = VecDeque::new();
        let mut in_wl: HashSet<usize> = HashSet::new();
        assert_eq!(worklist_pop(&mut wl, &mut in_wl), None);
        assert!(in_wl.is_empty());
    }

    #[test]
    fn self_loop_pattern() {
        // Simulate a block that re-enqueues itself
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();
        worklist_push(&mut wl, &mut in_wl, 0);

        let block = worklist_pop(&mut wl, &mut in_wl).unwrap();
        assert_eq!(block, 0);
        // Re-enqueue self (simulating state change)
        worklist_push(&mut wl, &mut in_wl, 0);
        // Also enqueue successor
        worklist_push(&mut wl, &mut in_wl, 1);
        assert_eq!(wl.len(), 2);
    }

    #[test]
    fn cycle_with_repeated_discovery() {
        // Simulate cycle: 0→1→2→0 with multiple state propagations
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();
        worklist_push(&mut wl, &mut in_wl, 0);

        let mut iterations = 0;
        while let Some(block) = worklist_pop(&mut wl, &mut in_wl) {
            iterations += 1;
            if iterations > 10 {
                break; // safety net
            }
            let succ = (block + 1) % 3;
            // Only re-enqueue if "state changed" (simulate with iteration limit)
            if iterations < 6 {
                worklist_push(&mut wl, &mut in_wl, succ);
            }
        }
        assert!(iterations <= 10, "worklist should terminate");
        assert!(wl.is_empty());
        assert!(in_wl.is_empty());
    }

    #[test]
    fn dense_successors_no_duplicates() {
        // Many successors, some repeated, old O(n) contains() would be slow here
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();

        // Seed with one node
        worklist_push(&mut wl, &mut in_wl, 0);
        let _ = worklist_pop(&mut wl, &mut in_wl);

        // Try to add 100 successors, with many duplicates
        let mut total_enqueued = 0;
        for i in 0..100 {
            let succ = i % 10; // only 10 unique blocks
            if worklist_push(&mut wl, &mut in_wl, succ) {
                total_enqueued += 1;
            }
        }
        assert_eq!(total_enqueued, 10); // only 10 unique blocks enqueued
        assert_eq!(wl.len(), 10);
        assert_eq!(in_wl.len(), 10);
    }

    #[test]
    fn set_and_deque_stay_in_sync_throughout() {
        let mut wl = VecDeque::new();
        let mut in_wl = HashSet::new();

        // Push, pop, re-push cycle
        for i in 0..20 {
            worklist_push(&mut wl, &mut in_wl, i);
        }
        assert_eq!(wl.len(), in_wl.len());

        for _ in 0..10 {
            worklist_pop(&mut wl, &mut in_wl);
        }
        assert_eq!(wl.len(), in_wl.len());
        assert_eq!(wl.len(), 10);

        // Re-push some previously popped
        for i in 0..5 {
            worklist_push(&mut wl, &mut in_wl, i);
        }
        assert_eq!(wl.len(), in_wl.len());
        assert_eq!(wl.len(), 15);

        // Drain completely
        while worklist_pop(&mut wl, &mut in_wl).is_some() {}
        assert!(wl.is_empty());
        assert!(in_wl.is_empty());
    }
}

#[cfg(test)]
mod primary_sink_location_tests {
    //! Regression guard for the primary sink-location attribution contract:
    //! a [`SinkSite`] carried on an [`SsaFuncSummary`] must propagate
    //! unchanged through summary resolution →
    //! [`SsaTaintEvent::primary_sink_site`] →
    //! [`crate::taint::Finding::primary_location`].
    //!
    //! The test is deliberately low-level, it wires up synthetic SSA and
    //! drives the three emission stages directly, so any future refactor
    //! that drops the site on the floor between stages fails here rather
    //! than only at the corpus/benchmark layer.
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, Cfg, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::{Cap, SourceKind};
    use crate::summary::SinkSite;
    use crate::summary::ssa_summary::SsaFuncSummary;
    use crate::taint::domain::TaintOrigin;
    use petgraph::graph::NodeIndex;
    use petgraph::prelude::*;
    use smallvec::smallvec;
    use std::collections::HashMap;

    /// Build a caller CFG that models `sink(source())`: two nodes, where
    /// the sink node carries `callee = "dangerous_exec"` so
    /// [`reconstruct_flow_path`] can name the sink.
    fn caller_cfg() -> (Cfg, NodeIndex, NodeIndex) {
        let mut cfg = Graph::new();
        let source = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (0, 5),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });
        let sink = cfg.add_node(NodeInfo {
            kind: StmtKind::Call,
            ast: AstMeta {
                span: (10, 30),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta {
                callee: Some("dangerous_exec".into()),
                ..Default::default()
            },
            ..Default::default()
        });
        (cfg, source, sink)
    }

    /// Build an SSA body for `v0 = source(); v1 = dangerous_exec(v0); ret`.
    fn caller_body(source_node: NodeIndex, sink_node: NodeIndex) -> SsaBody {
        let mut cfg_node_map = HashMap::new();
        cfg_node_map.insert(source_node, SsaValue(0));
        cfg_node_map.insert(sink_node, SsaValue(1));
        SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                phis: vec![],
                body: vec![
                    SsaInst {
                        value: SsaValue(0),
                        op: SsaOp::Source,
                        cfg_node: source_node,
                        var_name: Some("x".into()),
                        span: (0, 5),
                    },
                    SsaInst {
                        value: SsaValue(1),
                        op: SsaOp::Call {
                            callee: "dangerous_exec".into(),
                            callee_text: None,
                            args: vec![smallvec![SsaValue(0)]],
                            receiver: None,
                        },
                        cfg_node: sink_node,
                        var_name: None,
                        span: (10, 30),
                    },
                ],
                terminator: Terminator::Return(None),
                preds: smallvec![],
                succs: smallvec![],
            }],
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("x".into()),
                    cfg_node: source_node,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: None,
                    cfg_node: sink_node,
                    block: BlockId(0),
                },
            ],
            cfg_node_map,
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::default(),
            field_writes: std::collections::HashMap::new(),

            synthetic_externals: std::collections::HashSet::new(),
        }
    }

    /// Locks in the end-to-end contract that a SinkSite on an
    /// SsaFuncSummary surfaces verbatim as `Finding.primary_location`.
    ///
    /// If this fails, something on the summary→event→finding path
    /// (`pick_primary_sink_sites`, `emit_ssa_taint_events`, or
    /// `ssa_events_to_findings`) has silently stopped forwarding
    /// coordinates.  Fixing that path, not this test, is the right
    /// response.
    #[test]
    fn ssa_summary_sinksite_surfaces_as_finding_primary_location() {
        let (cfg, source_node, sink_node) = caller_cfg();
        let ssa = caller_body(source_node, sink_node);

        // Synthetic summary: parameter 0 reaches a SHELL_ESCAPE sink inside
        // the callee at "other.rs":42:10.
        let site = SinkSite {
            file_rel: "other.rs".into(),
            line: 42,
            col: 10,
            snippet: "Command::new(cmd).status()".into(),
            cap: Cap::SHELL_ESCAPE,
        };
        let summary = SsaFuncSummary {
            param_to_sink: vec![(0usize, smallvec![site.clone()])],
            ..Default::default()
        };

        // Drive the three emission stages with the summary's own
        // `param_to_sink`, that is what summary resolution feeds in the
        // real pipeline.
        let tainted: Vec<(SsaValue, Cap, SmallVec<[TaintOrigin; 2]>)> = vec![(
            SsaValue(0),
            Cap::SHELL_ESCAPE,
            smallvec![TaintOrigin {
                node: source_node,
                source_kind: SourceKind::EnvironmentConfig,
                source_span: None,
            }],
        )];
        let call_inst = &ssa.blocks[0].body[1];
        let primary_sites = pick_primary_sink_sites(
            call_inst,
            &tainted,
            Cap::SHELL_ESCAPE,
            &summary.param_to_sink,
        );
        assert_eq!(
            primary_sites.len(),
            1,
            "summary site must survive pick filter (line != 0, cap ∩ sink_caps ≠ ∅)",
        );

        let mut events = Vec::new();
        emit_ssa_taint_events(
            &mut events,
            sink_node,
            tainted.clone(),
            Cap::SHELL_ESCAPE,
            /* all_validated */ false,
            /* guard_kind   */ None,
            /* uses_summary */ true,
            primary_sites,
        );
        assert_eq!(events.len(), 1, "single site → single event");
        let event_site = events[0]
            .primary_sink_site
            .as_ref()
            .expect("event must carry the primary SinkSite");
        assert_eq!(
            (
                event_site.file_rel.as_str(),
                event_site.line,
                event_site.col,
            ),
            ("other.rs", 42, 10),
        );

        let findings = ssa_events_to_findings(&events, &ssa, &cfg);
        assert_eq!(findings.len(), 1);
        let loc = findings[0]
            .primary_location
            .as_ref()
            .expect("Finding.primary_location must be populated from SinkSite");
        assert_eq!(loc.file_rel, "other.rs");
        assert_eq!(loc.line, 42);
        assert_eq!(loc.col, 10);
        assert_eq!(loc.snippet, "Command::new(cmd).status()");
    }
}

#[cfg(test)]
mod goto_succ_propagation_tests {
    //! Regression guard for the 3-successor Goto collapse in
    //! `src/ssa/lower.rs` (see `three_successor_collapse_produces_goto`).
    //!
    //! Lowering collapses ≥3-successor blocks to `Terminator::Goto(first)`
    //! but preserves the full successor list on `block.succs`. Flow
    //! consumers (this module's `compute_succ_states`, SCCP's
    //! `process_terminator`) must treat `block.succs` as authoritative.
    //! Without that, taint exits only through the first successor and all
    //! downstream blocks on the other edges silently drop it.
    use super::super::*;
    use crate::cfg::Cfg;
    use crate::state::symbol::SymbolInterner;
    use petgraph::Graph;
    use smallvec::smallvec;

    #[test]
    fn goto_propagates_to_every_succ_on_three_way_collapse() {
        // Build a block with Terminator::Goto(1) but succs = [1, 2, 3], the
        // shape lowering emits for a 3-way fanout.
        let block = SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![],
            terminator: Terminator::Goto(BlockId(1)),
            preds: smallvec![],
            succs: smallvec![BlockId(1), BlockId(2), BlockId(3)],
        };

        let ssa = SsaBody {
            blocks: vec![block.clone()],
            entry: BlockId(0),
            value_defs: vec![],
            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(),
        };

        let cfg: Cfg = Graph::new();
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = std::collections::HashMap::new();

        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: None,
        };

        // A non-bottom exit state, the test only cares that *every* succ
        // receives a clone of it, so any distinguishable state works.
        let mut exit_state = SsaTaintState::initial();
        exit_state.values.push((
            SsaValue(42),
            VarTaint {
                caps: crate::labels::Cap::all(),
                origins: smallvec::SmallVec::new(),
                uses_summary: false,
            },
        ));

        let succ_states = compute_succ_states(&block, &cfg, &ssa, &transfer, &exit_state);

        assert_eq!(
            succ_states.len(),
            3,
            "Goto with 3 succs must propagate to all 3 successors, got {:?}",
            succ_states.iter().map(|(b, _)| *b).collect::<Vec<_>>()
        );

        let targets: Vec<BlockId> = succ_states.iter().map(|(b, _)| *b).collect();
        assert_eq!(targets, vec![BlockId(1), BlockId(2), BlockId(3)]);

        for (bid, state) in &succ_states {
            assert!(
                state.values.iter().any(|(v, _)| *v == SsaValue(42)),
                "succ {:?} did not receive the exit state taint",
                bid
            );
        }
    }

    #[test]
    fn goto_single_successor_still_works() {
        // Normal Goto with a single successor: behavior unchanged.
        let block = SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![],
            terminator: Terminator::Goto(BlockId(1)),
            preds: smallvec![],
            succs: smallvec![BlockId(1)],
        };
        let ssa = SsaBody {
            blocks: vec![block.clone()],
            entry: BlockId(0),
            value_defs: vec![],
            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(),
        };
        let cfg: Cfg = Graph::new();
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = std::collections::HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: None,
        };
        let exit_state = SsaTaintState::initial();

        let succ_states = compute_succ_states(&block, &cfg, &ssa, &transfer, &exit_state);
        assert_eq!(succ_states.len(), 1);
        assert_eq!(succ_states[0].0, BlockId(1));
    }

    // ── PathFact branch-narrowing smoke tests ─────────────────────────────

    /// Build a minimal `SsaBody` with a single value def named `var_name`.
    /// Used to drive `apply_path_fact_branch_narrowing` without a full CFG.
    fn ssa_body_with_named_value(var_name: &str) -> SsaBody {
        SsaBody {
            blocks: vec![],
            entry: BlockId(0),
            value_defs: vec![crate::ssa::ir::ValueDef {
                var_name: Some(var_name.into()),
                cfg_node: NodeIndex::new(0),
                block: BlockId(0),
            }],
            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(),
        }
    }

    fn initial_state_with_abstract() -> SsaTaintState {
        let mut s = SsaTaintState::initial();
        s.abstract_state = Some(crate::abstract_interp::AbstractState::empty());
        s
    }

    #[test]
    fn path_fact_contains_dotdot_narrows_false_branch() {
        let ssa = ssa_body_with_named_value("user");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing(
            &mut true_state,
            &mut false_state,
            "user.contains(\"..\")",
            &["user".to_string()],
            &ssa,
        );

        let abs = false_state.abstract_state.as_ref().unwrap();
        let fact = abs.get(SsaValue(0)).path;
        assert_eq!(fact.dotdot, crate::abstract_interp::Tri::No);
        // true branch (rejection path) unchanged.
        let true_abs = true_state.abstract_state.as_ref().unwrap();
        assert_eq!(
            true_abs.get(SsaValue(0)).path.dotdot,
            crate::abstract_interp::Tri::Maybe
        );
    }

    #[test]
    fn path_fact_starts_with_slash_narrows_false_branch() {
        let ssa = ssa_body_with_named_value("p");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing(
            &mut true_state,
            &mut false_state,
            "p.starts_with('/')",
            &["p".to_string()],
            &ssa,
        );

        let fact = false_state
            .abstract_state
            .as_ref()
            .unwrap()
            .get(SsaValue(0))
            .path;
        assert_eq!(fact.absolute, crate::abstract_interp::Tri::No);
    }

    #[test]
    fn path_fact_is_absolute_narrows_false_branch() {
        let ssa = ssa_body_with_named_value("p");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing(
            &mut true_state,
            &mut false_state,
            "p.is_absolute()",
            &["p".to_string()],
            &ssa,
        );

        let fact = false_state
            .abstract_state
            .as_ref()
            .unwrap()
            .get(SsaValue(0))
            .path;
        assert_eq!(fact.absolute, crate::abstract_interp::Tri::No);
    }

    #[test]
    fn path_fact_starts_with_literal_sets_prefix_lock_on_true_branch() {
        let ssa = ssa_body_with_named_value("p");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing(
            &mut true_state,
            &mut false_state,
            "p.starts_with(\"/var/app/uploads/\")",
            &["p".to_string()],
            &ssa,
        );

        let fact = true_state
            .abstract_state
            .as_ref()
            .unwrap()
            .get(SsaValue(0))
            .path;
        assert_eq!(
            fact.prefix_lock.as_deref(),
            Some("/var/app/uploads/"),
            "positive starts_with(literal) must attach prefix_lock on true branch"
        );
    }

    #[test]
    fn path_fact_negated_contains_dotdot_narrows_true_branch() {
        // `if !path.contains("..") { return; } sink(path);` — the surviving
        // (sink-reaching) arm is the TRUE branch of the IF condition.  The
        // rejection axis (DotDot) must narrow `true_state`, not `false_state`,
        // otherwise the unsafe arm gets dotdot=No and the sink suppression
        // masks the bug.
        let ssa = ssa_body_with_named_value("path");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing_with_interner(
            &mut true_state,
            &mut false_state,
            "!path.contains(\"..\")",
            &["path".to_string()],
            &ssa,
            None,
            true,
        );

        let true_abs = true_state.abstract_state.as_ref().unwrap();
        let false_abs = false_state.abstract_state.as_ref().unwrap();
        assert_eq!(
            true_abs.get(SsaValue(0)).path.dotdot,
            crate::abstract_interp::Tri::No,
            "negated-contains: TRUE arm (sink-reaching, safe) must narrow"
        );
        assert_eq!(
            false_abs.get(SsaValue(0)).path.dotdot,
            crate::abstract_interp::Tri::Maybe,
            "negated-contains: FALSE arm (rejection arm) must NOT narrow"
        );
    }

    #[test]
    fn path_fact_negated_filepath_islocal_narrows_false_branch() {
        // `if !filepath.IsLocal(p) { return; } sink(p);` — Go idiom.  The
        // classifier consumes the `!` itself (pre-negated handler), so the
        // safe arm remains the FALSE branch of the whole condition even
        // though `condition_negated == true` at AST level.
        let ssa = ssa_body_with_named_value("p");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing_with_interner(
            &mut true_state,
            &mut false_state,
            "!filepath.IsLocal(p)",
            &["p".to_string()],
            &ssa,
            None,
            true,
        );

        let true_abs = true_state.abstract_state.as_ref().unwrap();
        let false_abs = false_state.abstract_state.as_ref().unwrap();
        assert_eq!(
            false_abs.get(SsaValue(0)).path.dotdot,
            crate::abstract_interp::Tri::No,
            "!filepath.IsLocal: FALSE arm (sink-reaching, IsLocal=true) must narrow"
        );
        assert_eq!(
            false_abs.get(SsaValue(0)).path.absolute,
            crate::abstract_interp::Tri::No,
            "!filepath.IsLocal: FALSE arm absolute axis must narrow"
        );
        assert_eq!(
            true_abs.get(SsaValue(0)).path.dotdot,
            crate::abstract_interp::Tri::Maybe,
            "!filepath.IsLocal: TRUE arm (return) must NOT narrow"
        );
    }

    #[test]
    fn path_fact_no_match_leaves_state_untouched() {
        let ssa = ssa_body_with_named_value("x");
        let mut true_state = initial_state_with_abstract();
        let mut false_state = initial_state_with_abstract();

        super::super::apply_path_fact_branch_narrowing(
            &mut true_state,
            &mut false_state,
            "x == 5",
            &["x".to_string()],
            &ssa,
        );

        // No path-idiom → both abstract_states remain empty (no writes).
        let tabs = true_state.abstract_state.as_ref().unwrap();
        let fabs = false_state.abstract_state.as_ref().unwrap();
        assert!(tabs.get(SsaValue(0)).path.is_top());
        assert!(fabs.get(SsaValue(0)).path.is_top());
    }

    #[test]
    fn is_path_safe_for_sink_proven_safe_returns_true() {
        use crate::abstract_interp::{AbstractState, AbstractValue, PathFact};

        let mut abs = AbstractState::empty();
        let v = SsaValue(0);
        // Mark v as proven path-safe via the builder API.
        let safe_fact = PathFact::default()
            .with_dotdot_cleared()
            .with_absolute_cleared();
        abs.set(v, AbstractValue::with_path_fact(safe_fact.clone()));
        assert!(safe_fact.is_path_safe());
        assert_eq!(abs.get(v).path, safe_fact);
    }

    #[test]
    fn is_path_safe_for_sink_unknown_axis_returns_false() {
        use crate::abstract_interp::PathFact;

        // Only dotdot is cleared, absolute stays Maybe → not path-safe.
        let half_fact = PathFact::default().with_dotdot_cleared();
        assert!(!half_fact.is_path_safe());
    }

    // ── is_non_data_return + detect_variant_inner_fact ──────────────────

    fn make_body_with_const_return(text: &str) -> SsaBody {
        // A trivial body with one block that returns a Const-defined SSA
        // value.  Built by hand because the public lowering pipeline
        // requires a full Cfg + analysis context.
        use crate::ssa::ir::{BlockId, SsaBlock, SsaInst, SsaOp, Terminator};
        use petgraph::graph::NodeIndex;
        let v = SsaValue(0);
        SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                preds: smallvec::SmallVec::new(),
                succs: smallvec::SmallVec::new(),
                phis: vec![],
                body: vec![SsaInst {
                    value: v,
                    op: SsaOp::Const(Some(text.to_string())),
                    cfg_node: NodeIndex::new(0),
                    var_name: None,
                    span: (0, 0),
                }],
                terminator: Terminator::Return(Some(v)),
            }],
            entry: BlockId(0),
            value_defs: vec![crate::ssa::ir::ValueDef {
                var_name: None,
                cfg_node: NodeIndex::new(0),
                block: BlockId(0),
            }],
            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(),
        }
    }

    #[test]
    fn is_non_data_return_recognises_none_constant() {
        let body = make_body_with_const_return("None");
        assert!(super::super::is_non_data_return(SsaValue(0), &body));
    }

    #[test]
    fn is_non_data_return_recognises_null_and_nil_aliases() {
        for tag in ["null", "nil", "NULL", "undefined", "()"] {
            let body = make_body_with_const_return(tag);
            assert!(
                super::super::is_non_data_return(SsaValue(0), &body),
                "expected {tag} to be recognised as non-data return"
            );
        }
    }

    #[test]
    fn is_non_data_return_rejects_string_literals() {
        let body = make_body_with_const_return("\"some/path\"");
        assert!(
            !super::super::is_non_data_return(SsaValue(0), &body),
            "string literals must participate in path-safety join (could be unsafe)"
        );
    }
}

// ── receiver_candidates_for_type_lookup walks FieldProj ──────
//
// After SSA decomposition, `c.client.send(req)` lowers to
//   v_c      = Param("c", 0)
//   v_client = FieldProj(v_c, "client")
//   v_call   = Call("send", receiver: v_client, args: [v_req])
//
// The `receiver` of the outer call is `v_client`, not `v_c`.  For
// type-qualified label resolution to find the typed root (`c` of e.g.
// `RouterContext`), the candidate walk must traverse FieldProj receivers
// in addition to the existing Rust-only Call.receiver chain.  These tests
// pin the FieldProj-walking contract.
#[cfg(test)]
mod receiver_candidates_field_proj_tests {
    use super::super::*;
    use crate::symbol::Lang;
    use petgraph::graph::NodeIndex;
    use smallvec::smallvec;
    use std::collections::HashMap;

    fn empty_value_def(name: &str) -> ValueDef {
        ValueDef {
            var_name: Some(name.into()),
            cfg_node: NodeIndex::new(0),
            block: BlockId(0),
        }
    }

    /// Build a one-block SSA body for `c.client.send(req)`:
    ///   v0 = Param(c, 0)
    ///   v1 = Param(req, 1)
    ///   v2 = FieldProj(v0, "client")
    ///   v3 = Call("send", receiver: v2, args: [v1])
    fn body_with_field_proj_chain() -> SsaBody {
        let mut interner = crate::ssa::ir::FieldInterner::default();
        let client_id = interner.intern("client");
        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![
                SsaInst {
                    value: SsaValue(0),
                    op: SsaOp::Param { index: 0 },
                    cfg_node: NodeIndex::new(0),
                    var_name: Some("c".into()),
                    span: (0, 0),
                },
                SsaInst {
                    value: SsaValue(1),
                    op: SsaOp::Param { index: 1 },
                    cfg_node: NodeIndex::new(0),
                    var_name: Some("req".into()),
                    span: (0, 0),
                },
                SsaInst {
                    value: SsaValue(2),
                    op: SsaOp::FieldProj {
                        receiver: SsaValue(0),
                        field: client_id,
                        projected_type: None,
                    },
                    cfg_node: NodeIndex::new(0),
                    var_name: Some("c.client".into()),
                    span: (0, 0),
                },
                SsaInst {
                    value: SsaValue(3),
                    op: SsaOp::Call {
                        callee: "send".into(),
                        callee_text: Some("c.client.send".into()),
                        args: vec![smallvec![SsaValue(1)]],
                        receiver: Some(SsaValue(2)),
                    },
                    cfg_node: NodeIndex::new(0),
                    var_name: Some("c.client.send".into()),
                    span: (0, 0),
                },
            ],
            terminator: Terminator::Return(Some(SsaValue(3))),
            preds: smallvec![],
            succs: smallvec![],
        }];
        SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs: vec![
                empty_value_def("c"),
                empty_value_def("req"),
                empty_value_def("c.client"),
                empty_value_def("c.client.send"),
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner: interner,
            field_writes: std::collections::HashMap::new(),

            synthetic_externals: std::collections::HashSet::new(),
        }
    }

    #[test]
    fn field_proj_receiver_walks_to_typed_root_in_go() {
        // Go is not Rust, so pre-Phase-4 the candidate walk would have
        // returned ONLY the immediate receiver (v2 = FieldProj). With
        // We walk through FieldProj.receiver to recover v0 (the
        // typed root `c`).
        let body = body_with_field_proj_chain();
        let cands =
            super::super::receiver_candidates_for_type_lookup(SsaValue(2), Some(&body), Lang::Go);
        assert!(
            cands.contains(&SsaValue(2)),
            "starts with the immediate receiver"
        );
        assert!(
            cands.contains(&SsaValue(0)),
            "must walk FieldProj.receiver to reach the typed root v0 (`c`); got {cands:?}",
        );
    }

    #[test]
    fn field_proj_receiver_walks_in_python_and_java() {
        let body = body_with_field_proj_chain();
        for lang in [Lang::Python, Lang::Java, Lang::JavaScript, Lang::TypeScript] {
            let cands =
                super::super::receiver_candidates_for_type_lookup(SsaValue(2), Some(&body), lang);
            assert!(
                cands.contains(&SsaValue(0)),
                "{:?}: FieldProj.receiver walk must reach v0; got {cands:?}",
                lang,
            );
        }
    }

    #[test]
    fn rust_walks_call_receiver_and_field_proj() {
        // Rust still walks Call.receiver (chained `.unwrap()` shape), and
        // now ALSO walks FieldProj.receiver for any intermediate field
        // accesses in the chain.
        let body = body_with_field_proj_chain();
        let cands =
            super::super::receiver_candidates_for_type_lookup(SsaValue(2), Some(&body), Lang::Rust);
        assert!(cands.contains(&SsaValue(0)));
    }

    #[test]
    fn no_ssa_body_returns_only_start() {
        let cands = super::super::receiver_candidates_for_type_lookup(SsaValue(2), None, Lang::Go);
        assert_eq!(cands.as_slice(), &[SsaValue(2)]);
    }

    #[test]
    fn cycle_safety_no_infinite_loop_on_self_ref() {
        // Pathological: a FieldProj whose receiver is itself.  Should not
        // infinite-loop; should bail after one step (out.contains check).
        let mut interner = crate::ssa::ir::FieldInterner::default();
        let f_id = interner.intern("self_ref");
        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![SsaInst {
                value: SsaValue(0),
                op: SsaOp::FieldProj {
                    receiver: SsaValue(0),
                    field: f_id,
                    projected_type: None,
                },
                cfg_node: NodeIndex::new(0),
                var_name: None,
                span: (0, 0),
            }],
            terminator: Terminator::Return(Some(SsaValue(0))),
            preds: smallvec![],
            succs: smallvec![],
        }];
        let body = SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs: vec![empty_value_def("v0")],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner: interner,
            field_writes: std::collections::HashMap::new(),

            synthetic_externals: std::collections::HashSet::new(),
        };
        let cands =
            super::super::receiver_candidates_for_type_lookup(SsaValue(0), Some(&body), Lang::Go);
        // Cycle: only the start value is recorded; no infinite walk.
        assert_eq!(cands.as_slice(), &[SsaValue(0)]);
    }
}

// ── Hierarchy: ResolvedSummary union semantics ──────────
//
// `merge_resolved_summaries_fanout` is invoked at virtual-dispatch call
// sites where the receiver's static type has multiple concrete
// implementers.  These tests pin the merge contract that taint
// soundness depends on.
#[cfg(test)]
mod fanout_merge_tests {
    use super::super::ResolvedSummary;
    use super::super::merge_resolved_summaries_fanout;
    use crate::labels::Cap;
    use crate::summary::SinkSite;
    use smallvec::smallvec;

    fn empty() -> ResolvedSummary {
        ResolvedSummary {
            source_caps: Cap::empty(),
            sanitizer_caps: Cap::empty(),
            sink_caps: Cap::empty(),
            param_to_sink: vec![],
            param_to_sink_sites: vec![],
            propagates_taint: false,
            propagating_params: 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(),
            param_to_gate_filters: vec![],
            validated_params_to_return: vec![],
        }
    }

    /// B1, caps that grow taint signal (source/sink/receiver_to_sink)
    /// are unioned.  sanitizer_caps are intersected so only bits
    /// stripped by EVERY implementer count as cleared at the call site.
    #[test]
    fn merge_caps_union_or_intersect() {
        let mut a = empty();
        a.source_caps = Cap::from_bits(0b0011).unwrap();
        a.sanitizer_caps = Cap::from_bits(0b1110).unwrap();
        a.sink_caps = Cap::from_bits(0b0001).unwrap();
        a.receiver_to_sink = Cap::from_bits(0b0010).unwrap();

        let mut b = empty();
        b.source_caps = Cap::from_bits(0b0100).unwrap();
        b.sanitizer_caps = Cap::from_bits(0b0110).unwrap();
        b.sink_caps = Cap::from_bits(0b1000).unwrap();
        b.receiver_to_sink = Cap::from_bits(0b0001).unwrap();

        let m = merge_resolved_summaries_fanout(a, b);
        assert_eq!(m.source_caps.bits(), 0b0111, "source_caps must OR");
        assert_eq!(m.sanitizer_caps.bits(), 0b0110, "sanitizer_caps must AND");
        assert_eq!(m.sink_caps.bits(), 0b1001, "sink_caps must OR");
        assert_eq!(
            m.receiver_to_sink.bits(),
            0b0011,
            "receiver_to_sink must OR"
        );
    }

    /// B2, propagates_taint is OR'd; propagating_params is the union
    /// (any implementer's propagator counts).
    #[test]
    fn merge_propagation_unions() {
        let mut a = empty();
        a.propagates_taint = false;
        a.propagating_params = vec![0, 2];

        let mut b = empty();
        b.propagates_taint = true;
        b.propagating_params = vec![1, 2];

        let m = merge_resolved_summaries_fanout(a, b);
        assert!(m.propagates_taint, "propagates_taint must be OR'd");
        let mut params = m.propagating_params.clone();
        params.sort();
        assert_eq!(params, vec![0, 1, 2]);
    }

    /// B3, param_to_sink merges per-parameter caps (OR).  An impl
    /// that adds a sink at param N composes with another impl that
    /// adds a different cap at the same N.
    #[test]
    fn merge_param_to_sink_unions_per_param() {
        let mut a = empty();
        a.param_to_sink = vec![
            (0, Cap::from_bits(0b0001).unwrap()),
            (1, Cap::from_bits(0b0010).unwrap()),
        ];
        let mut b = empty();
        b.param_to_sink = vec![
            (0, Cap::from_bits(0b0100).unwrap()),
            (2, Cap::from_bits(0b1000).unwrap()),
        ];

        let m = merge_resolved_summaries_fanout(a, b);
        let mut sorted: Vec<(usize, u16)> = m
            .param_to_sink
            .iter()
            .map(|(i, c)| (*i, c.bits()))
            .collect();
        sorted.sort();
        assert_eq!(
            sorted,
            vec![(0, 0b0101), (1, 0b0010), (2, 0b1000)],
            "param_to_sink must union per-parameter caps and preserve disjoint params"
        );
    }

    /// B4, param_to_sink_sites merges per-parameter site lists with
    /// PartialEq dedup.  The same site appearing in both impls (e.g.
    /// inherited definition) must not be reported twice.
    #[test]
    fn merge_param_to_sink_sites_dedups() {
        let shared = SinkSite {
            file_rel: "src/lib.rs".into(),
            line: 10,
            col: 5,
            snippet: "exec(q)".into(),
            cap: Cap::from_bits(0b0001).unwrap(),
        };
        let unique_a = SinkSite {
            file_rel: "src/a.rs".into(),
            line: 20,
            col: 3,
            snippet: "do_a(q)".into(),
            cap: Cap::from_bits(0b0001).unwrap(),
        };
        let unique_b = SinkSite {
            file_rel: "src/b.rs".into(),
            line: 30,
            col: 7,
            snippet: "do_b(q)".into(),
            cap: Cap::from_bits(0b0001).unwrap(),
        };
        let mut a = empty();
        a.param_to_sink_sites = vec![(0, smallvec![shared.clone(), unique_a.clone()])];
        let mut b = empty();
        b.param_to_sink_sites = vec![(0, smallvec![shared.clone(), unique_b.clone()])];

        let m = merge_resolved_summaries_fanout(a, b);
        assert_eq!(m.param_to_sink_sites.len(), 1);
        let (idx, sites) = &m.param_to_sink_sites[0];
        assert_eq!(*idx, 0);
        assert_eq!(
            sites.len(),
            3,
            "shared site must dedup, unique sites preserved"
        );
        assert!(sites.iter().any(|s| s == &shared));
        assert!(sites.iter().any(|s| s == &unique_a));
        assert!(sites.iter().any(|s| s == &unique_b));
    }

    /// B5, SSA-precision fields are dropped on disagreement.  Two
    /// summaries with different `return_type` collapse to None;
    /// agreement is preserved.
    #[test]
    fn merge_ssa_precision_drops_on_disagreement() {
        use crate::ssa::type_facts::TypeKind;

        let mut a = empty();
        a.return_type = Some(TypeKind::Int);
        let mut b = empty();
        b.return_type = Some(TypeKind::String);
        let m = merge_resolved_summaries_fanout(a, b);
        assert_eq!(
            m.return_type, None,
            "disagreeing return_type values must be dropped to None"
        );

        let mut a = empty();
        a.return_type = Some(TypeKind::Int);
        let mut b = empty();
        b.return_type = Some(TypeKind::Int);
        let m = merge_resolved_summaries_fanout(a, b);
        assert_eq!(
            m.return_type,
            Some(TypeKind::Int),
            "agreeing return_type values must be preserved"
        );
    }

    /// B6, abstract_transfer + param_return_paths drop on
    /// disagreement (precise predicate-path data is not safely
    /// composable across distinct function bodies).
    #[test]
    fn merge_abstract_and_path_data_drops_on_disagreement() {
        use crate::abstract_interp::AbstractTransfer;
        use crate::summary::ssa_summary::{ReturnPathTransform, TaintTransform};

        let mut a = empty();
        a.abstract_transfer = vec![(0, AbstractTransfer::default())];
        a.param_return_paths = vec![(
            0,
            smallvec![ReturnPathTransform {
                transform: TaintTransform::Identity,
                path_predicate_hash: 0,
                known_true: 0,
                known_false: 0,
                abstract_contribution: None,
            }],
        )];
        let b = empty(); // empty path data → disagreement on element-by-element compare

        let m = merge_resolved_summaries_fanout(a, b);
        assert!(
            m.abstract_transfer.is_empty(),
            "abstract_transfer must drop on disagreement"
        );
        assert!(
            m.param_return_paths.is_empty(),
            "param_return_paths must drop on disagreement"
        );
    }

    /// B7, empty + empty = empty (no panic on degenerate inputs).
    #[test]
    fn merge_empties_is_identity() {
        let m = merge_resolved_summaries_fanout(empty(), empty());
        assert_eq!(m.source_caps, Cap::empty());
        assert_eq!(m.sink_caps, Cap::empty());
        assert!(m.param_to_sink.is_empty());
        assert!(!m.propagates_taint);
    }
}

//── synthetic field-WRITE round-trip ──────────────
//
// SSA lowering populates `SsaBody.field_writes` with entries that lift a
// synthetic base-update Assign (`obj.f = rhs`) into a structural field
// write.  When the taint engine sees one of those entries while
// `pointer_facts` is set, it must mirror the rhs taint into the
// matching `(loc, field)` cell on `SsaTaintState.field_taint`.  These
// tests pin the lift end-to-end without involving the real lowering
// pipeline so the side-table -> field-cell wiring is testable in
// isolation.
#[cfg(test)]
mod field_write_tests {
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, Cfg, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::pointer::PointsToFacts;
    use crate::ssa::ir::FieldId;
    use crate::state::symbol::SymbolInterner;
    use crate::taint::ssa_transfer::state::FieldTaintKey;
    use petgraph::graph::NodeIndex;
    use petgraph::prelude::*;
    use smallvec::smallvec;
    use std::collections::HashMap;

    /// Build a CFG with a single node tagged as a `Source` so we can
    /// drive `transfer_inst` with a real `cfg_node` for each instruction.
    fn make_cfg() -> (Cfg, NodeIndex, NodeIndex, NodeIndex, NodeIndex) {
        let mut cfg = Graph::new();
        let n_param = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (0, 3),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });
        let n_source = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (5, 12),
                ..Default::default()
            },
            taint: TaintMeta {
                labels: smallvec![DataLabel::Source(Cap::ENV_VAR)],
                ..Default::default()
            },
            call: CallMeta::default(),
            ..Default::default()
        });
        let n_assign = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (14, 30),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });
        let n_proj = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (32, 45),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });
        (cfg, n_param, n_source, n_assign, n_proj)
    }

    /// Synthetic body for the W1 round-trip:
    /// ```ignore
    ///   v0: Param { 0 }      // `obj`
    ///   v1: Source           // env source
    ///   v2: Assign([v1])     // synth field write: obj.cache = v1.
    ///                        // `field_writes[v2] = (v0, FieldId(0))`
    ///                        // (FieldId(0) interned for "cache").
    ///   v3: FieldProj v0.cache  // read back `obj.cache`
    /// ```
    fn make_body() -> (SsaBody, FieldId) {
        let (_cfg, n_param, n_source, n_assign, n_proj) = make_cfg();
        let mut field_interner = crate::ssa::ir::FieldInterner::default();
        let cache_id = field_interner.intern("cache");

        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![
                SsaInst {
                    value: SsaValue(0),
                    op: SsaOp::Param { index: 0 },
                    cfg_node: n_param,
                    var_name: Some("obj".into()),
                    span: (0, 3),
                },
                SsaInst {
                    value: SsaValue(1),
                    op: SsaOp::Source,
                    cfg_node: n_source,
                    var_name: Some("src".into()),
                    span: (5, 12),
                },
                SsaInst {
                    value: SsaValue(2),
                    op: SsaOp::Assign(smallvec![SsaValue(1)]),
                    cfg_node: n_assign,
                    var_name: Some("obj".into()),
                    span: (14, 30),
                },
                SsaInst {
                    value: SsaValue(3),
                    op: SsaOp::FieldProj {
                        receiver: SsaValue(0),
                        field: cache_id,
                        projected_type: None,
                    },
                    cfg_node: n_proj,
                    var_name: Some("read".into()),
                    span: (32, 45),
                },
            ],
            terminator: Terminator::Return(None),
            preds: smallvec![],
            succs: smallvec![],
        }];
        let value_defs = vec![
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_param,
                block: BlockId(0),
            },
            ValueDef {
                var_name: Some("src".into()),
                cfg_node: n_source,
                block: BlockId(0),
            },
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_assign,
                block: BlockId(0),
            },
            ValueDef {
                var_name: Some("read".into()),
                cfg_node: n_proj,
                block: BlockId(0),
            },
        ];
        let mut field_writes = HashMap::new();
        field_writes.insert(SsaValue(2), (SsaValue(0), cache_id));
        let body = SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs,
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner,
            field_writes,
            synthetic_externals: HashSet::new(),
        };
        (body, cache_id)
    }

    /// Run pointer analysis on the body so we get realistic pt() sets.
    fn analyse(body: &SsaBody) -> PointsToFacts {
        crate::pointer::analyse_body(body, crate::cfg::BodyId(7))
    }

    /// Reuse `make_cfg`'s nodes, the body's instructions all reference
    /// them, so `transfer_inst` can index `cfg[cfg_node]`.
    fn drive(body: &SsaBody, pf: &PointsToFacts) -> SsaTaintState {
        // We need a CFG that contains the bodies' cfg_nodes.
        let (cfg, _, _, _, _) = make_cfg();
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(7),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(pf),
        };

        let mut state = SsaTaintState::initial();
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, body, &transfer, &mut state);
        }
        state
    }

    /// Round-trip: a synthetic field write records the rhs taint into the
    /// `(loc, field)` cell, and a subsequent FieldProj read recovers it.
    #[test]
    fn write_then_read_round_trips() {
        let (body, cache_id) = make_body();
        let pf = analyse(&body);
        let state = drive(&body, &pf);

        // The FieldProj read on `obj.cache` should observe the source's
        // ENV_VAR cap via the `(Param(_, 0), cache)` field cell.
        let read_taint = state
            .get(SsaValue(3))
            .expect("FieldProj read should produce taint");
        assert!(
            read_taint.caps.contains(Cap::ENV_VAR),
            "field-proj read must inherit source's ENV_VAR cap; got {:?}",
            read_taint.caps,
        );

        // The cell itself must exist on `pt(v0)`'s sole member.
        let pt_v0 = pf.pt(SsaValue(0));
        assert!(!pt_v0.is_empty() && !pt_v0.is_top());
        let parent_loc = pt_v0.iter().next().unwrap();
        let cell = state
            .get_field(FieldTaintKey {
                loc: parent_loc,
                field: cache_id,
            })
            .expect("field cell should be populated by the W1 hook");
        assert!(cell.taint.caps.contains(Cap::ENV_VAR));
    }

    /// Pointer-disabled run (`pointer_facts: None`): no field cell is
    /// recorded, no taint flows through the `obj.cache` projection.  The
    /// strict-additive contract, pointer-disabled behaviour is the
    /// pre-W1 baseline.
    #[test]
    fn pointer_disabled_run_produces_no_field_taint() {
        let (body, cache_id) = make_body();
        // Build the same body but skip `pointer_facts` on the transfer.
        let (cfg, _, _, _, _) = make_cfg();
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: None,
        };
        let mut state = SsaTaintState::initial();
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }
        // No field cell populated.
        assert!(
            state.field_taint.is_empty(),
            "pointer-disabled run must not populate field_taint",
        );
        // FieldProj reads still produce the receiver's existing taint ,
        // none, so no entry for SsaValue(3) either.
        assert!(state.get(SsaValue(3)).is_none());
        let _ = cache_id;
    }

    /// W4: when the rhs of a synth field-WRITE has its symbol-level
    /// `validated_must` bit set, the field cell records
    /// `validated_must = true`.  A subsequent FieldProj read seeds the
    /// projected value's symbol-level `validated_must` from the cell.
    ///
    /// This is the key invariant: validation flows *through* abstract
    /// field identity, the read recovers what the write recorded.
    #[test]
    fn write_then_read_preserves_validated_must() {
        let (body, cache_id) = make_body();
        let pf = analyse(&body);

        // Build an interner that knows "src" and "read" so we can seed
        // and observe symbol-level validation bits.
        let mut interner = SymbolInterner::new();
        let sym_src = interner.intern("src");
        let sym_read = interner.intern("read");

        let (cfg, _, _, _, _) = make_cfg();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(7),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(&pf),
        };

        // Pre-seed `validated_must` on `src` so the synth Assign
        // observes it at write time.
        let mut state = SsaTaintState::initial();
        state.validated_must.insert(sym_src);
        state.validated_may.insert(sym_src);
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }

        // Cell records validated_must=true (rhs was must-validated).
        let pt_v0 = pf.pt(SsaValue(0));
        let parent_loc = pt_v0.iter().next().unwrap();
        let cell = state
            .get_field(FieldTaintKey {
                loc: parent_loc,
                field: cache_id,
            })
            .expect("W1 cell present");
        assert!(
            cell.validated_must,
            "cell.validated_must must be true after a must-validated rhs"
        );
        assert!(cell.validated_may);

        // Read seeded the projected symbol's validation bits.
        assert!(
            state.validated_must.contains(sym_read),
            "FieldProj read should seed validated_must on the projected symbol"
        );
        assert!(state.validated_may.contains(sym_read));
    }

    /// Empty-pt skip: when the receiver has no recorded points-to set
    /// (e.g. its op produces no abstract location), the field-write
    /// hook records nothing.  Strict-additive over the existing
    /// pass-through behaviour.
    #[test]
    fn write_with_empty_pt_records_nothing() {
        // Body with v0 = Const (no abstract location), v1 = Source,
        // v2 = Assign([v1]) annotated as field write of `v0.cache`.
        let (cfg, n0, n1, n2, _n3) = make_cfg();
        let mut field_interner = crate::ssa::ir::FieldInterner::default();
        let cache_id = field_interner.intern("cache");

        let body = SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                phis: vec![],
                body: vec![
                    SsaInst {
                        value: SsaValue(0),
                        op: SsaOp::Const(Some("0".into())),
                        cfg_node: n0,
                        var_name: Some("c".into()),
                        span: (0, 1),
                    },
                    SsaInst {
                        value: SsaValue(1),
                        op: SsaOp::Source,
                        cfg_node: n1,
                        var_name: Some("src".into()),
                        span: (5, 12),
                    },
                    SsaInst {
                        value: SsaValue(2),
                        op: SsaOp::Assign(smallvec![SsaValue(1)]),
                        cfg_node: n2,
                        var_name: Some("c".into()),
                        span: (14, 30),
                    },
                ],
                terminator: Terminator::Return(None),
                preds: smallvec![],
                succs: smallvec![],
            }],
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("c".into()),
                    cfg_node: n0,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("src".into()),
                    cfg_node: n1,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("c".into()),
                    cfg_node: n2,
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner,
            field_writes: {
                let mut m = HashMap::new();
                m.insert(SsaValue(2), (SsaValue(0), cache_id));
                m
            },
            synthetic_externals: HashSet::new(),
        };
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(0));
        // v0 is Const → empty pt, the hook should not insert anything.
        assert!(
            pf.pt(SsaValue(0)).is_empty(),
            "Const value should have empty pt set",
        );

        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(&pf),
        };

        let mut state = SsaTaintState::initial();
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }
        assert!(
            state.field_taint.is_empty(),
            "empty pt set must produce no field cell entries",
        );
    }
}

//── container ELEM write/read round-trip ──────────
//
// Container methods like `arr.push(v)` / `arr.shift()` flow per-element
// taint through the `Field(_, ELEM)` cells on `SsaTaintState`.  These
// tests pin the contract: a write hook on the receiver-side stores arg
// taint into the cell, and a subsequent read picks it up via the
// `analyse_body`-emitted FieldProj-like projection on the call result.
#[cfg(test)]
mod container_elem_tests {
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, Cfg, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::ssa::ir::FieldId;
    use crate::state::symbol::SymbolInterner;
    use crate::taint::ssa_transfer::state::FieldTaintKey;
    use petgraph::graph::NodeIndex;
    use petgraph::prelude::*;
    use smallvec::smallvec;
    use std::collections::HashMap;

    fn cfg_with_nodes(n: usize) -> (Cfg, Vec<NodeIndex>) {
        let mut cfg = Graph::new();
        let mut nodes = Vec::new();
        for i in 0..n {
            let nidx = cfg.add_node(NodeInfo {
                kind: if i == 1 { StmtKind::Seq } else { StmtKind::Seq },
                ast: AstMeta {
                    span: (i * 10, i * 10 + 5),
                    ..Default::default()
                },
                taint: if i == 1 {
                    TaintMeta {
                        labels: smallvec![DataLabel::Source(Cap::ENV_VAR)],
                        ..Default::default()
                    }
                } else {
                    TaintMeta::default()
                },
                call: CallMeta::default(),
                ..Default::default()
            });
            nodes.push(nidx);
        }
        (cfg, nodes)
    }

    fn run_with_pointer(
        body: &SsaBody,
        cfg: &Cfg,
        pf: &crate::pointer::PointsToFacts,
    ) -> SsaTaintState {
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(7),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(pf),
        };

        let mut state = SsaTaintState::initial();
        for inst in &body.blocks[0].body {
            transfer_inst(inst, cfg, body, &transfer, &mut state);
        }
        state
    }

    /// `arr.push(source()); arr.shift()`, the read picks the source's
    /// caps up via the ELEM cell.
    #[test]
    fn container_write_then_read_round_trips_taint() {
        let (cfg, nodes) = cfg_with_nodes(4);
        let n_param = nodes[0];
        let n_source = nodes[1];
        let n_push = nodes[2];
        let n_shift = nodes[3];

        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![
                SsaInst {
                    value: SsaValue(0),
                    op: SsaOp::Param { index: 0 },
                    cfg_node: n_param,
                    var_name: Some("arr".into()),
                    span: (0, 3),
                },
                SsaInst {
                    value: SsaValue(1),
                    op: SsaOp::Source,
                    cfg_node: n_source,
                    var_name: Some("src".into()),
                    span: (10, 15),
                },
                SsaInst {
                    value: SsaValue(2),
                    op: SsaOp::Call {
                        callee: "push".into(),
                        callee_text: None,
                        args: vec![smallvec![SsaValue(1)]],
                        receiver: Some(SsaValue(0)),
                    },
                    cfg_node: n_push,
                    var_name: None,
                    span: (20, 25),
                },
                SsaInst {
                    value: SsaValue(3),
                    op: SsaOp::Call {
                        callee: "shift".into(),
                        callee_text: None,
                        args: vec![],
                        receiver: Some(SsaValue(0)),
                    },
                    cfg_node: n_shift,
                    var_name: Some("e".into()),
                    span: (30, 35),
                },
            ],
            terminator: Terminator::Return(None),
            preds: smallvec![],
            succs: smallvec![],
        }];
        let body = SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("arr".into()),
                    cfg_node: n_param,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("src".into()),
                    cfg_node: n_source,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: None,
                    cfg_node: n_push,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("e".into()),
                    cfg_node: n_shift,
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::default(),
            field_writes: HashMap::new(),

            synthetic_externals: HashSet::new(),
        };

        // Run pointer analysis first to confirm the result of `shift()`
        // includes a `Field(_, ELEM)` member.  The W2 transfer hook
        // populates the cell on `push`; the FieldProj-like read on
        // `shift` then finds the cell on the cross-projection from
        // `analyse_body`.
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(7));
        let pt_shift = pf.pt(SsaValue(3));
        assert!(
            pt_shift.iter().any(|loc| matches!(
                pf.interner.resolve(loc),
                crate::pointer::AbsLoc::Field { field, .. } if *field == FieldId::ELEM
            )),
            "shift result must project through Field(_, ELEM); got {:?}",
            pt_shift,
        );

        // Drive the transfer.  `e := arr.shift()` goes through the
        // existing Call arm, the W2 path is the *write* on `push`.
        // The element-read side already exists on `analyse_body`; the
        // taint engine doesn't yet read field cells through call-result
        // paths (Call args are walked by Call's own argument-taint
        // logic, not field cells), so this test verifies the write
        // populated the cell, not that the call result automatically
        // recovers it through a field cell read.
        let state = run_with_pointer(&body, &cfg, &pf);

        // The push hook must have populated `(pt(arr), ELEM)`.
        let pt_arr = pf.pt(SsaValue(0));
        assert!(!pt_arr.is_empty() && !pt_arr.is_top());
        for loc in pt_arr.iter() {
            let cell = state.get_field(FieldTaintKey {
                loc,
                field: FieldId::ELEM,
            });
            assert!(
                cell.map(|c| c.taint.caps.contains(Cap::ENV_VAR))
                    .unwrap_or(false),
                "ELEM cell on pt(arr) {:?} must carry the source's ENV_VAR cap",
                loc,
            );
        }
    }

    /// W4: `arr.push(validate(src)); arr.shift()`, the push records
    /// `validated_must = true` on the ELEM cell because the pushed
    /// value's symbol carried `validated_must`.  The shift call result
    /// reads through the cell and seeds the result symbol's
    /// `validated_must`.
    ///
    /// This is the fixture that motivated the W4 cell-shape change in
    /// the prompt: `cmd := queue.shift()` after a validated push must
    /// surface the validation on the read.
    #[test]
    fn push_then_shift_preserves_validated_must() {
        let (cfg, nodes) = cfg_with_nodes(4);
        let n_param = nodes[0];
        let n_source = nodes[1];
        let n_push = nodes[2];
        let n_shift = nodes[3];

        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![
                SsaInst {
                    value: SsaValue(0),
                    op: SsaOp::Param { index: 0 },
                    cfg_node: n_param,
                    var_name: Some("arr".into()),
                    span: (0, 3),
                },
                SsaInst {
                    value: SsaValue(1),
                    op: SsaOp::Source,
                    cfg_node: n_source,
                    var_name: Some("src".into()),
                    span: (10, 15),
                },
                SsaInst {
                    value: SsaValue(2),
                    op: SsaOp::Call {
                        callee: "push".into(),
                        callee_text: None,
                        args: vec![smallvec![SsaValue(1)]],
                        receiver: Some(SsaValue(0)),
                    },
                    cfg_node: n_push,
                    var_name: None,
                    span: (20, 25),
                },
                SsaInst {
                    value: SsaValue(3),
                    op: SsaOp::Call {
                        callee: "shift".into(),
                        callee_text: None,
                        args: vec![],
                        receiver: Some(SsaValue(0)),
                    },
                    cfg_node: n_shift,
                    var_name: Some("cmd".into()),
                    span: (30, 35),
                },
            ],
            terminator: Terminator::Return(None),
            preds: smallvec![],
            succs: smallvec![],
        }];
        let body = SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("arr".into()),
                    cfg_node: n_param,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("src".into()),
                    cfg_node: n_source,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: None,
                    cfg_node: n_push,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("cmd".into()),
                    cfg_node: n_shift,
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::default(),
            field_writes: HashMap::new(),

            synthetic_externals: HashSet::new(),
        };

        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(7));

        // Build an interner that knows the relevant variable names.
        let mut interner = SymbolInterner::new();
        let sym_src = interner.intern("src");
        let sym_cmd = interner.intern("cmd");

        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(7),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(&pf),
        };

        // Seed `src` as validated_must before the push fires.
        let mut state = SsaTaintState::initial();
        state.validated_must.insert(sym_src);
        state.validated_may.insert(sym_src);
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }

        // Cell carries validated_must=true after push.
        let pt_arr = pf.pt(SsaValue(0));
        for loc in pt_arr.iter() {
            let cell = state
                .get_field(FieldTaintKey {
                    loc,
                    field: FieldId::ELEM,
                })
                .expect("push must have populated the ELEM cell");
            assert!(
                cell.validated_must,
                "push of must-validated value sets cell.validated_must (loc={:?})",
                loc
            );
        }

        // The W4 read counterpart on `shift` seeded `cmd`'s
        // validated_must from the cell.
        assert!(
            state.validated_must.contains(sym_cmd),
            "shift call result must inherit validated_must from the ELEM cell"
        );
    }

    /// Pointer-disabled run records nothing on container writes.
    #[test]
    fn container_write_pointer_disabled_records_nothing() {
        let (cfg, nodes) = cfg_with_nodes(3);
        let n_param = nodes[0];
        let n_source = nodes[1];
        let n_push = nodes[2];

        let body = SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                phis: vec![],
                body: vec![
                    SsaInst {
                        value: SsaValue(0),
                        op: SsaOp::Param { index: 0 },
                        cfg_node: n_param,
                        var_name: Some("arr".into()),
                        span: (0, 3),
                    },
                    SsaInst {
                        value: SsaValue(1),
                        op: SsaOp::Source,
                        cfg_node: n_source,
                        var_name: Some("src".into()),
                        span: (10, 15),
                    },
                    SsaInst {
                        value: SsaValue(2),
                        op: SsaOp::Call {
                            callee: "push".into(),
                            callee_text: None,
                            args: vec![smallvec![SsaValue(1)]],
                            receiver: Some(SsaValue(0)),
                        },
                        cfg_node: n_push,
                        var_name: None,
                        span: (20, 25),
                    },
                ],
                terminator: Terminator::Return(None),
                preds: smallvec![],
                succs: smallvec![],
            }],
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("arr".into()),
                    cfg_node: n_param,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("src".into()),
                    cfg_node: n_source,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: None,
                    cfg_node: n_push,
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::default(),
            field_writes: HashMap::new(),

            synthetic_externals: HashSet::new(),
        };

        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: None,
        };
        let mut state = SsaTaintState::initial();
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }
        assert!(
            state.field_taint.is_empty(),
            "pointer-disabled container write must not populate field_taint",
        );
    }
}

//── cross-call field-points-to application ────────
//
// `apply_field_points_to_writes` is the resolver-side hook that turns
// callee-summary `field_points_to.param_field_writes` into caller-side
// field_taint cells.  These tests pin the substitution contract:
// param_idx → caller args, u32::MAX → receiver, "<elem>" → ELEM
// sentinel, and unknown field names are skipped.
#[cfg(test)]
mod cross_call_field_tests {
    use super::super::apply_field_points_to_writes;
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::ssa::ir::FieldId;
    use crate::state::symbol::SymbolInterner;
    use crate::summary::points_to::FieldPointsToSummary;
    use crate::taint::domain::{TaintOrigin, VarTaint};
    use crate::taint::ssa_transfer::state::FieldTaintKey;
    use petgraph::graph::NodeIndex;
    use smallvec::smallvec;
    use std::collections::HashMap;

    /// W3 / W4: shared empty interner, these unit tests don't seed
    /// validation bits, so a fresh interner is sufficient for the
    /// `interner` parameter on `apply_field_points_to_writes`.
    fn empty_interner() -> SymbolInterner {
        SymbolInterner::new()
    }

    /// Build a tiny caller body that has one param (`obj`), one source,
    /// and intern's a single field name "cache".  Returns the body, the
    /// `cache` FieldId, and the resulting `PointsToFacts`.
    fn caller_body() -> (SsaBody, FieldId, crate::pointer::PointsToFacts) {
        let mut field_interner = crate::ssa::ir::FieldInterner::default();
        let cache_id = field_interner.intern("cache");
        // We also pre-register a dummy node 0 in CFG.
        let body = SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                phis: vec![],
                body: vec![
                    SsaInst {
                        value: SsaValue(0),
                        op: SsaOp::Param { index: 0 },
                        cfg_node: NodeIndex::new(0),
                        var_name: Some("obj".into()),
                        span: (0, 3),
                    },
                    SsaInst {
                        value: SsaValue(1),
                        op: SsaOp::Source,
                        cfg_node: NodeIndex::new(0),
                        var_name: Some("src".into()),
                        span: (5, 12),
                    },
                ],
                terminator: Terminator::Return(None),
                preds: smallvec![],
                succs: smallvec![],
            }],
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("obj".into()),
                    cfg_node: NodeIndex::new(0),
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("src".into()),
                    cfg_node: NodeIndex::new(0),
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner,
            field_writes: HashMap::new(),

            synthetic_externals: HashSet::new(),
        };
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(7));
        (body, cache_id, pf)
    }

    fn seeded_state() -> SsaTaintState {
        let mut state = SsaTaintState::initial();
        // SsaValue(1) has source taint with ENV_VAR cap.
        state.set(
            SsaValue(1),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![TaintOrigin {
                    node: NodeIndex::new(0),
                    source_kind: crate::labels::SourceKind::EnvironmentConfig,
                    source_span: Some((5, 12)),
                }],
                uses_summary: false,
            },
        );
        state
    }

    /// Callee summary with `param_field_writes[(0, ["cache"])]` ,
    /// "callee writes cache field on parameter 0 (obj)".
    /// Caller passes `(obj, source)` to this callee, `arg 0 = obj`,
    /// but the W3 hook resolves the *value at arg position 0* as the
    /// receiver of the field write, populating its pt's cells.
    ///
    /// We model the caller as `callee(obj, source)` with arg 0 = obj
    /// (the receiver) and arg 1 = source (the value being written).
    /// The callee's signature is `fn store(obj, value) { obj.cache = value; }`
    ///, so the field write on param 0 is keyed by `pt(obj)` and the
    /// taint comes from arg 1's caps.  Our helper conservatively unions
    /// every arg's taint into the cell, which over-tints (for this
    /// shape, arg 0's pt member becomes the loc, with arg 0's own taint
    /// applied), but is sound.
    ///
    /// To make the test precise, we model the simpler shape `fn store(obj)
    /// { obj.cache = source(); }`, callee writes a literal source into
    /// `obj.cache`, with no value parameter.  Then the caller-side hook
    /// only sees param 0's taint (zero), so the cell is empty and the
    /// test fails.
    ///
    /// The cleanest test fixture: param_idx 0 with field "cache", and
    /// at the call site arg 0 carries source taint.  The hook then
    /// records (pt(arg0_value), cache) ← arg0_value's taint.  In a
    /// real callee this corresponds to "callee writes its parameter
    /// value into a self.cache field internally", but the spread we
    /// validate is just substitute-and-mirror.
    #[test]
    fn cross_call_writes_into_param_field_cell() {
        let (body, cache_id, pf) = caller_body();
        let mut state = seeded_state();
        // Caller-side args: arg 0 = source-tainted SSA (SsaValue(1)).
        // The W3 hook reads pt(arg0_v) which traces through pt(SsaValue(1));
        // that value is `Source`, so its pt is empty by design.
        //
        // We need a value whose pt covers an `AbsLoc::Param`.  Use
        // SsaValue(0) (the "obj" Param) as arg 0 *and* seed it with
        // taint manually so the substitution has caps to mirror.
        state.set(
            SsaValue(0),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![TaintOrigin {
                    node: NodeIndex::new(0),
                    source_kind: crate::labels::SourceKind::EnvironmentConfig,
                    source_span: Some((0, 3)),
                }],
                uses_summary: false,
            },
        );

        let mut summary = FieldPointsToSummary::empty();
        summary.add_write(0, "cache");

        let args: Vec<smallvec::SmallVec<[SsaValue; 2]>> = vec![smallvec![SsaValue(0)]];
        let receiver = None;
        apply_field_points_to_writes(
            &summary,
            &args,
            &receiver,
            &mut state,
            &body,
            &pf,
            &empty_interner(),
        );

        // pt(SsaValue(0)) is `{Param(_, 0)}`.
        let pt_v0 = pf.pt(SsaValue(0));
        let loc = pt_v0
            .iter()
            .next()
            .expect("Param value must have non-empty pt");
        let cell = state
            .get_field(FieldTaintKey {
                loc,
                field: cache_id,
            })
            .expect("W3 hook should populate (Param, cache) cell");
        assert!(cell.taint.caps.contains(Cap::ENV_VAR));
    }

    /// Receiver flow uses sentinel `param_idx == u32::MAX`.
    #[test]
    fn cross_call_receiver_field_uses_max_sentinel() {
        let (body, cache_id, pf) = caller_body();
        let mut state = SsaTaintState::initial();
        // Seed receiver with taint, SsaValue(0) is the param/receiver.
        state.set(
            SsaValue(0),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![],
                uses_summary: false,
            },
        );

        let mut summary = FieldPointsToSummary::empty();
        summary.add_write(u32::MAX, "cache");

        let args: Vec<smallvec::SmallVec<[SsaValue; 2]>> = vec![];
        let receiver = Some(SsaValue(0));
        apply_field_points_to_writes(
            &summary,
            &args,
            &receiver,
            &mut state,
            &body,
            &pf,
            &empty_interner(),
        );

        let pt_recv = pf.pt(SsaValue(0));
        let loc = pt_recv.iter().next().unwrap();
        assert!(
            state
                .get_field(FieldTaintKey {
                    loc,
                    field: cache_id
                })
                .is_some()
        );
    }

    /// `<elem>` field name routes to `FieldId::ELEM` directly without
    /// going through interner lookup.
    #[test]
    fn cross_call_elem_marker_routes_to_elem_sentinel() {
        let (body, _cache_id, pf) = caller_body();
        let mut state = SsaTaintState::initial();
        state.set(
            SsaValue(0),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![],
                uses_summary: false,
            },
        );

        let mut summary = FieldPointsToSummary::empty();
        summary.add_write(0, "<elem>");

        let args: Vec<smallvec::SmallVec<[SsaValue; 2]>> = vec![smallvec![SsaValue(0)]];
        apply_field_points_to_writes(
            &summary,
            &args,
            &None,
            &mut state,
            &body,
            &pf,
            &empty_interner(),
        );

        let pt_v0 = pf.pt(SsaValue(0));
        let loc = pt_v0.iter().next().unwrap();
        assert!(
            state
                .get_field(FieldTaintKey {
                    loc,
                    field: FieldId::ELEM
                })
                .is_some(),
            "ELEM cell must be populated when summary uses '<elem>' marker",
        );
    }

    /// Field names the caller never interned are skipped silently ,
    /// no FieldProj read in the caller could observe such a cell.
    #[test]
    fn cross_call_unknown_field_name_skipped() {
        let (body, _cache_id, pf) = caller_body();
        let mut state = SsaTaintState::initial();
        state.set(
            SsaValue(0),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![],
                uses_summary: false,
            },
        );

        let mut summary = FieldPointsToSummary::empty();
        // "unknown" not in caller's field_interner.
        summary.add_write(0, "unknown");

        let args: Vec<smallvec::SmallVec<[SsaValue; 2]>> = vec![smallvec![SsaValue(0)]];
        apply_field_points_to_writes(
            &summary,
            &args,
            &None,
            &mut state,
            &body,
            &pf,
            &empty_interner(),
        );

        assert!(
            state.field_taint.is_empty(),
            "unknown field name must not create a cell",
        );
    }

    /// Overflow summary is treated conservatively as no-op, the
    /// engine cannot soundly cell-flood, so it skips entirely.
    #[test]
    fn cross_call_overflow_summary_is_noop() {
        let (body, _cache_id, pf) = caller_body();
        let mut state = SsaTaintState::initial();
        state.set(
            SsaValue(0),
            VarTaint {
                caps: Cap::ENV_VAR,
                origins: smallvec![],
                uses_summary: false,
            },
        );

        let mut summary = FieldPointsToSummary::empty();
        summary.add_write(0, "cache");
        summary.overflow = true; // Force overflow

        let args: Vec<smallvec::SmallVec<[SsaValue; 2]>> = vec![smallvec![SsaValue(0)]];
        apply_field_points_to_writes(
            &summary,
            &args,
            &None,
            &mut state,
            &body,
            &pf,
            &empty_interner(),
        );
        assert!(state.field_taint.is_empty());
    }

    /// Suppress unused-variable warnings for builders we may not exercise.
    #[test]
    fn ensure_helpers_compile() {
        // Body / source-label imports are used by the other tests; this
        // exists to keep the imports referenced under module-level
        // compile checks even if a single test path is filtered out.
        let _ = NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta::default(),
            taint: TaintMeta {
                labels: smallvec![DataLabel::Source(Cap::ENV_VAR)],
                ..Default::default()
            },
            call: CallMeta::default(),
            ..Default::default()
        };
    }
}

// ── A7 audit: field_taint reads respect the origin cap ─────────────────
//
// `SsaTaintState.add_field` already routes through `merge_origins`, but
// the FieldProj READ path used to walk the cell's origins inline,
// deduping by node only, meaning a cell with N>cap origins surfaced
// all N to the projected SSA value.  After A7, the read path uses
// `push_origin_bounded`, ensuring the cap-driven survivor selection
// applies on read too.
#[cfg(test)]
mod field_taint_origin_cap_tests {
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, Cfg, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::Cap;
    use crate::ssa::ir::FieldId;
    use crate::state::symbol::SymbolInterner;
    use crate::taint::domain::TaintOrigin;
    use crate::taint::ssa_transfer::state::FieldTaintKey;
    use petgraph::graph::NodeIndex;
    use petgraph::prelude::*;
    use smallvec::smallvec;
    use std::collections::HashMap;
    use std::sync::Mutex;

    static TEST_GUARD: Mutex<()> = Mutex::new(());

    /// Build a minimal body with one Param + one FieldProj read on
    /// `obj.cache`, whose cell is pre-populated with > cap origins.
    fn build_body() -> (SsaBody, FieldId, Cfg, NodeIndex) {
        let mut cfg = Graph::new();
        let n_param = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (0, 3),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });
        let n_proj = cfg.add_node(NodeInfo {
            kind: StmtKind::Seq,
            ast: AstMeta {
                span: (5, 12),
                ..Default::default()
            },
            taint: TaintMeta::default(),
            call: CallMeta::default(),
            ..Default::default()
        });

        let mut field_interner = crate::ssa::ir::FieldInterner::default();
        let cache_id = field_interner.intern("cache");
        let body = SsaBody {
            blocks: vec![SsaBlock {
                id: BlockId(0),
                phis: vec![],
                body: vec![
                    SsaInst {
                        value: SsaValue(0),
                        op: SsaOp::Param { index: 0 },
                        cfg_node: n_param,
                        var_name: Some("obj".into()),
                        span: (0, 3),
                    },
                    SsaInst {
                        value: SsaValue(1),
                        op: SsaOp::FieldProj {
                            receiver: SsaValue(0),
                            field: cache_id,
                            projected_type: None,
                        },
                        cfg_node: n_proj,
                        var_name: Some("read".into()),
                        span: (5, 12),
                    },
                ],
                terminator: Terminator::Return(None),
                preds: smallvec![],
                succs: smallvec![],
            }],
            entry: BlockId(0),
            value_defs: vec![
                ValueDef {
                    var_name: Some("obj".into()),
                    cfg_node: n_param,
                    block: BlockId(0),
                },
                ValueDef {
                    var_name: Some("read".into()),
                    cfg_node: n_proj,
                    block: BlockId(0),
                },
            ],
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner,
            field_writes: HashMap::new(),

            synthetic_externals: HashSet::new(),
        };
        (body, cache_id, cfg, n_proj)
    }

    /// Pre-populate the cell with `n` distinct-node origins, then read
    /// through the FieldProj.  Cap is set tight via the test-only
    /// override so we observe truncation.
    #[test]
    fn field_proj_read_respects_origin_cap() {
        let _g = TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::taint::ssa_transfer::state::set_max_origins_override(2);

        let (body, cache_id, cfg, _n_proj) = build_body();
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(0));

        // Pre-populate the (Param, cache) cell with 4 origins ,
        // 2× the cap.  The `add_field` path already truncates via
        // `merge_origins`, so we go through it 4 times to grow.
        let mut state = SsaTaintState::initial();
        let pt_v0 = pf.pt(SsaValue(0));
        let parent_loc = pt_v0.iter().next().unwrap();
        for i in 0..4 {
            let key = FieldTaintKey {
                loc: parent_loc,
                field: cache_id,
            };
            state.add_field(
                key,
                VarTaint {
                    caps: Cap::ENV_VAR,
                    origins: smallvec![TaintOrigin {
                        node: NodeIndex::new(100 + i),
                        source_kind: crate::labels::SourceKind::EnvironmentConfig,
                        source_span: Some((i * 10, i * 10 + 3)),
                    }],
                    uses_summary: false,
                },
                false,
                false,
            );
        }
        // After 4 add_field calls under cap=2, the cell should have ≤ 2
        // origins (merge_origins truncates).
        let cell = state
            .get_field(FieldTaintKey {
                loc: parent_loc,
                field: cache_id,
            })
            .unwrap();
        assert!(
            cell.taint.origins.len() <= 2,
            "field cell origin count must respect cap=2; got {}",
            cell.taint.origins.len(),
        );

        // Run the FieldProj read.  Origin cap on the projected value
        // must also be ≤ 2.
        let interner = SymbolInterner::new();
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner: &interner,
            local_summaries: &local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(0),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(&pf),
        };
        for inst in &body.blocks[0].body {
            transfer_inst(inst, &cfg, &body, &transfer, &mut state);
        }
        let read = state
            .get(SsaValue(1))
            .expect("FieldProj read should produce taint");
        assert!(
            read.origins.len() <= 2,
            "projected SSA value's origin count must respect cap=2; got {}",
            read.origins.len(),
        );

        crate::taint::ssa_transfer::state::set_max_origins_override(0);
    }
}

// ── A2 audit: lattice exercised through full worklist ──────────────────
//
// A8 covered convergence on synthetic states; A2 layers on the
// requirement that the same lattice composes correctly with
// `run_ssa_taint_full`'s multi-block worklist.  These tests build a
// real SSA body with a manually-populated `field_writes` side-table,
// run the full worklist, and assert convergence + flow semantics on
// the field_taint cells.
//
// Two scenarios:
// 1. `must_validated_flows_through_join`, both predecessor blocks
//    write the cell with `validated_must = true`.  After the join, the
//    cell at the read site retains `validated_must = true` (AND
//    intersection of two `true`s).
// 2. `early_exit_branch_drops_validated_must`, only one predecessor
//    writes; the other reaches the read block via an empty branch.
//    After the join, the cell has `validated_must = false`,
//    `validated_may = true`, W4's must/may intersection in action.
#[cfg(test)]
mod pointer_lattice_worklist_tests {
    use super::super::*;
    use crate::cfg::{AstMeta, CallMeta, Cfg, NodeInfo, StmtKind, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::ssa::ir::FieldId;
    use crate::state::symbol::SymbolInterner;
    use crate::taint::ssa_transfer::state::FieldTaintKey;
    use petgraph::graph::NodeIndex;
    use petgraph::prelude::*;
    use smallvec::smallvec;
    use std::collections::HashMap;

    /// Build a CFG with N nodes; node 1 carries a Source label.
    fn cfg_with_nodes(n: usize) -> (Cfg, Vec<NodeIndex>) {
        let mut cfg = Graph::new();
        let mut nodes = Vec::new();
        for i in 0..n {
            let nidx = cfg.add_node(NodeInfo {
                kind: StmtKind::Seq,
                ast: AstMeta {
                    span: (i * 10, i * 10 + 5),
                    ..Default::default()
                },
                taint: if i == 1 {
                    TaintMeta {
                        labels: smallvec![DataLabel::Source(Cap::ENV_VAR)],
                        ..Default::default()
                    }
                } else {
                    TaintMeta::default()
                },
                call: CallMeta::default(),
                ..Default::default()
            });
            nodes.push(nidx);
        }
        (cfg, nodes)
    }

    /// Build a 4-block diamond:
    ///
    /// ```text
    ///    B0  Param(obj), Source(src), synth `obj.cache = src`
    ///   /  \
    ///  B1   B2     (intermediate; populates side-table identically)
    ///   \  /
    ///    B3  FieldProj(obj.cache) → read
    /// ```
    ///
    /// Both predecessors of B3 carry the identical synth field write,
    /// so the joined cell at B3's entry retains the validation
    /// channels.  `seed_validated_must = true` triggers the symbol-
    /// level `src` validation that flows through the W1 hook.
    fn build_diamond_body(seed_validated_must: bool) -> (SsaBody, Cfg, FieldId, SymbolInterner) {
        let (cfg, nodes) = cfg_with_nodes(8);
        let n_param = nodes[0];
        let n_source = nodes[1];
        let n_assign1 = nodes[2];
        let n_assign2 = nodes[3];
        let n_proj = nodes[4];

        let mut field_interner = crate::ssa::ir::FieldInterner::default();
        let cache_id = field_interner.intern("cache");

        // Block 0: param + source (no field write here; the writes
        // are split across B1 and B2).
        let block0 = SsaBlock {
            id: BlockId(0),
            phis: vec![],
            body: vec![
                SsaInst {
                    value: SsaValue(0),
                    op: SsaOp::Param { index: 0 },
                    cfg_node: n_param,
                    var_name: Some("obj".into()),
                    span: (0, 3),
                },
                SsaInst {
                    value: SsaValue(1),
                    op: SsaOp::Source,
                    cfg_node: n_source,
                    var_name: Some("src".into()),
                    span: (10, 15),
                },
            ],
            terminator: Terminator::Goto(BlockId(1)),
            preds: smallvec![],
            succs: smallvec![BlockId(1), BlockId(2)],
        };

        // Block 1: synth `obj.cache = src`, field_writes[v2] = (v0, cache_id)
        let block1 = SsaBlock {
            id: BlockId(1),
            phis: vec![],
            body: vec![SsaInst {
                value: SsaValue(2),
                op: SsaOp::Assign(smallvec![SsaValue(1)]),
                cfg_node: n_assign1,
                var_name: Some("obj".into()),
                span: (20, 30),
            }],
            terminator: Terminator::Goto(BlockId(3)),
            preds: smallvec![BlockId(0)],
            succs: smallvec![BlockId(3)],
        };

        // Block 2: identical synth write, keeps both branches
        // contributing the same cell so AND-intersection of must
        // preserves true on the join.
        let block2 = SsaBlock {
            id: BlockId(2),
            phis: vec![],
            body: vec![SsaInst {
                value: SsaValue(3),
                op: SsaOp::Assign(smallvec![SsaValue(1)]),
                cfg_node: n_assign2,
                var_name: Some("obj".into()),
                span: (40, 50),
            }],
            terminator: Terminator::Goto(BlockId(3)),
            preds: smallvec![BlockId(0)],
            succs: smallvec![BlockId(3)],
        };

        // Block 3: read, FieldProj uses obj from a phi between B1 and B2.
        let block3 = SsaBlock {
            id: BlockId(3),
            phis: vec![SsaInst {
                value: SsaValue(4),
                op: SsaOp::Phi(smallvec![
                    (BlockId(1), SsaValue(2)),
                    (BlockId(2), SsaValue(3)),
                ]),
                cfg_node: n_proj,
                var_name: Some("obj".into()),
                span: (60, 65),
            }],
            body: vec![SsaInst {
                value: SsaValue(5),
                op: SsaOp::FieldProj {
                    receiver: SsaValue(4),
                    field: cache_id,
                    projected_type: None,
                },
                cfg_node: n_proj,
                var_name: Some("read".into()),
                span: (60, 65),
            }],
            terminator: Terminator::Return(None),
            preds: smallvec![BlockId(1), BlockId(2)],
            succs: smallvec![],
        };

        let value_defs = vec![
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_param,
                block: BlockId(0),
            },
            ValueDef {
                var_name: Some("src".into()),
                cfg_node: n_source,
                block: BlockId(0),
            },
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_assign1,
                block: BlockId(1),
            },
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_assign2,
                block: BlockId(2),
            },
            ValueDef {
                var_name: Some("obj".into()),
                cfg_node: n_proj,
                block: BlockId(3),
            },
            ValueDef {
                var_name: Some("read".into()),
                cfg_node: n_proj,
                block: BlockId(3),
            },
        ];

        let mut field_writes = HashMap::new();
        field_writes.insert(SsaValue(2), (SsaValue(0), cache_id));
        field_writes.insert(SsaValue(3), (SsaValue(0), cache_id));

        let body = SsaBody {
            blocks: vec![block0, block1, block2, block3],
            entry: BlockId(0),
            value_defs,
            cfg_node_map: HashMap::new(),
            exception_edges: vec![],
            field_interner,
            field_writes,
            synthetic_externals: HashSet::new(),
        };

        let mut interner = SymbolInterner::new();
        // Pre-intern the names the test cares about.
        let _ = interner.intern("obj");
        let sym_src = interner.intern("src");
        let _ = interner.intern("read");
        // We can't pre-seed `validated_must` on the worklist's entry
        // state from outside, so the must/may semantics here come
        // from the absence of writes on one branch (lattice
        // intersection at the join).  The `seed_validated_must` flag
        // is reserved for future per-block seeding work.
        let _ = (sym_src, seed_validated_must);
        (body, cfg, cache_id, interner)
    }

    fn build_transfer<'a>(
        interner: &'a SymbolInterner,
        local_summaries: &'a FuncSummaries,
        pf: &'a crate::pointer::PointsToFacts,
    ) -> SsaTaintTransfer<'a> {
        SsaTaintTransfer {
            lang: Lang::JavaScript,
            namespace: "",
            interner,
            local_summaries,
            global_summaries: None,
            interop_edges: &[],
            owner_body_id: crate::cfg::BodyId(7),
            parent_body_id: None,
            global_seed: None,
            param_seed: None,
            receiver_seed: None,
            const_values: None,
            type_facts: None,
            ssa_summaries: None,
            extra_labels: None,
            base_aliases: None,
            callee_bodies: None,
            inline_cache: None,
            context_depth: 0,
            callback_bindings: None,
            points_to: None,
            dynamic_pts: None,
            import_bindings: None,
            promisify_aliases: None,
            module_aliases: None,
            static_map: None,
            auto_seed_handler_params: false,
            cross_file_bodies: None,
            pointer_facts: Some(pf),
        }
    }

    /// A2.a: full worklist convergence on the diamond.  Both
    /// predecessor branches write the cell, so the projected SSA
    /// value at B3 carries the source's caps, and `block_states`
    /// shows the cell present at B3's entry but absent at B0's entry.
    #[test]
    fn full_worklist_propagates_field_cell_across_join() {
        let (body, cfg, _cache_id, interner) = build_diamond_body(true);
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(7));
        let local_summaries: FuncSummaries = HashMap::new();
        let transfer = build_transfer(&interner, &local_summaries, &pf);

        let (_events, block_states) =
            crate::taint::ssa_transfer::run_ssa_taint_full(&body, &cfg, &transfer);

        // Block 0's entry state has no field_taint cell yet.
        let b0 = block_states[0]
            .as_ref()
            .expect("block 0 entry state present");
        assert!(
            b0.field_taint.is_empty(),
            "B0 entry must have no field_taint cells yet; got {:?}",
            b0.field_taint
        );

        // Block 3's entry state carries the cell after the join.
        let b3 = block_states[3]
            .as_ref()
            .expect("block 3 entry state present");
        let pt_v0 = pf.pt(SsaValue(0));
        assert!(!pt_v0.is_empty() && !pt_v0.is_top());
        let parent_loc = pt_v0.iter().next().unwrap();
        let cell = b3.get_field(FieldTaintKey {
            loc: parent_loc,
            field: _cache_id,
        });
        assert!(
            cell.is_some(),
            "B3 entry must contain (Param(_,0), cache) cell after diamond join; got {:?}",
            b3.field_taint
        );
        let cell = cell.unwrap();
        assert!(
            cell.taint.caps.contains(Cap::ENV_VAR),
            "joined cell must carry the Source's ENV_VAR cap"
        );
    }

    /// A2.b: early-exit branch, only B1 writes, B2 reaches B3 via
    /// an empty body.  After the join, the cell exists (B1 wrote
    /// it), but `validated_must` is `false` (B2 didn't write, the
    /// orphan-side merge clears `must` per the W4 lattice rule);
    /// `validated_may` is preserved on the writer's side via OR.
    ///
    /// To exercise the validation channels we synthesise the cell
    /// directly at the appropriate exit state, then run the
    /// worklist's join via two `SsaTaintState::join()` calls, the
    /// body's worklist itself doesn't seed `validated_must` on the
    /// rhs of an Assign, so we model the "writer recorded must=true"
    /// scenario at the lattice level rather than driving it through
    /// transfer_inst.
    #[test]
    fn early_exit_branch_drops_validated_must_on_join() {
        let (body, _cfg, _cache_id, _interner) = build_diamond_body(false);
        let pf = crate::pointer::analyse_body(&body, crate::cfg::BodyId(7));
        let pt_v0 = pf.pt(SsaValue(0));
        let parent_loc = pt_v0.iter().next().unwrap();

        // Predecessor 1: cell with validated_must=true, validated_may=true.
        let mut pred1 = SsaTaintState::initial();
        pred1.add_field(
            FieldTaintKey {
                loc: parent_loc,
                field: _cache_id,
            },
            crate::taint::domain::VarTaint {
                caps: Cap::ENV_VAR,
                origins: SmallVec::new(),
                uses_summary: false,
            },
            true,
            true,
        );

        // Predecessor 2: empty (no cell).
        let pred2 = SsaTaintState::initial();

        // Worklist join semantics.
        let joined = pred1.join(&pred2);
        let cell = joined
            .get_field(FieldTaintKey {
                loc: parent_loc,
                field: _cache_id,
            })
            .expect("cell present on the writer's side");
        assert!(
            !cell.validated_must,
            "join with empty side must clear validated_must (orphan rule)"
        );
        assert!(
            cell.validated_may,
            "validated_may from the writer's side survives the join"
        );
        assert!(cell.taint.caps.contains(Cap::ENV_VAR));
    }
}