nyx-scanner 0.6.1

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

use crate::cfg::{Cfg, EdgeKind, StmtKind};
use petgraph::algo::dominators::{Dominators, simple_fast};
use petgraph::graph::NodeIndex;
use petgraph::prelude::*;
use petgraph::visit::EdgeRef;
use smallvec::SmallVec;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};

use super::ir::*;

/// Try to decompose a chained-receiver method call (e.g. `a.b.c.method`)
/// into a `FieldProj` chain plus a bare-method `Call`.
///
/// **Returns** `Some((final_receiver_value, bare_method_name))` on success,
/// `None` to fall back to the existing single-Call lowering (current
/// behaviour).
///
/// On success, the caller should:
///   - Construct the `Call` op with `callee = bare_method_name`,
///     `callee_text = Some(original_callee.to_string())`,
///     `receiver = Some(final_receiver_value)`.
///   - Use the returned receiver as the implicit method receiver, do NOT
///     add the chain root or any intermediate field name to `args`.
///
/// **Decomposition rules**:
///   - Skip when the callee contains zero `.` characters (no member access)
///     or only one `.` (single-dot case is handled by the existing
///     `info.call.receiver` channel without needing a `FieldProj` op).
///   - Bail when any "complex" token appears in the callee, `(`, `)`,
///     `[`, `]`, `::`, `->`, `?`, `<`, `>`, `*`, `&`, `:` (other than `::`
///     already filtered), or whitespace, signaling the callee text isn't
///     a clean `<ident>.<ident>...` chain we can safely split on `.`.
///   - The first segment must be a known SSA variable in `var_stacks`;
///     otherwise the chain root is unresolvable and we bail.
///   - Each intermediate segment becomes a `FieldProj { receiver, field }`
///     instruction emitted onto `block.body` with a fresh `SsaValue`.
///   - The last segment is the bare method name returned to the caller.
///
/// FieldProj instructions are tagged with `var_name = Some("base.f1.f2")`
/// so debug output and downstream consumers that key on `var_name` can
/// recognise the projection chain provenance.
#[allow(clippy::too_many_arguments)]
fn try_lower_field_proj_chain(
    callee: &str,
    var_stacks: &HashMap<String, Vec<SsaValue>>,
    field_interner: &mut crate::ssa::ir::FieldInterner,
    block_idx: usize,
    block_id: BlockId,
    next_value: &mut u32,
    ssa_blocks: &mut [SsaBlock],
    value_defs: &mut Vec<ValueDef>,
    cfg_node: NodeIndex,
    span: (usize, usize),
) -> Option<(SsaValue, String)> {
    // Bail on any token that signals a complex callee expression.
    // `::` (Rust/C++ paths) is folded into the broader `:` check.
    for ch in callee.chars() {
        match ch {
            '(' | ')' | '[' | ']' | '<' | '>' | '?' | '*' | '&' | ':' | ' ' | '\t' | '\n' | '-'
            | '!' | ',' | ';' | '"' | '\'' | '\\' => return None,
            _ => {}
        }
    }
    let segments: Vec<&str> = callee.split('.').collect();
    // Need at least 3 segments: `base.field.method` → 1 FieldProj, 1 Call.
    if segments.len() < 3 {
        return None;
    }
    // Reject empty segments (would happen on leading/trailing/double dots).
    if segments.iter().any(|s| s.is_empty()) {
        return None;
    }

    let base = segments[0];
    let mut current = *var_stacks.get(base).and_then(|s| s.last())?;
    let mut chain_var = base.to_string();

    // Each intermediate segment becomes a FieldProj op.  segments[0] is the
    // base SSA variable, segments[len-1] is the bare method name.
    for field_name in &segments[1..segments.len() - 1] {
        let fid = field_interner.intern(field_name);
        let v = SsaValue(*next_value);
        *next_value += 1;
        chain_var.push('.');
        chain_var.push_str(field_name);
        ssa_blocks[block_idx].body.push(SsaInst {
            value: v,
            op: SsaOp::FieldProj {
                receiver: current,
                field: fid,
                projected_type: None,
            },
            cfg_node,
            var_name: Some(chain_var.clone()),
            span,
        });
        value_defs.push(ValueDef {
            var_name: Some(chain_var.clone()),
            cfg_node,
            block: block_id,
        });
        current = v;
    }

    let method = segments.last().unwrap().to_string();
    Some((current, method))
}

/// Lower a CFG to SSA form for a single function scope.
///
/// `scope` filters nodes by `enclosing_func`:
///   - `None` → top-level code only (`enclosing_func.is_none()`)
///   - `Some(name)` → only nodes with `enclosing_func == Some(name)`
///
/// If `scope_all` is true, all nodes reachable from `entry` are included
/// regardless of `enclosing_func`.
pub fn lower_to_ssa(
    cfg: &Cfg,
    entry: NodeIndex,
    scope: Option<&str>,
    scope_all: bool,
) -> Result<SsaBody, SsaError> {
    lower_to_ssa_inner(cfg, entry, scope, scope_all, false, &[], false)
}

/// Like `lower_to_ssa` but with formal parameter names supplied in declaration
/// order. External variables that match these names are placed first (in
/// declaration order) so that `Param { index }` indices 0..N correspond to
/// call-site argument positions.
pub fn lower_to_ssa_with_params(
    cfg: &Cfg,
    entry: NodeIndex,
    scope: Option<&str>,
    scope_all: bool,
    formal_params: &[String],
) -> Result<SsaBody, SsaError> {
    // `with_params=true` signals "callers supplied an explicit formal list,
    // even if empty" (e.g. arrow `() => {…}` has zero formals).  This lets
    // the synthetic-externals classifier distinguish "no formals info" from
    // "explicit empty formals" — closure captures of an arrow with empty
    // formals are still synthetic, not formals.  Bug surfaced on outline's
    // jest test files: free vars bubbled up from nested arrow callbacks
    // (`body`, `userId`, `server.post`) became Params at the outer arrow's
    // entry, and the JS/TS auto-seed treated `userId` as a real handler
    // formal, producing 934 phantom taint findings.  See
    // `taint/ssa_transfer/mod.rs::auto_seed_handler_params`.
    lower_to_ssa_inner(cfg, entry, scope, scope_all, false, formal_params, true)
}

/// Like `lower_to_ssa` but with `scope_nop`: when true, all nodes are included
/// in the SSA body for graph connectivity, but out-of-scope nodes become Nop
/// (their defines/uses are ignored). This is used for the JS two-level solve
/// where the CFG linearizes function bodies inline.
pub fn lower_to_ssa_scoped_nop(
    cfg: &Cfg,
    entry: NodeIndex,
    scope: Option<&str>,
) -> Result<SsaBody, SsaError> {
    lower_to_ssa_inner(cfg, entry, scope, false, true, &[], false)
}

fn lower_to_ssa_inner(
    cfg: &Cfg,
    entry: NodeIndex,
    scope: Option<&str>,
    scope_all: bool,
    scope_nop: bool,
    formal_params: &[String],
    with_params: bool,
) -> Result<SsaBody, SsaError> {
    if cfg.node_count() == 0 {
        return Err(SsaError::EmptyCfg);
    }

    // When scope_nop is set, traverse all nodes (scope_all=true) for graph connectivity
    let traverse_all = scope_all || scope_nop;

    // Collect reachable nodes in scope, stripping exception edges.
    let (reachable, filtered_edges, raw_exception_edges) =
        collect_reachable(cfg, entry, scope, traverse_all);

    // Build the set of nodes that should be treated as Nop (out-of-scope but included)
    let nop_nodes: HashSet<NodeIndex> = if scope_nop {
        let in_scope = |node: NodeIndex| -> bool {
            let info = &cfg[node];
            match scope {
                None => info.ast.enclosing_func.is_none(),
                Some(name) => info.ast.enclosing_func.as_deref() == Some(name),
            }
        };
        reachable
            .iter()
            .filter(|&&n| !in_scope(n) && !matches!(cfg[n].kind, StmtKind::Entry | StmtKind::Exit))
            .copied()
            .collect()
    } else {
        HashSet::new()
    };
    if reachable.is_empty() {
        return Err(SsaError::EmptyCfg);
    }

    // 1. Form basic blocks
    let (blocks_nodes, block_of_node, block_succs, block_preds) =
        form_blocks(cfg, entry, &reachable, &filtered_edges);

    let num_blocks = blocks_nodes.len();
    if num_blocks == 0 {
        return Err(SsaError::EmptyCfg);
    }

    // 2. Compute dominators on block-level graph
    let (block_graph, block_graph_entry) = build_block_graph(num_blocks, &block_succs, BlockId(0));
    let doms = simple_fast(&block_graph, block_graph_entry);

    // 3. Compute dominance frontiers
    let dom_frontiers = compute_dominance_frontiers(num_blocks, &block_preds, &doms, &block_graph);

    // 4. Collect variable definitions per block (skip nop nodes)
    let mut var_defs = collect_var_defs(cfg, &blocks_nodes, &nop_nodes);

    // 4b. For per-function scope: identify external variables (used but not defined)
    //     and inject synthetic Param defs at entry block so rename can find them.
    //     When formal_params is supplied, reorder so formal params come first in
    //     declaration order, this makes Param indices correspond to call-site positions.
    //
    let external_vars = if scope.is_some() && !scope_all && !scope_nop {
        let raw = identify_external_uses(cfg, &blocks_nodes, &var_defs);
        reorder_external_vars(raw, formal_params)
    } else {
        vec![]
    };
    // Register external vars as defined in block 0 so phi insertion considers them
    for var in &external_vars {
        var_defs.entry(var.clone()).or_default().insert(0);
    }

    // 5. Phi insertion (Cytron algorithm)
    let phi_placements = insert_phis(&var_defs, &dom_frontiers, num_blocks);

    // 6. Rename variables (dominator tree preorder walk)
    let dom_tree_children = build_dom_tree_children(num_blocks, &doms, &block_graph);
    let (
        mut ssa_blocks,
        mut value_defs,
        cfg_node_map,
        field_interner,
        field_writes,
        synthetic_externals,
    ) = rename_variables(
        cfg,
        &blocks_nodes,
        &block_succs,
        &block_preds,
        &phi_placements,
        &dom_tree_children,
        &filtered_edges,
        &external_vars,
        formal_params,
        with_params,
        &nop_nodes,
    );

    // 6b. Fill any missing phi operands with a shared Undef sentinel so
    // every phi has exactly one operand per predecessor. See
    // `fill_undef_phi_operands` for the invariant rationale.
    fill_undef_phi_operands(
        &mut ssa_blocks,
        &block_preds,
        &mut value_defs,
        &blocks_nodes,
    );

    // 7. Fill in preds/succs on SsaBlocks
    for bid in 0..num_blocks {
        let id = BlockId(bid as u32);
        ssa_blocks[bid].id = id;
        ssa_blocks[bid].preds = block_preds[bid]
            .iter()
            .map(|&b| BlockId(b as u32))
            .collect();
        ssa_blocks[bid].succs = block_succs[bid]
            .iter()
            .map(|&b| BlockId(b as u32))
            .collect();
    }

    // 7b. Debug assertions: verify structural invariants.
    // The helper body is `debug_assert!` only, so it's a no-op in release ,
    // call unconditionally to avoid a dead_code warning when the lib is
    // built without `--tests`.
    debug_assert_bfs_ordering(&block_preds);
    // Phi operand counts are a release-level invariant: every phi must
    // have exactly one operand per predecessor. Missing operands are
    // filled with an explicit Undef sentinel in
    // `fill_undef_phi_operands`; extra operands would reference
    // nonexistent predecessors and corrupt analysis silently.
    assert_phi_operand_counts(&ssa_blocks, &block_preds);

    // 8. Map exception edges from CFG node indices to SSA block IDs
    let exception_edges: Vec<(BlockId, BlockId)> = raw_exception_edges
        .iter()
        .filter_map(|(src_node, catch_node)| {
            let src_block = block_of_node.get(src_node)?;
            let catch_block = block_of_node.get(catch_node)?;
            Some((BlockId(*src_block as u32), BlockId(*catch_block as u32)))
        })
        .collect();

    let body = SsaBody {
        blocks: ssa_blocks,
        entry: BlockId(0),
        value_defs,
        cfg_node_map,
        exception_edges,
        field_interner,
        field_writes,
        synthetic_externals,
    };

    // 9. Catch-block reachability invariant.
    //
    // A CatchParam-carrying block that is neither reachable from entry nor
    // listed as an exception target indicates a CFG construction bug. Debug
    // builds panic loudly; release builds warn, record an engine note so
    // downstream findings carry "SSA lowering bailed" provenance, and fall
    // through to the existing orphan handling above (the "all definitions"
    // fallback) which remains sound for taint reachability.
    check_catch_block_reachability_gated(&body);

    Ok(body)
}

/// Runtime gate around [`check_catch_block_reachability`] that panics in
/// debug builds and warns + records an engine note in release builds.
///
/// The current lowering's orphan handling (`process_block` fallback in
/// `rename_variables`) already widens to an "all definitions" conservative
/// state for blocks without predecessors. That preserves soundness for
/// taint reachability but masks CFG-builder bugs: this gate surfaces them.
fn check_catch_block_reachability_gated(body: &SsaBody) {
    let result = super::invariants::check_catch_block_reachability(body);
    if let Err(err) = result {
        #[cfg(debug_assertions)]
        {
            if !catch_invariant_do_not_panic() {
                panic!(
                    "SSA catch-block reachability invariant violated:\n{}",
                    err.joined()
                );
            }
        }
        tracing::warn!(
            violations = %err.joined(),
            "SSA catch-block reachability invariant violated; proceeding with \
             conservative orphan fallback"
        );
        crate::taint::ssa_transfer::record_engine_note(
            crate::engine_notes::EngineNote::SsaLoweringBailed {
                reason: format!("catch_block_orphan: {}", err.joined()),
            },
        );
    }
}

// Test-only escape hatch: when set, `check_catch_block_reachability_gated`
// takes the release-build path (warn + engine note, no panic) even under
// `debug_assertions`. Used by the invariant test that constructs a
// synthetic orphan catch body.
#[cfg(debug_assertions)]
thread_local! {
    static CATCH_INVARIANT_DO_NOT_PANIC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

#[cfg(debug_assertions)]
#[allow(dead_code)]
pub(crate) fn set_catch_invariant_do_not_panic(on: bool) {
    CATCH_INVARIANT_DO_NOT_PANIC.with(|c| c.set(on));
}

#[cfg(debug_assertions)]
fn catch_invariant_do_not_panic() -> bool {
    CATCH_INVARIANT_DO_NOT_PANIC.with(|c| c.get())
}

/// Collect reachable nodes (BFS from entry), filtering by scope and stripping exception edges.
/// Returns (reachable set, filtered edges, exception edges as (src_node, catch_node)).
fn collect_reachable(
    cfg: &Cfg,
    entry: NodeIndex,
    scope: Option<&str>,
    scope_all: bool,
) -> (
    HashSet<NodeIndex>,
    Vec<(NodeIndex, NodeIndex, EdgeKind)>,
    Vec<(NodeIndex, NodeIndex)>,
) {
    let mut reachable = HashSet::new();
    let mut edges = Vec::new();
    let mut exception_edges = Vec::new();
    let mut queue = VecDeque::new();

    // Check if a node is in scope
    let in_scope = |node: NodeIndex| -> bool {
        if scope_all {
            return true;
        }
        let info = &cfg[node];
        match scope {
            None => info.ast.enclosing_func.is_none(),
            Some(name) => info.ast.enclosing_func.as_deref() == Some(name),
        }
    };

    if !in_scope(entry) && !scope_all {
        // Entry must be in scope; for top-level, Entry node often has no enclosing_func
        // Accept Entry/Exit nodes regardless of scope
        if !matches!(cfg[entry].kind, StmtKind::Entry | StmtKind::Exit) {
            return (reachable, edges, exception_edges);
        }
    }

    reachable.insert(entry);
    queue.push_back(entry);

    while let Some(node) = queue.pop_front() {
        for edge in cfg.edges(node) {
            let kind = *edge.weight();
            let target = edge.target();

            // Strip exception edges from the graph, but still visit targets
            // so catch-block nodes are included in the SSA body.
            if matches!(kind, EdgeKind::Exception) {
                if (in_scope(target)
                    || matches!(cfg[target].kind, StmtKind::Entry | StmtKind::Exit))
                    && reachable.insert(target)
                {
                    queue.push_back(target);
                }
                // Record exception edge for taint seeding
                exception_edges.push((node, target));
                continue;
            }

            // Allow Entry/Exit nodes and nodes in scope
            if !in_scope(target) && !matches!(cfg[target].kind, StmtKind::Entry | StmtKind::Exit) {
                continue;
            }

            edges.push((node, target, kind));

            if reachable.insert(target) {
                queue.push_back(target);
            }
        }
    }

    (reachable, edges, exception_edges)
}

/// Form basic blocks from filtered CFG nodes.
///
/// Returns:
/// - blocks_nodes: Vec<Vec<NodeIndex>>, nodes per block (in order)
/// - block_of_node: HashMap<NodeIndex, usize>, node → block index
/// - block_succs: Vec<Vec<usize>>, successors per block
/// - block_preds: Vec<Vec<usize>>, predecessors per block
fn form_blocks(
    cfg: &Cfg,
    entry: NodeIndex,
    reachable: &HashSet<NodeIndex>,
    filtered_edges: &[(NodeIndex, NodeIndex, EdgeKind)],
) -> (
    Vec<Vec<NodeIndex>>,
    HashMap<NodeIndex, usize>,
    Vec<Vec<usize>>,
    Vec<Vec<usize>>,
) {
    // Build adjacency from filtered edges
    let mut successors: HashMap<NodeIndex, Vec<(NodeIndex, EdgeKind)>> = HashMap::new();
    let mut in_degree: HashMap<NodeIndex, usize> = HashMap::new();
    let mut has_branching_in: HashMap<NodeIndex, bool> = HashMap::new();

    for node in reachable {
        in_degree.entry(*node).or_insert(0);
        has_branching_in.entry(*node).or_insert(false);
    }

    // CFG construction wires every Return / Throw node to the synthetic
    // function-exit node via a `Seq` edge so the underlying graph is a single
    // connected component.  Those edges are bookkeeping only: control flow
    // does not actually fall through a Return into the exit block.  Treating
    // them as block successors causes an early-return block to share its
    // post-exit body with the function's fall-through tail, silently merging
    // two distinct paths into one (the "merged-return" defect).  Strip them
    // here so block-level adjacency reflects real control flow; the SSA
    // terminator for the containing block becomes Return / Unreachable
    // instead of Goto(exit).
    let is_terminating =
        |n: NodeIndex| -> bool { matches!(cfg[n].kind, StmtKind::Return | StmtKind::Throw) };

    for &(src, tgt, kind) in filtered_edges {
        if is_terminating(src) {
            continue;
        }
        successors.entry(src).or_default().push((tgt, kind));
        *in_degree.entry(tgt).or_insert(0) += 1;
        if matches!(kind, EdgeKind::True | EdgeKind::False | EdgeKind::Back) {
            *has_branching_in.entry(tgt).or_insert(false) = true;
        }
    }

    // Determine block leaders
    let mut is_leader: HashSet<NodeIndex> = HashSet::new();
    is_leader.insert(entry); // entry is always a leader

    for &node in reachable {
        let in_deg = in_degree.get(&node).copied().unwrap_or(0);
        if in_deg > 1 || has_branching_in.get(&node).copied().unwrap_or(false) {
            is_leader.insert(node);
        }
        // Orphan nodes (reachable via exception edges but no filtered predecessors)
        // must be leaders so they get their own block (e.g. catch block entries).
        if in_deg == 0 && node != entry {
            is_leader.insert(node);
        }
        // Node following a multi-exit node
        let succs = successors.get(&node).map(|s| s.len()).unwrap_or(0);
        if succs > 1 {
            for &(tgt, _) in successors.get(&node).unwrap_or(&vec![]) {
                is_leader.insert(tgt);
            }
        }
    }

    // Build blocks by following single-successor Seq edges from each leader
    let mut blocks_nodes: Vec<Vec<NodeIndex>> = Vec::new();
    let mut block_of_node: HashMap<NodeIndex, usize> = HashMap::new();
    let mut visited: HashSet<NodeIndex> = HashSet::new();

    // BFS order to assign blocks deterministically (entry first)
    let mut leader_queue: VecDeque<NodeIndex> = VecDeque::new();
    leader_queue.push_back(entry);
    let mut leader_visited: HashSet<NodeIndex> = HashSet::new();
    leader_visited.insert(entry);

    // Discover leaders in BFS order over `cfg`, but skip edges whose
    // source is a terminating (Return / Throw) node.  Walking the raw
    // `cfg` directly here would re-introduce the bookkeeping
    // Return/Throw → fn_exit edges we just stripped, fn_exit (or any
    // post-return join) would be discovered through them and assigned a
    // block ID before its true block-level predecessors, breaking the
    // BFS-forward-pred invariant (`debug_assert_bfs_ordering`).
    //
    // We can't simply BFS our `successors` map because that excludes
    // exception edges entirely (collect_reachable strips them and records
    // them separately in `exception_edges`).  Catch-block nodes are still
    // in `reachable` and must be discoverable as leaders via the
    // try-body → catch path, only the terminating-source bookkeeping
    // edges are bogus.
    {
        let mut bfs_queue: VecDeque<NodeIndex> = VecDeque::new();
        let mut bfs_seen: HashSet<NodeIndex> = HashSet::new();
        bfs_queue.push_back(entry);
        bfs_seen.insert(entry);
        while let Some(node) = bfs_queue.pop_front() {
            if reachable.contains(&node) && is_leader.contains(&node) && leader_visited.insert(node)
            {
                leader_queue.push_back(node);
            }
            if is_terminating(node) {
                continue;
            }
            for edge in cfg.edges(node) {
                let tgt = edge.target();
                if reachable.contains(&tgt) && bfs_seen.insert(tgt) {
                    bfs_queue.push_back(tgt);
                }
            }
        }

        // Belt-and-braces: any leader still unvisited gets appended in
        // CFG-node-index order so block-ID assignment remains
        // deterministic.  We do NOT include the synthetic function-exit
        // node when it is unreachable through filtered edges, that
        // happens whenever every path in the body terminates explicitly
        // (e.g. a function whose only return is `return buf.toString()`
        // at the tail).  Including it would emit an orphan SSA block
        // with no real predecessors and no semantic meaning, which the
        // structural reachability invariant correctly rejects.
        // Genuine orphan handlers (catch blocks reached via stripped
        // exception edges) keep their entries here.
        let mut orphan_leaders: Vec<NodeIndex> = is_leader
            .iter()
            .copied()
            .filter(|n| !leader_visited.contains(n))
            .filter(|n| !matches!(cfg[*n].kind, StmtKind::Exit))
            .collect();
        orphan_leaders.sort_by_key(|n| n.index());
        for n in orphan_leaders {
            if leader_visited.insert(n) {
                leader_queue.push_back(n);
            }
        }
    }

    for leader in leader_queue {
        if visited.contains(&leader) {
            continue;
        }

        let block_idx = blocks_nodes.len();
        let mut block = vec![leader];
        visited.insert(leader);
        block_of_node.insert(leader, block_idx);

        // Follow single-successor Seq edges
        let mut current = leader;
        loop {
            let succs = successors.get(&current).cloned().unwrap_or_default();
            if succs.len() == 1
                && matches!(succs[0].1, EdgeKind::Seq)
                && !is_leader.contains(&succs[0].0)
            {
                let next = succs[0].0;
                if visited.insert(next) {
                    block.push(next);
                    block_of_node.insert(next, block_idx);
                    current = next;
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        blocks_nodes.push(block);
    }

    // Build block-level successor/predecessor lists
    let num_blocks = blocks_nodes.len();
    let mut block_succs: Vec<Vec<usize>> = vec![vec![]; num_blocks];
    let mut block_preds: Vec<Vec<usize>> = vec![vec![]; num_blocks];

    for &(src, tgt, _kind) in filtered_edges {
        // Mirror the adjacency-construction filter above: edges out of
        // Return/Throw CFG nodes are not real successors at the block level.
        if is_terminating(src) {
            continue;
        }
        if let (Some(&src_blk), Some(&tgt_blk)) = (block_of_node.get(&src), block_of_node.get(&tgt))
        {
            if src_blk != tgt_blk && !block_succs[src_blk].contains(&tgt_blk) {
                block_succs[src_blk].push(tgt_blk);
                block_preds[tgt_blk].push(src_blk);
            }
        }
    }

    (blocks_nodes, block_of_node, block_succs, block_preds)
}

/// Build a block-level petgraph for dominator computation.
fn build_block_graph(
    num_blocks: usize,
    block_succs: &[Vec<usize>],
    _entry: BlockId,
) -> (Graph<BlockId, ()>, NodeIndex) {
    let mut g: Graph<BlockId, ()> = Graph::new();
    let mut block_nodes: Vec<NodeIndex> = Vec::with_capacity(num_blocks);

    for i in 0..num_blocks {
        block_nodes.push(g.add_node(BlockId(i as u32)));
    }

    for (i, succs) in block_succs.iter().enumerate() {
        for &s in succs {
            g.add_edge(block_nodes[i], block_nodes[s], ());
        }
    }

    let entry_gnode = block_nodes[0]; // block 0 is always entry
    (g, entry_gnode)
}

/// Compute dominance frontiers for all blocks.
fn compute_dominance_frontiers(
    num_blocks: usize,
    block_preds: &[Vec<usize>],
    doms: &Dominators<NodeIndex>,
    block_graph: &Graph<BlockId, ()>,
) -> Vec<HashSet<usize>> {
    let mut df: Vec<HashSet<usize>> = vec![HashSet::new(); num_blocks];

    // Map block index → graph NodeIndex
    let block_node: Vec<NodeIndex> = block_graph.node_indices().collect();

    for n in 0..num_blocks {
        let preds = &block_preds[n];
        if preds.len() >= 2 {
            for &p in preds {
                let mut runner = p;
                // idom(n) in the block graph
                let n_gnode = block_node[n];
                let idom_n = doms.immediate_dominator(n_gnode);
                loop {
                    let runner_gnode = block_node[runner];
                    if idom_n == Some(runner_gnode) {
                        break;
                    }
                    df[runner].insert(n);
                    // Move runner to its immediate dominator
                    match doms.immediate_dominator(runner_gnode) {
                        Some(idom_runner) if idom_runner != runner_gnode => {
                            // Find block index from graph node
                            runner = block_graph[idom_runner].0 as usize;
                        }
                        _ => break, // reached root
                    }
                }
            }
        }
    }

    df
}

/// Identify variables used but not defined within the scoped blocks.
/// These represent external (e.g. global/top-level) variables that need
/// synthetic Param instructions so the SSA rename pass can reference them.
fn identify_external_uses(
    cfg: &Cfg,
    blocks_nodes: &[Vec<NodeIndex>],
    var_defs: &BTreeMap<String, HashSet<usize>>,
) -> Vec<String> {
    let mut used: HashSet<String> = HashSet::new();
    for nodes in blocks_nodes {
        for &node in nodes {
            for u in &cfg[node].taint.uses {
                used.insert(u.clone());
            }
        }
    }
    // External = used but never defined in any block
    let mut external: Vec<String> = used
        .into_iter()
        .filter(|u| !var_defs.contains_key(u))
        .collect();
    external.sort(); // deterministic order
    external
}

/// True iff `name` is a language-reserved method receiver identifier
/// (Rust/Python `self`, JS/TS/Java/PHP/C++ `this`).
///
/// Receivers get their own IR node ([`SsaOp::SelfParam`]) and are therefore
/// tracked as a distinct channel from positional parameters.  Keeping the
/// check localised to one helper ensures the set of receiver names stays
/// consistent across lowering and summary extraction.
pub(crate) fn is_receiver_name(name: &str) -> bool {
    matches!(name, "self" | "this")
}

/// Reorder external variables so the receiver (`self`/`this`) comes first,
/// followed by formal positional parameters in declaration order, followed
/// by remaining external vars in alphabetical order.
///
/// This fixed order is what the synthetic-parameter injection step relies
/// on to emit one [`SsaOp::SelfParam`] (for the leading receiver slot, when
/// present) followed by a contiguous run of [`SsaOp::Param { index }`] values
/// whose indices 0..N correspond exactly to positional call-site argument
/// positions, no receiver offset required anywhere downstream.
///
/// W1.b: every formal parameter gets a Param op even when the body never
/// references it directly.  Without this, the *first* `obj.f = rhs` on a
/// formal `obj` whose body never reads `obj` produces no W1
/// `field_writes` entry, `var_stacks["obj"]` is empty when the synth
/// Assign runs because no external-use path interned `obj`.  Subsequent
/// writes work because the synth Assign itself defines `obj`, so the
/// gap is exactly the FIRST write.  Always emitting a formal Param at
/// block 0 closes that gap.
fn reorder_external_vars(external: Vec<String>, formal_params: &[String]) -> Vec<String> {
    if formal_params.is_empty() {
        return external; // no reordering, preserve existing alphabetical sort
    }
    let ext_set: HashSet<&str> = external.iter().map(|s| s.as_str()).collect();
    let formal_set: HashSet<&str> = formal_params.iter().map(|s| s.as_str()).collect();
    let mut result = Vec::with_capacity(external.len());
    // Receiver first (highest priority), regardless of whether it appears in
    // formal_params or was discovered purely as an external reference.
    // Languages with explicit self (Rust/Python) put it in formal_params;
    // languages with implicit this (JS/TS/Java/PHP) have it only as an
    // external reference.  Either way, SelfParam should be emitted first.
    if ext_set.contains("self") || formal_set.contains("self") {
        result.push("self".to_string());
    } else if ext_set.contains("this") || formal_set.contains("this") {
        result.push("this".to_string());
    }
    // Formal positional params next (declaration order), skipping any
    // receiver that was already emitted above.  W1.b: include EVERY
    // formal regardless of whether the body uses it externally, an
    // unused formal that gets field-written via `obj.cache = rhs` still
    // needs a Param op so the synth Assign loop sees its prior reaching
    // def in `var_stacks`.
    for p in formal_params {
        if is_receiver_name(p) {
            continue;
        }
        result.push(p.clone());
    }
    // Remaining external vars alphabetically (external is already sorted),
    // excluding anything already placed.
    let placed: HashSet<String> = result.iter().cloned().collect();
    for v in external {
        if placed.contains(&v) {
            continue;
        }
        if !formal_set.contains(v.as_str()) && !is_receiver_name(&v) {
            result.push(v);
        }
    }
    result
}

/// Collect variable definitions per block: var_name → set of block indices.
/// Nodes in `nop_nodes` are skipped (they won't define variables in SSA).
fn collect_var_defs(
    cfg: &Cfg,
    blocks_nodes: &[Vec<NodeIndex>],
    nop_nodes: &HashSet<NodeIndex>,
) -> BTreeMap<String, HashSet<usize>> {
    let mut defs: BTreeMap<String, HashSet<usize>> = BTreeMap::new();

    for (block_idx, nodes) in blocks_nodes.iter().enumerate() {
        for &node in nodes {
            if nop_nodes.contains(&node) {
                continue;
            }
            if let Some(ref d) = cfg[node].taint.defines {
                defs.entry(d.clone()).or_default().insert(block_idx);
                // Register parent prefixes for synthetic base updates on field writes.
                // E.g. `obj.data` also registers `obj` so phi insertion works correctly.
                let mut path = d.as_str();
                while let Some(dot_pos) = path.rfind('.') {
                    path = &path[..dot_pos];
                    defs.entry(path.to_string()).or_default().insert(block_idx);
                }
            }
            // Register extra defines from destructuring patterns.
            for ed in &cfg[node].taint.extra_defines {
                defs.entry(ed.clone()).or_default().insert(block_idx);
            }
            // Implicit definitions for uninitialized declarations (e.g., C/C++
            // `char buf[256]`).  The variable appears in uses but not defines
            // because def_use() doesn't treat declarations without initializers
            // as definitions.  Registering here ensures phi insertion at join points.
            if cfg[node].taint.defines.is_none()
                && cfg[node].call.callee.is_none()
                && cfg[node].kind == StmtKind::Seq
                && cfg[node].taint.uses.len() == 1
            {
                defs.entry(cfg[node].taint.uses[0].clone())
                    .or_default()
                    .insert(block_idx);
            }
        }
    }

    defs
}

/// Cytron-style phi insertion: returns phi_placements[block] = set of var names needing phis.
///
/// Returns a `BTreeSet<String>` per block so downstream consumers that iterate
/// the set (notably `rename_variables`) observe a deterministic, alphabetical
/// order regardless of the underlying hasher state.  The Cytron algorithm
/// itself is order-independent, only its observers are.
fn insert_phis(
    var_defs: &BTreeMap<String, HashSet<usize>>,
    dom_frontiers: &[HashSet<usize>],
    _num_blocks: usize,
) -> Vec<BTreeSet<String>> {
    let num_blocks = dom_frontiers.len();
    let mut phi_placements: Vec<BTreeSet<String>> = vec![BTreeSet::new(); num_blocks];

    for (var, def_blocks) in var_defs {
        let mut worklist: VecDeque<usize> = def_blocks.iter().copied().collect();
        let mut has_phi: HashSet<usize> = HashSet::new();

        while let Some(b) = worklist.pop_front() {
            for &f in &dom_frontiers[b] {
                if has_phi.insert(f) {
                    phi_placements[f].insert(var.clone());
                    // Phi is a new definition, add to worklist
                    if !def_blocks.contains(&f) {
                        worklist.push_back(f);
                    }
                }
            }
        }
    }

    phi_placements
}

/// Build dominator tree children lists.
fn build_dom_tree_children(
    num_blocks: usize,
    doms: &Dominators<NodeIndex>,
    block_graph: &Graph<BlockId, ()>,
) -> Vec<Vec<usize>> {
    let mut children: Vec<Vec<usize>> = vec![vec![]; num_blocks];
    let block_nodes: Vec<NodeIndex> = block_graph.node_indices().collect();

    for i in 0..num_blocks {
        if let Some(idom) = doms.immediate_dominator(block_nodes[i]) {
            let idom_idx = block_graph[idom].0 as usize;
            if idom_idx != i {
                children[idom_idx].push(i);
            }
        }
    }

    children
}

/// Rename variables: dominator tree preorder walk with per-variable stacks.
///
/// Returns (ssa_blocks, value_defs, cfg_node_map).
fn rename_variables(
    cfg: &Cfg,
    blocks_nodes: &[Vec<NodeIndex>],
    block_succs: &[Vec<usize>],
    block_preds: &[Vec<usize>],
    phi_placements: &[BTreeSet<String>],
    dom_tree_children: &[Vec<usize>],
    filtered_edges: &[(NodeIndex, NodeIndex, EdgeKind)],
    external_vars: &[String],
    formal_params: &[String],
    with_params: bool,
    nop_nodes: &HashSet<NodeIndex>,
) -> (
    Vec<SsaBlock>,
    Vec<ValueDef>,
    HashMap<NodeIndex, SsaValue>,
    crate::ssa::ir::FieldInterner,
    HashMap<SsaValue, (SsaValue, crate::ssa::ir::FieldId)>,
    HashSet<SsaValue>,
) {
    let num_blocks = blocks_nodes.len();
    let mut next_value: u32 = 0;
    let mut value_defs: Vec<ValueDef> = Vec::new();
    let mut cfg_node_map: HashMap<NodeIndex, SsaValue> = HashMap::new();
    // Per-body interner for FieldProj field names; populated when the
    // member-access decomposition (try_lower_field_proj_chain) emits a
    // chain for chained-receiver method calls (`a.b.c()`), and remains
    // empty otherwise so existing per-statement Call lowering is
    // bit-for-bit unchanged.
    let mut field_interner = crate::ssa::ir::FieldInterner::new();
    //side-table mapping each synthetic base-update
    // [`SsaOp::Assign`]'s defined value to its `(receiver, field)` pair.
    // Populated below at the synthetic-Assign emission site.  Read by
    // the taint engine to lift the assign into a structural field WRITE.
    let mut field_writes: HashMap<SsaValue, (SsaValue, crate::ssa::ir::FieldId)> = HashMap::new();

    // Per-variable rename stacks
    let mut var_stacks: HashMap<String, Vec<SsaValue>> = HashMap::new();

    // Pre-allocate SSA blocks
    let mut ssa_blocks: Vec<SsaBlock> = (0..num_blocks)
        .map(|i| SsaBlock {
            id: BlockId(i as u32),
            phis: Vec::new(),
            body: Vec::new(),
            terminator: Terminator::Unreachable,
            preds: SmallVec::new(),
            succs: SmallVec::new(),
        })
        .collect();

    // `BTreeMap` guarantees a deterministic (alphabetical) iteration order when
    // pushing phi values onto `var_stacks` and when filling operands on
    // successor phis, both sites are observable in SSA numbering if they
    // reordered between runs.
    let mut phi_values: Vec<BTreeMap<String, SsaValue>> = vec![BTreeMap::new(); num_blocks];

    // Pre-create phi instructions for all blocks (operands filled during rename)
    for (block_idx, vars) in phi_placements.iter().enumerate() {
        let block_id = BlockId(block_idx as u32);
        let cfg_node = blocks_nodes[block_idx][0]; // anchor to first node
        for var in vars {
            let v = SsaValue(next_value);
            next_value += 1;
            value_defs.push(ValueDef {
                var_name: Some(var.clone()),
                cfg_node,
                block: block_id,
            });
            phi_values[block_idx].insert(var.clone(), v);
            ssa_blocks[block_idx].phis.push(SsaInst {
                value: v,
                op: SsaOp::Phi(SmallVec::new()),
                cfg_node,
                var_name: Some(var.clone()),
                span: cfg[cfg_node].ast.span,
            });
        }
    }

    // Process blocks in dominator tree preorder
    // We need to track stack depths to restore after processing subtrees
    // Use iterative approach: process block, then process children, restore

    // Simpler approach: preorder walk with explicit save/restore
    fn process_block(
        block_idx: usize,
        cfg: &Cfg,
        blocks_nodes: &[Vec<NodeIndex>],
        block_succs: &[Vec<usize>],
        block_preds: &[Vec<usize>],
        phi_placements: &[BTreeSet<String>],
        dom_tree_children: &[Vec<usize>],
        filtered_edges: &[(NodeIndex, NodeIndex, EdgeKind)],
        var_stacks: &mut HashMap<String, Vec<SsaValue>>,
        ssa_blocks: &mut [SsaBlock],
        phi_values: &mut [BTreeMap<String, SsaValue>],
        value_defs: &mut Vec<ValueDef>,
        cfg_node_map: &mut HashMap<NodeIndex, SsaValue>,
        next_value: &mut u32,
        nop_nodes: &HashSet<NodeIndex>,
        field_interner: &mut crate::ssa::ir::FieldInterner,
        field_writes: &mut HashMap<SsaValue, (SsaValue, crate::ssa::ir::FieldId)>,
    ) {
        let block_id = BlockId(block_idx as u32);

        // Save stack depths for rollback
        let saved: Vec<(String, usize)> = var_stacks
            .iter()
            .map(|(k, v)| (k.clone(), v.len()))
            .collect();

        // 1. Push pre-created phi values onto var stacks
        for (var, &v) in &phi_values[block_idx] {
            var_stacks.entry(var.clone()).or_default().push(v);
        }

        // 2. Process body nodes
        for &node in &blocks_nodes[block_idx] {
            let info = &cfg[node];

            // Helper: build Call args from arg_uses, falling back to info.taint.uses
            let build_call_args = |info: &crate::cfg::NodeInfo,
                                   var_stacks: &HashMap<String, Vec<SsaValue>>|
             -> (Vec<SmallVec<[SsaValue; 2]>>, Option<SsaValue>) {
                let receiver = info
                    .call
                    .receiver
                    .as_ref()
                    .and_then(|r| var_stacks.get(r).and_then(|s| s.last().copied()));
                let args = if !info.call.arg_uses.is_empty() {
                    let mut args: Vec<SmallVec<[SsaValue; 2]>> = info
                        .call
                        .arg_uses
                        .iter()
                        .map(|arg_idents| {
                            arg_idents
                                .iter()
                                .filter_map(|ident| {
                                    var_stacks.get(ident).and_then(|s| s.last().copied())
                                })
                                .collect()
                        })
                        .collect();
                    // For chained calls (e.g. fetch(url).then(fn)), arg_uses only
                    // captures the final call's args. Variables used by intermediate
                    // calls (like `url` in fetch) are in info.taint.uses but not arg_uses.
                    // Add them as an extra group so sink detection can see them.
                    //
                    // Exclude the receiver ident: it's carried on its own typed
                    // channel (`SsaOp::Call.receiver`).  Callers that care about
                    // positional arity must read it from `info.call.arg_uses.len()`,
                    // not `args.len()`, since this implicit group inflates args.
                    let arg_uses_flat: HashSet<&str> = info
                        .call
                        .arg_uses
                        .iter()
                        .flat_map(|g| g.iter().map(|s| s.as_str()))
                        .collect();
                    let receiver_ident = info.call.receiver.as_deref();
                    let implicit: SmallVec<[SsaValue; 2]> = info
                        .taint
                        .uses
                        .iter()
                        .filter(|u| !arg_uses_flat.contains(u.as_str()))
                        .filter(|u| Some(u.as_str()) != receiver_ident)
                        .filter_map(|u| var_stacks.get(u).and_then(|s| s.last().copied()))
                        .collect();
                    if !implicit.is_empty() {
                        args.push(implicit);
                    }
                    args
                } else {
                    // Fallback: treat all uses as a single argument group
                    let all_uses: SmallVec<[SsaValue; 2]> = info
                        .taint
                        .uses
                        .iter()
                        .filter_map(|u| var_stacks.get(u).and_then(|s| s.last().copied()))
                        .collect();
                    if all_uses.is_empty() {
                        vec![]
                    } else {
                        vec![all_uses]
                    }
                };
                (args, receiver)
            };

            // Determine operation and collect uses
            // Out-of-scope nodes (nop_nodes) become Nop: they preserve graph
            // connectivity but don't participate in taint flow.
            let op = if nop_nodes.contains(&node) {
                SsaOp::Nop
            } else if info.catch_param {
                SsaOp::CatchParam
            } else if info
                .taint
                .labels
                .iter()
                .any(|l| matches!(l, crate::labels::DataLabel::Source(_)))
                && info.call.callee.is_none()
            {
                // Pure source (e.g. $_GET, env var), no callee, so no args to track.
                // Source-labeled calls (e.g. file_get_contents) fall through to Call
                // so argument taint and sink detection still work.
                SsaOp::Source
            } else if info.call.callee.is_some() {
                let callee = info.call.callee.as_deref().unwrap_or("").to_string();
                let (mut args, mut receiver) = build_call_args(info, var_stacks);
                // try decomposing chained-receiver method calls
                // (`a.b.c()`) into a FieldProj chain plus a bare-method Call
                // so downstream consumers can read the receiver structure
                // without re-parsing the callee text.  Bails to None on any
                // non-chain receiver (current behaviour preserved).
                let (final_callee, callee_text) = match try_lower_field_proj_chain(
                    &callee,
                    var_stacks,
                    field_interner,
                    block_idx,
                    block_id,
                    next_value,
                    ssa_blocks,
                    value_defs,
                    node,
                    info.ast.span,
                ) {
                    Some((recv_v, bare_method)) => {
                        receiver = Some(recv_v);
                        // Strip any positional arg group that exactly matches the
                        // chain root identifier, it has been replaced by the
                        // FieldProj chain receiver, and re-listing it as an
                        // argument would inflate arity / double-taint.
                        if let Some(base_ident) = callee.split('.').next() {
                            if let Some(base_v) = var_stacks.get(base_ident).and_then(|s| s.last())
                            {
                                args.retain(|grp| !(grp.len() == 1 && grp.first() == Some(base_v)));
                            }
                        }
                        (bare_method, Some(callee.clone()))
                    }
                    None => (callee, None),
                };
                SsaOp::Call {
                    callee: final_callee,
                    callee_text,
                    args,
                    receiver,
                }
            } else if info.taint.defines.is_some()
                && info.taint.uses.is_empty()
                && !info
                    .taint
                    .labels
                    .iter()
                    .any(|l| matches!(l, crate::labels::DataLabel::Source(_)))
            {
                // Reassignment kill: a node that defines a variable but has no
                // uses (operands) and is not a source is a constant/literal
                // assignment.  SSA rename allocates a fresh SsaValue, so
                // downstream references see this new (untainted) value, the
                // prior tainted definition is implicitly dead.
                SsaOp::Const(info.taint.const_text.clone())
            } else if info.taint.defines.is_some() {
                let mut uses: SmallVec<[SsaValue; 4]> = info
                    .taint
                    .uses
                    .iter()
                    .filter_map(|u| var_stacks.get(u).and_then(|s| s.last().copied()))
                    .collect();
                // Inject Const for binary expression literal operand.
                // When a binary expression has one identifier and one numeric literal
                // (e.g., `flags & 0x07`), the literal isn't in `uses`. Inject a
                // synthetic Const instruction so the Assign has 2 uses, preventing
                // copy propagation from eliminating the operation.
                if uses.len() == 1 && info.bin_op.is_some() && info.bin_op_const.is_some() {
                    let const_val = info.bin_op_const.unwrap();
                    let const_v = SsaValue(*next_value);
                    *next_value += 1;
                    let const_inst = SsaInst {
                        value: const_v,
                        op: SsaOp::Const(Some(const_val.to_string())),
                        cfg_node: node,
                        var_name: None,
                        span: info.ast.span,
                    };
                    ssa_blocks[block_idx].body.push(const_inst);
                    value_defs.push(ValueDef {
                        var_name: None,
                        cfg_node: node,
                        block: block_id,
                    });
                    uses.push(const_v);
                }
                SsaOp::Assign(uses)
            } else if matches!(info.kind, StmtKind::Return | StmtKind::Throw)
                && !info.taint.uses.is_empty()
            {
                // `return s` / `throw e` with identifier uses: emit an
                // `Assign(uses)` so the SSA carries an explicit pass-through
                // for the returned/thrown value.  Without this, the Return
                // node was lowered as a `Nop` and the terminator-setup
                // "last non-Nop body inst" search returned None, producing
                // `Terminator::Return(None)` for a function that visibly
                // returns an identifier.  That broke per-return-path
                // PathFact narrowing for non-Rust languages where the
                // returned identifier wasn't computed in the same block
                // (e.g. Python `def f(s): return s`, `s` is a Param in
                // block 0, the Return block itself has no body insts).
                let uses: SmallVec<[SsaValue; 4]> = info
                    .taint
                    .uses
                    .iter()
                    .filter_map(|u| var_stacks.get(u).and_then(|s| s.last().copied()))
                    .collect();
                if uses.is_empty() {
                    SsaOp::Nop
                } else {
                    SsaOp::Assign(uses)
                }
            } else if matches!(
                info.kind,
                StmtKind::Entry
                    | StmtKind::Exit
                    | StmtKind::If
                    | StmtKind::Loop
                    | StmtKind::Break
                    | StmtKind::Continue
                    | StmtKind::Return
                    | StmtKind::Throw
            ) {
                SsaOp::Nop
            } else if info.call.callee.is_some() {
                let callee = info.call.callee.as_deref().unwrap_or("").to_string();
                let (mut args, mut receiver) = build_call_args(info, var_stacks);
                // same FieldProj-chain decomposition as the primary
                // Call branch above, kept in sync because this fallback
                // path also constructs SSA Call ops (used for control-flow
                // wrapper calls that landed past the earlier match arms).
                let (final_callee, callee_text) = match try_lower_field_proj_chain(
                    &callee,
                    var_stacks,
                    field_interner,
                    block_idx,
                    block_id,
                    next_value,
                    ssa_blocks,
                    value_defs,
                    node,
                    info.ast.span,
                ) {
                    Some((recv_v, bare_method)) => {
                        receiver = Some(recv_v);
                        if let Some(base_ident) = callee.split('.').next() {
                            if let Some(base_v) = var_stacks.get(base_ident).and_then(|s| s.last())
                            {
                                args.retain(|grp| !(grp.len() == 1 && grp.first() == Some(base_v)));
                            }
                        }
                        (bare_method, Some(callee.clone()))
                    }
                    None => (callee, None),
                };
                SsaOp::Call {
                    callee: final_callee,
                    callee_text,
                    args,
                    receiver,
                }
            } else {
                SsaOp::Nop
            };

            // Allocate SSA value
            let v = SsaValue(*next_value);
            *next_value += 1;
            let var_name_for_ssa = if nop_nodes.contains(&node) {
                None
            } else if info.taint.defines.is_some() {
                info.taint.defines.clone()
            } else if info.kind == StmtKind::Seq
                && info.call.callee.is_none()
                && info.taint.uses.len() == 1
                && !var_stacks.contains_key(&info.taint.uses[0])
            {
                // Implicit definition for uninitialized declarations (e.g.,
                // C/C++ `char buf[256]`).  Creates a reaching definition so
                // output-parameter sources like fgets() can taint the buffer
                // and subsequent uses (e.g., system(buf)) see the tainted value.
                Some(info.taint.uses[0].clone())
            } else {
                None
            };
            value_defs.push(ValueDef {
                var_name: var_name_for_ssa.clone(),
                cfg_node: node,
                block: block_id,
            });

            // Push defined variable onto stack (skip nop nodes)
            if let Some(ref d) = var_name_for_ssa {
                var_stacks.entry(d.clone()).or_default().push(v);
            }

            cfg_node_map.insert(node, v);

            // Clone op for potential extra_defines before moving into SsaInst
            let primary_op_for_extras = if info.taint.extra_defines.is_empty() {
                None
            } else {
                Some(op.clone())
            };
            ssa_blocks[block_idx].body.push(SsaInst {
                value: v,
                op,
                cfg_node: node,
                var_name: var_name_for_ssa.clone(),
                span: info.ast.span,
            });

            // Synthetic base update: when a dotted path is defined (e.g. `obj.data`),
            // create synthetic Assign instructions for parent prefixes (e.g. `obj`)
            // so that subsequent reads of the base variable see the field write.
            // Only includes the new field value (not the old base) so that field
            // overwrites properly kill taint: if obj.data is re-assigned to a
            // constant, the base `obj` no longer carries that field's taint.
            //
            //each synthetic Assign also records its
            // structural identity into `field_writes`, `(receiver_old_value,
            // FieldId(field_name))`, so the taint engine can recognise the
            // synthetic assign as a field WRITE and mirror the rhs taint
            // into the matching `(loc, field)` cell on `SsaTaintState`.
            // The "old" parent value is the reaching def of `parent` BEFORE
            // we push the new `synth_v`; when no prior def exists (the
            // parent is undefined at this point), we skip the side-table
            // entry so the consumer's `pt(receiver)` walk produces no work.
            if !nop_nodes.contains(&node) {
                if let Some(ref d) = info.taint.defines {
                    let mut current = d.as_str();
                    let mut child_value = v;
                    while let Some(dot_pos) = current.rfind('.') {
                        let parent = &current[..dot_pos];
                        let field_name = &current[dot_pos + 1..];
                        // Snapshot prior reaching def of `parent` BEFORE we
                        // push the new synth_v.  Used by the field-write
                        // side-table as the receiver SsaValue.
                        let prior_parent_value: Option<SsaValue> =
                            var_stacks.get(parent).and_then(|s| s.last().copied());
                        let synth_v = SsaValue(*next_value);
                        *next_value += 1;
                        let synth_uses: SmallVec<[SsaValue; 4]> =
                            SmallVec::from_elem(child_value, 1);
                        value_defs.push(ValueDef {
                            var_name: Some(parent.to_string()),
                            cfg_node: node,
                            block: block_id,
                        });
                        var_stacks
                            .entry(parent.to_string())
                            .or_default()
                            .push(synth_v);
                        ssa_blocks[block_idx].body.push(SsaInst {
                            value: synth_v,
                            op: SsaOp::Assign(synth_uses),
                            cfg_node: node,
                            var_name: Some(parent.to_string()),
                            span: info.ast.span,
                        });
                        // Record `(synth_v -> (prior_parent, field_id))` so
                        // the taint engine can lift the synthetic assign
                        // into a field-write hook.  The field name is
                        // interned through the per-body `FieldInterner` so
                        // FieldProj reads downstream resolve to the same id.
                        if let Some(rcv) = prior_parent_value {
                            let fid = field_interner.intern(field_name);
                            field_writes.insert(synth_v, (rcv, fid));
                        }
                        child_value = synth_v;
                        current = parent;
                    }
                }
            }

            // Emit extra SSA instructions for destructuring bindings.
            // Each extra define inherits the same op (Source/Call/Assign) as the primary.
            if let Some(ref primary_op) = primary_op_for_extras {
                for extra_def in &info.taint.extra_defines {
                    let ev = SsaValue(*next_value);
                    *next_value += 1;
                    value_defs.push(ValueDef {
                        var_name: Some(extra_def.clone()),
                        cfg_node: node,
                        block: block_id,
                    });
                    var_stacks.entry(extra_def.clone()).or_default().push(ev);
                    ssa_blocks[block_idx].body.push(SsaInst {
                        value: ev,
                        op: primary_op.clone(),
                        cfg_node: node,
                        var_name: Some(extra_def.clone()),
                        span: info.ast.span,
                    });
                }
            }
        }

        // 3. Set terminator
        let succs = &block_succs[block_idx];
        let last_node = *blocks_nodes[block_idx].last().unwrap();

        ssa_blocks[block_idx].terminator = if succs.is_empty() {
            // A block with no successors at the block level is one of:
            //   (1) a block containing a Throw, terminates with an
            //       exception; no normal fall-through.
            //   (2) a block containing a Return, terminates with a value
            //       (or void).  After form_blocks strips the bookkeeping
            //       Seq edge from Return → fn_exit, every explicit-return
            //       block lands here, including `if cond { return X; }`
            //       early returns.
            //   (3) the function-exit (fn_exit) block itself when the
            //       function falls off the end (implicit return).
            //
            // Distinguish them by inspecting the block's CFG nodes.
            let return_node = blocks_nodes[block_idx]
                .iter()
                .copied()
                .find(|&n| cfg[n].kind == StmtKind::Return);
            let has_throw_node = blocks_nodes[block_idx]
                .iter()
                .any(|&n| cfg[n].kind == StmtKind::Throw);

            if has_throw_node && return_node.is_none() {
                // Throw terminates control flow with an exception.  No
                // structured Throw terminator exists today; downstream
                // analyses rely on `exception_edges` (recorded separately)
                // for catch-block dispatch.  Mark the normal-flow exit as
                // Unreachable so successor consumers do not invent a
                // synthetic fall-through edge.
                Terminator::Unreachable
            } else if let Some(rn) = return_node {
                let return_info = &cfg[rn];
                // Return-value resolution.  Mirror the legacy
                // `has_const_return` path so callers see exactly the same
                // SSA shape they did before the merged-return fix, only
                // the *terminator* changes (Goto(exit) → Return(_)), not
                // the value selection.
                //
                //   (a) Literal return (`return 'x'`, `return None`,
                //       `return []`, `return;`).  Marked by
                //       `taint.uses.is_empty()` on the Return CFG node.
                //       Emit a synthetic Const inst so taint never leaks
                //       from an unrelated inst earlier in the same block
                //       (regression guard: C-1 inline-return precision).
                //   (b) Computed / passthrough return, last non-Nop body
                //       inst.  Covers `return foo()` (Call sits before the
                //       Return Nop), `return x + y` (Assign), and the
                //       implicit tail expression collapsed into a single
                //       block by the leader-following loop.  When the
                //       Return carries identifier uses (`return req`,
                //       `return { req.session, ... }`), the SSA defs for
                //       those identifiers are already on the body as
                //       Param / Assign / Source insts, picking the last
                //       one matches pre-fix behaviour exactly.
                //   (c) Void / unresolved, `Return(None)`.
                if return_info.taint.uses.is_empty() {
                    let const_text = return_info.taint.const_text.clone();
                    let const_v = SsaValue(*next_value);
                    *next_value += 1;
                    let block_id = BlockId(block_idx as u32);
                    value_defs.push(ValueDef {
                        var_name: None,
                        cfg_node: rn,
                        block: block_id,
                    });
                    ssa_blocks[block_idx].body.push(SsaInst {
                        value: const_v,
                        op: SsaOp::Const(const_text),
                        cfg_node: rn,
                        var_name: None,
                        span: return_info.ast.span,
                    });
                    Terminator::Return(Some(const_v))
                } else {
                    let from_body = ssa_blocks[block_idx]
                        .body
                        .iter()
                        .rev()
                        .find(|inst| !matches!(inst.op, SsaOp::Nop))
                        .map(|inst| inst.value);
                    Terminator::Return(from_body)
                }
            } else {
                // (3) fn_exit / true fall-off, no Return CFG node in this
                // block.  Use the last non-Nop body instruction as the
                // implicit return value (e.g. the function's tail-position
                // expression in Rust).
                let ret_val = ssa_blocks[block_idx]
                    .body
                    .iter()
                    .rev()
                    .find(|inst| !matches!(inst.op, SsaOp::Nop))
                    .map(|inst| inst.value);
                Terminator::Return(ret_val)
            }
        } else if succs.len() == 1 {
            Terminator::Goto(BlockId(succs[0] as u32))
        } else if succs.len() == 2 {
            // Find the If/Loop node that branches
            let cond_node = blocks_nodes[block_idx]
                .iter()
                .rev()
                .find(|&&n| matches!(cfg[n].kind, StmtKind::If | StmtKind::Loop))
                .copied()
                .unwrap_or(last_node);

            // Determine which successor is true/false by looking at edge kinds
            let mut true_blk = succs[0];
            let mut false_blk = succs[1];

            // Check filtered edges from any node in this block to successors
            for &(src, tgt, kind) in filtered_edges {
                if blocks_nodes[block_idx].contains(&src) {
                    let tgt_blk_opt = succs.iter().position(|&s| {
                        blocks_nodes
                            .get(s)
                            .is_some_and(|nodes| nodes.contains(&tgt))
                    });
                    if let Some(tgt_blk_pos) = tgt_blk_opt {
                        match kind {
                            EdgeKind::True => true_blk = succs[tgt_blk_pos],
                            EdgeKind::False => false_blk = succs[tgt_blk_pos],
                            _ => {}
                        }
                    }
                }
            }

            // Lower structured condition from CFG metadata
            let cond_info = &cfg[cond_node];
            let condition = if cond_info.condition_text.is_some()
                && !cond_info.condition_vars.is_empty()
            {
                let expr =
                    crate::constraint::lower::lower_condition_with_stacks(cond_info, var_stacks);
                if matches!(expr, crate::constraint::lower::ConditionExpr::Unknown) {
                    None
                } else {
                    Some(Box::new(expr))
                }
            } else {
                None
            };

            Terminator::Branch {
                cond: cond_node,
                true_blk: BlockId(true_blk as u32),
                false_blk: BlockId(false_blk as u32),
                condition,
            }
        } else {
            // More than 2 successors, model as a multi-way Switch.
            //
            // This replaces the previous `Goto(first)` collapse: the
            // structured terminator now enumerates every target instead
            // of hiding N-1 of them behind `block.succs`. Flow consumers
            // (taint, const-prop, symex) still iterate `succs` as
            // authoritative, but downstream tooling that inspects the
            // terminator shape gets the full fanout.
            //
            // Note: today's switch-statement CFG construction decomposes
            // cases into a cascade of binary `Branch` headers (see
            // `build_switch` in src/cfg.rs), so real switch statements
            // never reach this arm. Folding the cascade back into a
            // single Switch node is a follow-up; in the meantime, this
            // arm fires only on genuine multi-way CFG fanouts (e.g.
            // future Go-switch / Java-arrow / Rust-match lowerings).
            //
            // Scrutinee: use the primary SSA value defined at the last
            // node in this block when one exists; fall back to
            // `SsaValue(0)` (a valid index, SSA numbering is 1-based
            // only conceptually, and value 0 is always present in a
            // non-empty body) when no value is defined. Downstream
            // consumers that care about the scrutinee (abstract interp,
            // symex per-case constraints) treat a missing/degenerate
            // scrutinee as "unknown" rather than panicking.
            let scrutinee = cfg_node_map.get(&last_node).copied().unwrap_or(SsaValue(0));
            let targets: SmallVec<[BlockId; 4]> =
                succs.iter().skip(1).map(|&s| BlockId(s as u32)).collect();
            let default = BlockId(succs[0] as u32);
            // Synthetic ≥3-way fanouts have no per-case literal metadata ,
            // every entry is None (unknown), so the executor falls back to
            // first-reachable behavior on this terminator.
            let case_values: SmallVec<[Option<crate::constraint::domain::ConstValue>; 4]> =
                std::iter::repeat_with(|| None)
                    .take(targets.len())
                    .collect();
            tracing::debug!(
                block = block_idx,
                num_succs = succs.len(),
                "emitting Terminator::Switch for ≥3-way fanout",
            );
            Terminator::Switch {
                scrutinee,
                targets,
                default,
                case_values,
            }
        };

        // 4. Fill phi operands in successor blocks
        for &succ in succs {
            for (var, &phi_val) in &phi_values[succ] {
                // The version of `var` reaching from this block
                let reaching_val = var_stacks.get(var).and_then(|s| s.last().copied());
                if let Some(rv) = reaching_val {
                    // Find the phi instruction and add this operand
                    for phi in &mut ssa_blocks[succ].phis {
                        if phi.value == phi_val {
                            if let SsaOp::Phi(ref mut operands) = phi.op {
                                operands.push((block_id, rv));
                            }
                        }
                    }
                }
            }
        }

        // 5. Recurse into dominator tree children
        for &child in &dom_tree_children[block_idx] {
            process_block(
                child,
                cfg,
                blocks_nodes,
                block_succs,
                block_preds,
                phi_placements,
                dom_tree_children,
                filtered_edges,
                var_stacks,
                ssa_blocks,
                phi_values,
                value_defs,
                cfg_node_map,
                next_value,
                nop_nodes,
                field_interner,
                field_writes,
            );
        }

        // 6. Restore stacks
        for (var, depth) in &saved {
            if let Some(stack) = var_stacks.get_mut(var) {
                stack.truncate(*depth);
            }
        }
        // Remove any new variables that weren't in saved
        let saved_vars: HashSet<&String> = saved.iter().map(|(k, _)| k).collect();
        var_stacks.retain(|k, _| saved_vars.contains(k));
    }

    // Inject synthetic Param instructions at START of block 0 for external variables.
    // These create SSA definitions so the rename pass can reference them.
    // Pre-seed var_stacks so process_block sees them.
    //
    // `external_vars` contains both real formal parameters and free / closure-
    // captured variables (variables read by the body but not declared as a
    // formal and not assigned anywhere).  Both end up emitted as
    // [`SsaOp::Param`] in block 0; we record the SSA values that correspond
    // to free vars in `synthetic_externals` so downstream analyses (the JS/TS
    // handler-name auto-seed in particular) can avoid treating closure
    // captures as if they were parameters of the function under analysis.
    //
    // **Conservative behaviour when the caller didn't supply formal-param
    // info.** Several call sites (`lower_to_ssa`, `lower_to_ssa_scoped_nop`)
    // don't supply formal parameter names; in that case we cannot distinguish
    // formals from free vars structurally, so we leave `synthetic_externals`
    // empty and the auto-seed pass keeps its pre-fix behaviour of treating
    // every `Param` op as a candidate.  Callers that opt in via
    // `lower_to_ssa_with_params` set `with_params=true`, signalling that
    // `formal_params` is the authoritative formal list — even when empty
    // (arrow `() => {…}`).  In that case every external becomes synthetic
    // unless it appears in `formal_params`, so the auto-seed pass cannot
    // mistake a bubbled-up free var (like `userId` lifted from a nested
    // jest test callback) for a formal of the outer body.
    let mut synthetic_externals: HashSet<SsaValue> = HashSet::new();
    let formal_set: HashSet<&str> = formal_params.iter().map(|s| s.as_str()).collect();
    let track_synthetic = with_params;
    if !external_vars.is_empty() {
        let entry_cfg_node = blocks_nodes[0][0];
        let mut synthetic_body = Vec::with_capacity(external_vars.len());
        let mut positional_idx: usize = 0;
        for var in external_vars.iter() {
            let v = SsaValue(next_value);
            next_value += 1;
            value_defs.push(ValueDef {
                var_name: Some(var.clone()),
                cfg_node: entry_cfg_node,
                block: BlockId(0),
            });
            let is_receiver = is_receiver_name(var);
            let op = if is_receiver {
                SsaOp::SelfParam
            } else {
                let op = SsaOp::Param {
                    index: positional_idx,
                };
                positional_idx += 1;
                op
            };
            // A non-receiver var is "synthetic" (a free / closure capture)
            // when it is *not* one of the function's declared formals AND
            // not a dotted access on a formal (`input.cmd` where `input` is
            // a formal — it represents a structural projection of the
            // formal, not a free variable; the auto-seed should still treat
            // it as part of the formal's own taint surface).  Receivers are
            // intentionally excluded: `this` / `self` represent the implicit
            // receiver, which always belongs to the function.
            //
            // Only fire when the caller supplied formal-parameter names; see
            // the `track_synthetic` rationale above.
            let root_is_formal = var
                .split_once('.')
                .map(|(root, _)| formal_set.contains(root))
                .unwrap_or(false);
            if track_synthetic
                && !is_receiver
                && !formal_set.contains(var.as_str())
                && !root_is_formal
            {
                synthetic_externals.insert(v);
            }
            synthetic_body.push(SsaInst {
                value: v,
                op,
                cfg_node: entry_cfg_node,
                var_name: Some(var.clone()),
                span: (0, 0),
            });
            var_stacks.entry(var.clone()).or_default().push(v);
        }
        // Prepend synthetic params before any existing body instructions
        synthetic_body.append(&mut ssa_blocks[0].body);
        ssa_blocks[0].body = synthetic_body;
    }

    process_block(
        0, // entry block
        cfg,
        blocks_nodes,
        block_succs,
        block_preds,
        phi_placements,
        dom_tree_children,
        filtered_edges,
        &mut var_stacks,
        &mut ssa_blocks,
        &mut phi_values,
        &mut value_defs,
        &mut cfg_node_map,
        &mut next_value,
        nop_nodes,
        &mut field_interner,
        &mut field_writes,
    );

    // Process orphan blocks (e.g. catch blocks disconnected after exception edge removal).
    // These blocks have no predecessors and weren't reached by the dominator tree walk.
    //
    // Rebuild var_stacks from already-processed instructions so that catch blocks
    // can reference variables defined before the try block (e.g. `userInput`).
    let has_orphans =
        (1..num_blocks).any(|bid| block_preds[bid].is_empty() && ssa_blocks[bid].body.is_empty());
    if has_orphans {
        // Rebuild var_stacks from all SSA instructions created during the main walk.
        // This gives orphan blocks access to all variable definitions.
        var_stacks.clear();
        for block in &ssa_blocks {
            for inst in block.phis.iter().chain(block.body.iter()) {
                if let Some(ref name) = inst.var_name {
                    var_stacks.entry(name.clone()).or_default().push(inst.value);
                }
            }
        }

        for bid in 1..num_blocks {
            if block_preds[bid].is_empty() && ssa_blocks[bid].body.is_empty() {
                process_block(
                    bid,
                    cfg,
                    blocks_nodes,
                    block_succs,
                    block_preds,
                    phi_placements,
                    dom_tree_children,
                    filtered_edges,
                    &mut var_stacks,
                    &mut ssa_blocks,
                    &mut phi_values,
                    &mut value_defs,
                    &mut cfg_node_map,
                    &mut next_value,
                    nop_nodes,
                    &mut field_interner,
                    &mut field_writes,
                );
            }
        }
    }

    (
        ssa_blocks,
        value_defs,
        cfg_node_map,
        field_interner,
        field_writes,
        synthetic_externals,
    )
}

// ─────────────────────────────────────────────────────────────────────────────
//  Debug invariant checkers
// ─────────────────────────────────────────────────────────────────────────────

/// Verify BFS block ordering: every non-entry, non-orphan block must have at
/// least one predecessor with a smaller block ID.
fn debug_assert_bfs_ordering(block_preds: &[Vec<usize>]) {
    for (i, preds) in block_preds.iter().enumerate() {
        if i == 0 {
            continue; // entry block
        }
        if preds.is_empty() {
            continue; // orphan block (e.g. catch block reached via exception edge)
        }
        let has_forward_pred = preds.iter().any(|&p| p < i);
        debug_assert!(
            has_forward_pred,
            "Block {} has no forward predecessor — BFS ordering violated. Preds: {:?}",
            i, preds
        );
    }
}

/// Verify phi operand counts: each phi must have exactly one operand
/// per predecessor, and every operand must reference an actual
/// predecessor of the block.
///
/// Runs in release builds because phi-operand mismatches are
/// load-bearing for soundness, downstream taint, const, and abstract
/// analyses iterate phi operands by `(pred_blk, value)` pairs, and
/// either a missing operand (silent "no contribution" on that edge)
/// or a phantom operand (garbage into the join) corrupts analysis
/// without surfacing.
///
/// The invariant is strict equality. Predecessors that carry no
/// reaching definition for the phi's variable are filled with the
/// [`SsaOp::Undef`] sentinel in `fill_undef_phi_operands`, rather than
/// being dropped, so consumers that look up by `(pred_blk, value)`
/// see a real operand for every control-flow edge.
fn assert_phi_operand_counts(ssa_blocks: &[SsaBlock], block_preds: &[Vec<usize>]) {
    use std::collections::HashSet;
    for (i, block) in ssa_blocks.iter().enumerate() {
        let pred_set: HashSet<u32> = block_preds[i].iter().map(|&p| p as u32).collect();
        for phi in &block.phis {
            if let SsaOp::Phi(ref operands) = phi.op {
                assert_eq!(
                    operands.len(),
                    block_preds[i].len(),
                    "SSA phi operand count does not match predecessor count: block {} phi v{} \
                     (var={:?}) has {} operands but block has {} predecessors. \
                     preds={:?}, operand_preds={:?}",
                    i,
                    phi.value.0,
                    phi.var_name,
                    operands.len(),
                    block_preds[i].len(),
                    block_preds[i],
                    operands.iter().map(|(b, _)| b.0).collect::<Vec<_>>(),
                );
                // Each operand's pred block must be an actual predecessor,
                // and no predecessor may appear more than once.
                let mut seen: HashSet<u32> = HashSet::new();
                for (pred_blk, _) in operands.iter() {
                    assert!(
                        pred_set.contains(&pred_blk.0),
                        "SSA phi operand references nonexistent predecessor: block {} phi v{} \
                         references pred B{} but block predecessors are {:?}",
                        i,
                        phi.value.0,
                        pred_blk.0,
                        block_preds[i],
                    );
                    assert!(
                        seen.insert(pred_blk.0),
                        "SSA phi operand duplicates predecessor: block {} phi v{} has two \
                         operands for pred B{}",
                        i,
                        phi.value.0,
                        pred_blk.0,
                    );
                }
            }
        }
    }
}

/// Post-rename pass: ensure every phi has one operand per predecessor.
///
/// During rename, phi operands are only pushed when the variable has a
/// live reaching definition on that predecessor edge. Edges where the
/// variable is not yet defined (e.g. a try-body rejoining after a
/// catch-only binding, an early-return branch on a later-defined
/// variable, an orphan catch block's implicit predecessors) leave the
/// phi with fewer operands than the block has predecessors.
///
/// This pass scans all phis, and for every missing `(pred_block, _)`
/// slot, pushes `(pred_block, undef_val)` where `undef_val` is a
/// single shared sentinel instruction ([`SsaOp::Undef`]) synthesized
/// at the end of block 0's body. Consumers iterate phi operands by
/// `(pred_blk, value)` and therefore see a real operand on every
/// control-flow edge, no implicit "missing = empty" semantics.
///
/// The Undef instruction is created lazily (only when at least one phi
/// has a gap) so functions with fully-dominating definitions pay zero
/// cost. All phis share the same Undef value: a phi operand is
/// identified by its `(pred_block, value)` pair, so sharing the value
/// across phis is safe and keeps the synthesized-instruction count at
/// most one per function body.
fn fill_undef_phi_operands(
    ssa_blocks: &mut [SsaBlock],
    block_preds: &[Vec<usize>],
    value_defs: &mut Vec<ValueDef>,
    blocks_nodes: &[Vec<NodeIndex>],
) {
    // Fast path: detect whether any phi has a gap. Avoid allocating
    // the Undef value in the common case where every phi is saturated.
    let needs_undef = ssa_blocks.iter().enumerate().any(|(bi, block)| {
        block.phis.iter().any(|phi| {
            if let SsaOp::Phi(ref operands) = phi.op {
                operands.len() < block_preds[bi].len()
            } else {
                false
            }
        })
    });
    if !needs_undef {
        return;
    }

    // Anchor the synthetic Undef instruction to the entry block's first
    // CFG node so span lookups don't hit an invalid NodeIndex.
    let anchor_node = blocks_nodes
        .first()
        .and_then(|b| b.first())
        .copied()
        .expect("entry block has at least one CFG node");

    let undef_val = SsaValue(value_defs.len() as u32);
    value_defs.push(ValueDef {
        var_name: None,
        cfg_node: anchor_node,
        block: BlockId(0),
    });
    // Place the Undef instruction at the end of block 0's body so it
    // appears after any synthetic Param / SelfParam emissions, its
    // only role is to anchor the SsaValue; ordering relative to other
    // body instructions is cosmetic (no consumer depends on its
    // position, only on the value lookup).
    ssa_blocks[0].body.push(SsaInst {
        value: undef_val,
        op: SsaOp::Undef,
        cfg_node: anchor_node,
        var_name: None,
        span: (0, 0),
    });

    // Fill missing operand slots. Iterate `block_preds[bi]` in its
    // natural order so the resulting phi operand list is deterministic
    // across runs.
    for (bi, block) in ssa_blocks.iter_mut().enumerate() {
        for phi in block.phis.iter_mut() {
            if let SsaOp::Phi(ref mut operands) = phi.op {
                if operands.len() == block_preds[bi].len() {
                    continue;
                }
                use std::collections::HashSet;
                let present: HashSet<u32> = operands.iter().map(|(b, _)| b.0).collect();
                for &pred in &block_preds[bi] {
                    let pid = pred as u32;
                    if !present.contains(&pid) {
                        operands.push((BlockId(pid), undef_val));
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cfg::{EdgeKind, NodeInfo, StmtKind, TaintMeta};
    use petgraph::Graph;

    fn make_node(kind: StmtKind) -> NodeInfo {
        NodeInfo {
            kind,
            ..Default::default()
        }
    }

    #[test]
    fn linear_cfg_no_phis() {
        // Entry → x=1 → y=x → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let n1 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let n2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("y".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, n1, EdgeKind::Seq);
        cfg.add_edge(n1, n2, EdgeKind::Seq);
        cfg.add_edge(n2, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Should be a single block (all Seq edges, no branches)
        assert_eq!(ssa.blocks.len(), 1);
        // No phis in a linear CFG
        assert!(ssa.blocks[0].phis.is_empty());
        // 4 body instructions (entry, x=1, y=x, exit)
        assert_eq!(ssa.blocks[0].body.len(), 4);
    }

    #[test]
    fn diamond_cfg_produces_phi() {
        // Entry → x=1 → If → [True: x=2] [False: x=3] → Join → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let def_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let if_node = cfg.add_node(make_node(StmtKind::If));
        let true_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let false_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(make_node(StmtKind::Seq));
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, def_x, EdgeKind::Seq);
        cfg.add_edge(def_x, if_node, EdgeKind::Seq);
        cfg.add_edge(if_node, true_node, EdgeKind::True);
        cfg.add_edge(if_node, false_node, EdgeKind::False);
        cfg.add_edge(true_node, join, EdgeKind::Seq);
        cfg.add_edge(false_node, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Should have multiple blocks
        assert!(ssa.blocks.len() >= 3);

        // The join block should have a phi for "x"
        let join_block = ssa
            .blocks
            .iter()
            .find(|b| !b.phis.is_empty())
            .expect("should have a block with a phi");
        assert_eq!(join_block.phis.len(), 1);
        assert_eq!(join_block.phis[0].var_name.as_deref(), Some("x"));

        // Phi should have 2 operands (from true and false branches)
        if let SsaOp::Phi(ref operands) = join_block.phis[0].op {
            assert_eq!(operands.len(), 2);
        } else {
            panic!("expected Phi op");
        }
    }

    #[test]
    fn loop_cfg_produces_phi() {
        // Entry → x=0 → Loop header → [Back: x=x+1] → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let def_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let loop_header = cfg.add_node(make_node(StmtKind::Loop));
        let body = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, def_x, EdgeKind::Seq);
        cfg.add_edge(def_x, loop_header, EdgeKind::Seq);
        cfg.add_edge(loop_header, body, EdgeKind::True);
        cfg.add_edge(body, loop_header, EdgeKind::Back);
        cfg.add_edge(loop_header, exit, EdgeKind::False);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Loop header block should have a phi for "x" (from entry and back edge)
        let header_phis: Vec<_> = ssa.blocks.iter().filter(|b| !b.phis.is_empty()).collect();

        assert!(
            !header_phis.is_empty(),
            "loop header should have a phi for x"
        );

        let x_phi = header_phis[0]
            .phis
            .iter()
            .find(|p| p.var_name.as_deref() == Some("x"));
        assert!(x_phi.is_some(), "should have phi for variable x");
    }

    #[test]
    fn multiple_reassignments_distinct_values() {
        // Entry → x=1 → x=2 → x=3 → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let n1 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let n2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let n3 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, n1, EdgeKind::Seq);
        cfg.add_edge(n1, n2, EdgeKind::Seq);
        cfg.add_edge(n2, n3, EdgeKind::Seq);
        cfg.add_edge(n3, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Each definition of x should produce a distinct SsaValue
        let x_values: Vec<_> = ssa
            .value_defs
            .iter()
            .enumerate()
            .filter(|(_, vd)| vd.var_name.as_deref() == Some("x"))
            .map(|(i, _)| SsaValue(i as u32))
            .collect();

        assert_eq!(x_values.len(), 3, "three definitions of x");
        // All distinct
        let unique: HashSet<_> = x_values.iter().collect();
        assert_eq!(unique.len(), 3, "all SsaValues should be distinct");
    }

    #[test]
    fn empty_cfg_returns_error() {
        let cfg: Cfg = Graph::new();
        let result = lower_to_ssa(&cfg, NodeIndex::new(0), None, true);
        assert!(result.is_err());
    }

    // ── BFS ordering and phi invariant tests ─────────────────────────────

    #[test]
    fn bfs_ordering_holds_for_linear_cfg() {
        // Entry → A → B → Exit, all blocks should satisfy BFS ordering
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let a = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let b = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("y".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, a, EdgeKind::Seq);
        cfg.add_edge(a, b, EdgeKind::Seq);
        cfg.add_edge(b, exit, EdgeKind::Seq);

        // This exercises the debug_assert_bfs_ordering in debug builds
        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        assert!(!ssa.blocks.is_empty());
    }

    #[test]
    fn bfs_ordering_holds_for_diamond_cfg() {
        // Entry → If → [True] [False] → Join → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let def_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let if_node = cfg.add_node(make_node(StmtKind::If));
        let true_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let false_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(make_node(StmtKind::Seq));
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, def_x, EdgeKind::Seq);
        cfg.add_edge(def_x, if_node, EdgeKind::Seq);
        cfg.add_edge(if_node, true_node, EdgeKind::True);
        cfg.add_edge(if_node, false_node, EdgeKind::False);
        cfg.add_edge(true_node, join, EdgeKind::Seq);
        cfg.add_edge(false_node, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        // Exercises both BFS ordering and phi operand count assertions
        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        // The join block should have a phi with exactly 2 operands (== 2 preds)
        let phi_block = ssa.blocks.iter().find(|b| !b.phis.is_empty());
        if let Some(block) = phi_block {
            assert_eq!(
                block.preds.len(),
                2,
                "join block should have 2 predecessors"
            );
            for phi in &block.phis {
                if let SsaOp::Phi(ref ops) = phi.op {
                    assert!(
                        ops.len() <= block.preds.len(),
                        "phi operands should not exceed predecessor count"
                    );
                }
            }
        }
    }

    #[test]
    fn bfs_ordering_holds_for_loop_with_back_edge() {
        // Entry → x=0 → Loop → body(x=x+1) → [Back→Loop] → Exit
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let def_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let loop_h = cfg.add_node(make_node(StmtKind::Loop));
        let body = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, def_x, EdgeKind::Seq);
        cfg.add_edge(def_x, loop_h, EdgeKind::Seq);
        cfg.add_edge(loop_h, body, EdgeKind::True);
        cfg.add_edge(body, loop_h, EdgeKind::Back);
        cfg.add_edge(loop_h, exit, EdgeKind::False);

        // Exercises BFS ordering with back edges and phi on loop header
        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        assert!(!ssa.blocks.is_empty());
    }

    #[test]
    fn orphan_catch_block_does_not_violate_bfs_ordering() {
        // Entry → body → Exit, with an exception edge body → catch → Exit
        // The catch block becomes an orphan (no normal-flow predecessors)
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let body = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let catch = cfg.add_node(NodeInfo {
            catch_param: true,
            taint: TaintMeta {
                defines: Some("e".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, body, EdgeKind::Seq);
        cfg.add_edge(body, exit, EdgeKind::Seq);
        cfg.add_edge(body, catch, EdgeKind::Exception);
        cfg.add_edge(catch, exit, EdgeKind::Seq);

        // The catch block is reached via exception edge (stripped from normal flow)
        // so it may appear as an orphan. The BFS assertion should skip it.
        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        assert!(!ssa.blocks.is_empty());
    }

    #[test]
    fn phi_operand_count_equals_pred_count_in_diamond() {
        // Specific test: phi operands == predecessor count (not just <=)
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let if_node = cfg.add_node(make_node(StmtKind::If));
        let t = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("v".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let f = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("v".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["v".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, if_node, EdgeKind::Seq);
        cfg.add_edge(if_node, t, EdgeKind::True);
        cfg.add_edge(if_node, f, EdgeKind::False);
        cfg.add_edge(t, join, EdgeKind::Seq);
        cfg.add_edge(f, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        let phi_block = ssa
            .blocks
            .iter()
            .find(|b| !b.phis.is_empty())
            .expect("should have a phi block");

        for phi in &phi_block.phis {
            if let SsaOp::Phi(ref ops) = phi.op {
                assert_eq!(
                    ops.len(),
                    phi_block.preds.len(),
                    "phi operand count should equal predecessor count in a clean diamond"
                );
            }
        }
    }

    #[test]
    fn bfs_assertion_helper_accepts_valid_orderings() {
        // Direct unit test of the assertion helper with valid input
        let block_preds = vec![
            vec![],     // block 0: entry (no preds)
            vec![0],    // block 1: pred is block 0 (forward)
            vec![0, 1], // block 2: both forward preds
            vec![],     // block 3: orphan (no preds)
            vec![2],    // block 4: forward pred
        ];
        // Should not panic
        debug_assert_bfs_ordering(&block_preds);
    }

    /// Regression guard: a catch block that joins an exception
    /// predecessor and a normal control-flow predecessor must lower to a
    /// consistent phi. For variables defined before the try (live on
    /// *both* edges), the phi at the catch block has exactly two operands
    ///, one per predecessor, and the release assertion accepts it.
    #[test]
    fn catch_block_join_phi_has_operand_per_live_predecessor() {
        // Entry → defines `x` → Try → (Seq) → Join ← (Exception via body) Catch
        //        //                         A phi for `x` at the join block should carry
        //                         one operand from each of its two predecessors.
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let define_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let body = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let catch = cfg.add_node(NodeInfo {
            catch_param: true,
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, define_x, EdgeKind::Seq);
        cfg.add_edge(define_x, body, EdgeKind::Seq);
        cfg.add_edge(body, join, EdgeKind::Seq);
        cfg.add_edge(body, catch, EdgeKind::Exception);
        cfg.add_edge(catch, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        // Lowering must succeed, the assertion is active in release.
        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Locate the block containing a phi for `x`; it must be the join
        // block with two reachable predecessors. The phi must have
        // exactly two operands.
        let phi_block = ssa
            .blocks
            .iter()
            .find(|b| {
                b.phis
                    .iter()
                    .any(|p| p.var_name.as_deref() == Some("x") && matches!(p.op, SsaOp::Phi(_)))
            })
            .expect("expected a phi for `x` at the catch/normal join");
        assert_eq!(
            phi_block.preds.len(),
            2,
            "catch/normal join block must have 2 predecessors, got {}",
            phi_block.preds.len()
        );
        let phi_for_x = phi_block
            .phis
            .iter()
            .find(|p| p.var_name.as_deref() == Some("x"))
            .unwrap();
        if let SsaOp::Phi(ref operands) = phi_for_x.op {
            assert_eq!(
                operands.len(),
                2,
                "phi for `x` at the catch/normal join must have one operand per \
                 predecessor, got {}",
                operands.len()
            );
        } else {
            panic!("expected SsaOp::Phi for `x`");
        }
    }

    /// Regression guard for the Undef fill pass. When a variable is
    /// only defined on one branch of a join (e.g. a catch-only binding
    /// rejoining the normal path), the lowering must still emit one
    /// phi operand per predecessor, the missing edge becoming a
    /// reference to the synthesized `SsaOp::Undef` sentinel rather
    /// than being dropped.
    #[test]
    fn partial_phi_edge_fills_with_undef_sentinel() {
        // Entry → Body → Join
        //        //        Catch (defines `e`) → Join
        //
        // `e` is defined only on the exception path; on the normal path
        // from Body → Join it has no reaching definition. The phi for `e`
        // at Join must have two operands (one per predecessor), with the
        // Body-side operand pointing at the Undef sentinel.
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let body = cfg.add_node(make_node(StmtKind::Seq));
        let catch = cfg.add_node(NodeInfo {
            catch_param: true,
            taint: TaintMeta {
                defines: Some("e".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["e".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, body, EdgeKind::Seq);
        cfg.add_edge(body, join, EdgeKind::Seq);
        cfg.add_edge(body, catch, EdgeKind::Exception);
        cfg.add_edge(catch, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Find the phi for `e`.
        let phi_block = ssa
            .blocks
            .iter()
            .find(|b| b.phis.iter().any(|p| p.var_name.as_deref() == Some("e")))
            .expect("expected a phi for `e`");
        let phi_for_e = phi_block
            .phis
            .iter()
            .find(|p| p.var_name.as_deref() == Some("e"))
            .unwrap();
        let operands = match &phi_for_e.op {
            SsaOp::Phi(ops) => ops,
            _ => panic!("expected SsaOp::Phi for `e`"),
        };

        // Strict invariant: one operand per predecessor.
        assert_eq!(
            operands.len(),
            phi_block.preds.len(),
            "phi for `e` must have one operand per predecessor",
        );

        // At least one operand must reference the Undef sentinel (the
        // Body-side edge where `e` has no reaching definition).
        let found_inst = |v: SsaValue| -> Option<&SsaInst> {
            ssa.blocks
                .iter()
                .flat_map(|b| b.phis.iter().chain(b.body.iter()))
                .find(|i| i.value == v)
        };
        let any_undef = operands.iter().any(|(_, v)| {
            found_inst(*v)
                .map(|i| matches!(i.op, SsaOp::Undef))
                .unwrap_or(false)
        });
        assert!(
            any_undef,
            "phi for `e` at the catch-join must reference SsaOp::Undef \
             on the normal-path predecessor edge",
        );
    }

    #[test]
    fn phi_assertion_helper_accepts_exact_operand_count() {
        // Direct test of the assertion helper: a phi with exactly as many
        // operands as the block has predecessors must not panic.
        let dummy_node = NodeIndex::new(0);
        let block = SsaBlock {
            id: BlockId(1),
            phis: vec![SsaInst {
                value: SsaValue(0),
                op: SsaOp::Phi(smallvec::smallvec![
                    (BlockId(0), SsaValue(1)),
                    (BlockId(2), SsaValue(2)),
                ]),
                cfg_node: dummy_node,
                var_name: Some("x".into()),
                span: (0, 0),
            }],
            body: vec![],
            terminator: Terminator::Unreachable,
            preds: smallvec::smallvec![BlockId(0), BlockId(2)],
            succs: smallvec::smallvec![],
        };
        let block_preds = vec![vec![], vec![0, 2], vec![0]];
        assert_phi_operand_counts(
            &[
                SsaBlock {
                    id: BlockId(0),
                    phis: vec![],
                    body: vec![],
                    terminator: Terminator::Goto(BlockId(1)),
                    preds: smallvec::smallvec![],
                    succs: smallvec::smallvec![BlockId(1)],
                },
                block,
                SsaBlock {
                    id: BlockId(2),
                    phis: vec![],
                    body: vec![],
                    terminator: Terminator::Goto(BlockId(1)),
                    preds: smallvec::smallvec![BlockId(0)],
                    succs: smallvec::smallvec![BlockId(1)],
                },
            ],
            &block_preds,
        );
    }

    #[test]
    #[should_panic(expected = "SSA phi operand count does not match predecessor count")]
    fn phi_assertion_helper_rejects_more_operands_than_preds() {
        // A phi with MORE operands than preds references a nonexistent
        // predecessor, unsound because downstream consumers either
        // panic on the lookup or silently feed garbage taint into the
        // join. Strict-equality invariant catches this.
        let dummy_node = NodeIndex::new(0);
        let block = SsaBlock {
            id: BlockId(1),
            phis: vec![SsaInst {
                value: SsaValue(0),
                op: SsaOp::Phi(smallvec::smallvec![
                    (BlockId(0), SsaValue(1)),
                    (BlockId(2), SsaValue(2)),
                    (BlockId(3), SsaValue(3)),
                ]),
                cfg_node: dummy_node,
                var_name: Some("x".into()),
                span: (0, 0),
            }],
            body: vec![],
            terminator: Terminator::Unreachable,
            preds: smallvec::smallvec![BlockId(0), BlockId(2)],
            succs: smallvec::smallvec![],
        };
        let block_preds = vec![vec![], vec![0, 2]];
        assert_phi_operand_counts(
            &[
                SsaBlock {
                    id: BlockId(0),
                    phis: vec![],
                    body: vec![],
                    terminator: Terminator::Goto(BlockId(1)),
                    preds: smallvec::smallvec![],
                    succs: smallvec::smallvec![BlockId(1)],
                },
                block,
            ],
            &block_preds,
        );
    }

    #[test]
    #[should_panic(expected = "SSA phi operand count does not match predecessor count")]
    fn phi_assertion_helper_rejects_fewer_operands_than_preds() {
        // A phi with fewer operands than preds violates the strict-equality
        // invariant: `fill_undef_phi_operands` is responsible for filling
        // every missing slot with an Undef sentinel, so the final body
        // should never have gaps. This test guards the post-pass.
        let dummy_node = NodeIndex::new(0);
        let block = SsaBlock {
            id: BlockId(1),
            phis: vec![SsaInst {
                value: SsaValue(0),
                op: SsaOp::Phi(smallvec::smallvec![(BlockId(0), SsaValue(1))]),
                cfg_node: dummy_node,
                var_name: Some("e".into()),
                span: (0, 0),
            }],
            body: vec![],
            terminator: Terminator::Unreachable,
            preds: smallvec::smallvec![BlockId(0), BlockId(2)],
            succs: smallvec::smallvec![],
        };
        let block_preds = vec![vec![], vec![0, 2]];
        assert_phi_operand_counts(
            &[
                SsaBlock {
                    id: BlockId(0),
                    phis: vec![],
                    body: vec![],
                    terminator: Terminator::Goto(BlockId(1)),
                    preds: smallvec::smallvec![],
                    succs: smallvec::smallvec![BlockId(1)],
                },
                block,
            ],
            &block_preds,
        );
    }

    #[test]
    #[should_panic(expected = "SSA phi operand references nonexistent predecessor")]
    fn phi_assertion_helper_rejects_wrong_pred_block() {
        // A phi with the correct operand count but referencing a block
        // that isn't actually a predecessor must also fail the invariant.
        let dummy_node = NodeIndex::new(0);
        let block = SsaBlock {
            id: BlockId(1),
            phis: vec![SsaInst {
                value: SsaValue(0),
                op: SsaOp::Phi(smallvec::smallvec![
                    (BlockId(0), SsaValue(1)),
                    (BlockId(3), SsaValue(2)),
                ]),
                cfg_node: dummy_node,
                var_name: Some("x".into()),
                span: (0, 0),
            }],
            body: vec![],
            terminator: Terminator::Unreachable,
            preds: smallvec::smallvec![BlockId(0), BlockId(2)],
            succs: smallvec::smallvec![],
        };
        let block_preds = vec![vec![], vec![0, 2]];
        assert_phi_operand_counts(
            &[
                SsaBlock {
                    id: BlockId(0),
                    phis: vec![],
                    body: vec![],
                    terminator: Terminator::Goto(BlockId(1)),
                    preds: smallvec::smallvec![],
                    succs: smallvec::smallvec![BlockId(1)],
                },
                block,
            ],
            &block_preds,
        );
    }

    #[test]
    fn three_successor_collapse_produces_switch() {
        // Build a CFG where a single node has 3 successors. The
        // structured `Terminator::Switch` replaced the old
        // `Goto(first)` collapse so every target is visible on the
        // terminator shape (not only on `block.succs`).
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let branch = cfg.add_node(make_node(StmtKind::If));
        let s0 = cfg.add_node(make_node(StmtKind::Seq));
        let s1 = cfg.add_node(make_node(StmtKind::Seq));
        let s2 = cfg.add_node(make_node(StmtKind::Seq));
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, branch, EdgeKind::Seq);
        cfg.add_edge(branch, s0, EdgeKind::True);
        cfg.add_edge(branch, s1, EdgeKind::False);
        cfg.add_edge(branch, s2, EdgeKind::Seq);
        cfg.add_edge(s0, exit, EdgeKind::Seq);
        cfg.add_edge(s1, exit, EdgeKind::Seq);
        cfg.add_edge(s2, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        assert!(!ssa.blocks.is_empty());

        let switch_block = ssa
            .blocks
            .iter()
            .find(|b| matches!(b.terminator, Terminator::Switch { .. }) && b.succs.len() >= 3)
            .expect("expected a block with a Switch terminator and ≥3 succs");

        assert_eq!(
            switch_block.succs.len(),
            3,
            "≥3-successor lowering must retain all succs on block.succs, got {:?}",
            switch_block.succs
        );

        if let Terminator::Switch {
            targets, default, ..
        } = &switch_block.terminator
        {
            // Default is the first succ (deterministic ordering); the
            // remaining N-1 succs populate `targets` in order.
            assert_eq!(
                *default, switch_block.succs[0],
                "Switch default must match succs[0]"
            );
            assert_eq!(
                targets.len(),
                switch_block.succs.len() - 1,
                "Switch targets must cover every succ except default"
            );
            for (i, t) in targets.iter().enumerate() {
                assert_eq!(
                    *t,
                    switch_block.succs[i + 1],
                    "Switch target[{i}] must match succs[{}]",
                    i + 1
                );
            }
        }
    }

    #[test]
    fn normal_two_successor_produces_branch() {
        // Regression: normal 2-successor case should still produce Branch
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let if_node = cfg.add_node(make_node(StmtKind::If));
        let t = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let f = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, if_node, EdgeKind::Seq);
        cfg.add_edge(if_node, t, EdgeKind::True);
        cfg.add_edge(if_node, f, EdgeKind::False);
        cfg.add_edge(t, exit, EdgeKind::Seq);
        cfg.add_edge(f, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        let has_branch = ssa
            .blocks
            .iter()
            .any(|b| matches!(b.terminator, Terminator::Branch { .. }));
        assert!(
            has_branch,
            "normal 2-successor case must produce Branch, not Goto"
        );
    }

    /// Regression: a block containing an explicit Return CFG node must
    /// terminate with [`Terminator::Return`], never [`Terminator::Goto`]
    /// to a synthetic exit block.  Previously, the bookkeeping
    /// `Return → fn_exit` `Seq` edge made early-return blocks fall into
    /// the single-successor `Goto` arm, and the fall-through tail
    /// expression's body got merged into the shared exit block, every
    /// early-return path therefore appeared to also execute the tail.
    /// Mirrors the `if cond { return X; } Y` shape that motivated the fix.
    #[test]
    fn early_return_block_terminates_with_return_not_goto_to_exit() {
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        // Param-style external use (x is read by the if condition).
        let if_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::If)
        });
        // True branch: return constant.  uses=[] + const_text=Some triggers
        // the literal-return path, ensuring the block emits a synthetic
        // Const + Return(Some(_)), the same shape `return None` /
        // `return String::new()` produces in real Rust code.
        let early_ret = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                const_text: Some("\"\"".to_string()),
                ..Default::default()
            },
            ..make_node(StmtKind::Return)
        });
        // False branch: tail expression that defines `y` (the implicit
        // function return value).
        let tail = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("y".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, if_node, EdgeKind::Seq);
        cfg.add_edge(if_node, early_ret, EdgeKind::True);
        cfg.add_edge(if_node, tail, EdgeKind::False);
        // Bookkeeping wire-up the real CFG construction performs in
        // `build_cfg`, Return / Throw → fn_exit via Seq, so the SSA
        // lowering has to handle it.
        cfg.add_edge(early_ret, exit, EdgeKind::Seq);
        cfg.add_edge(tail, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Locate the block containing the early-return CFG node and
        // assert it terminates with Return, not Goto(_) into the
        // shared exit block.
        let early_block = ssa
            .blocks
            .iter()
            .find(|b| {
                b.body
                    .iter()
                    .chain(b.phis.iter())
                    .any(|inst| inst.cfg_node == early_ret)
            })
            .expect("early-return CFG node must live in some SSA block");
        assert!(
            matches!(early_block.terminator, Terminator::Return(_)),
            "early-return block must terminate with Return, got {:?}",
            early_block.terminator
        );
        assert!(
            early_block.succs.is_empty(),
            "early-return block must have no successors at the block level, \
             got succs = {:?}",
            early_block.succs
        );

        // The fall-through (tail) block must NOT have the early-return
        // block as a predecessor.  Pre-fix, both the early-return path
        // and the tail path merged into the shared fn_exit block, so the
        // tail's body was reachable from the early-return path, that's
        // the merged-return defect.
        let tail_block = ssa
            .blocks
            .iter()
            .find(|b| {
                b.body
                    .iter()
                    .chain(b.phis.iter())
                    .any(|inst| inst.cfg_node == tail)
            })
            .expect("tail CFG node must live in some SSA block");
        let early_block_id = early_block.id;
        assert!(
            !tail_block.preds.contains(&early_block_id),
            "tail block must not have early-return block as a predecessor; \
             merged-return defect would re-emerge.  tail.preds = {:?}, \
             early_block_id = {:?}",
            tail_block.preds,
            early_block_id
        );
    }

    /// Regression: an OR-chain rejection arm such as
    /// `if a || b || c { return X; } Y` must have its rejection body emit a
    /// `Terminator::Return(_)` and have `succs.is_empty()`.  Pre-fix the
    /// rejection body's String::new() Call shared a block whose only
    /// successor was the merged tail, losing the early-return semantics
    /// entirely and diluting per-return-path PathFact narrowing.
    #[test]
    fn or_chain_rejection_block_terminates_with_return() {
        use crate::cfg::build_cfg;

        let src = br#"
            fn sanitize_path(s: &str) -> String {
                if s.contains("..") || s.starts_with('/') || s.starts_with('\\') {
                    return String::new();
                }
                s.to_string()
            }
        "#;
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter::Language::from(tree_sitter_rust::LANGUAGE))
            .unwrap();
        let tree = parser.parse(src.as_slice(), None).unwrap();
        let file_cfg = build_cfg(&tree, src.as_slice(), "rust", "test.rs", None);
        let body = if file_cfg.bodies.len() > 1 {
            &file_cfg.bodies[1]
        } else {
            file_cfg.first_body()
        };
        let cfg = &body.graph;
        let entry = body.entry;

        // Locate the Return CFG node sourced from the if-body and the tail
        // expression's Call node so the assertions are meaningful even if
        // block ordering shifts.
        let mut rejection_call: Option<NodeIndex> = None;
        for idx in cfg.node_indices() {
            let info = &cfg[idx];
            if info.kind == StmtKind::Call {
                if let Some(callee) = &info.call.callee {
                    if callee == "String::new" || callee.ends_with("String::new") {
                        rejection_call = Some(idx);
                    }
                }
            }
        }
        let rejection_call = rejection_call
            .expect("CFG must contain a String::new() Call node for the rejection arm");

        let ssa = lower_to_ssa(cfg, entry, None, true).expect("SSA lowering should succeed");

        // Find the SSA block containing the String::new() Call.  This is
        // the rejection-arm block.
        let rejection_block = ssa
            .blocks
            .iter()
            .find(|b| {
                b.body
                    .iter()
                    .chain(b.phis.iter())
                    .any(|inst| inst.cfg_node == rejection_call)
            })
            .expect("rejection-arm Call must live in some SSA block");

        assert!(
            rejection_block.succs.is_empty(),
            "rejection-arm block must have no block-level successors after \
             return-frontier strip; got succs = {:?}",
            rejection_block.succs
        );
        assert!(
            matches!(rejection_block.terminator, Terminator::Return(_)),
            "rejection-arm block must terminate with Terminator::Return; got {:?}",
            rejection_block.terminator
        );
    }

    /// Cross-language regression: the same merged-return defect that the Rust
    /// fix closed must not appear in C. The C OR-chain shape from
    /// `tests/benchmark/corpus/c/safe/safe_direct_path_sanitizer.c` has both
    /// a rejection arm (`return ""`) and a tail return (`return s`).  Both
    /// must produce blocks whose terminator is `Terminator::Return(_)`.
    #[test]
    fn c_or_chain_both_return_arms_terminate_with_return() {
        use crate::cfg::build_cfg;

        let src = br#"
            const char *sanitize_path(const char *s) {
                if (strstr(s, "..") != NULL || s[0] == '/' || s[0] == '\\') {
                    return "";
                }
                return s;
            }
        "#;
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter::Language::from(tree_sitter_c::LANGUAGE))
            .unwrap();
        let tree = parser.parse(src.as_slice(), None).unwrap();
        let file_cfg = build_cfg(&tree, src.as_slice(), "c", "test.c", None);
        let body = file_cfg.first_body();
        let cfg = &body.graph;
        let entry = body.entry;

        let ssa = lower_to_ssa(cfg, entry, None, true).expect("SSA lowering should succeed");

        let return_blocks: Vec<&SsaBlock> = ssa
            .blocks
            .iter()
            .filter(|b| matches!(b.terminator, Terminator::Return(_)))
            .collect();
        assert!(
            return_blocks.len() >= 2,
            "Expected ≥2 Return-terminated blocks (rejection arm + tail); got {}: {:?}",
            return_blocks.len(),
            ssa.blocks
                .iter()
                .map(|b| (b.id, &b.terminator))
                .collect::<Vec<_>>()
        );

        // Each Return-terminated block must have an empty successor list
        // (no fall-through past Return).
        for b in &return_blocks {
            assert!(
                b.succs.is_empty(),
                "Return-terminated block id={:?} has succs={:?}",
                b.id,
                b.succs
            );
        }
    }

    // ─────────────────────────────────────────────────────────────────
    // FieldProj chain lowering tests
    // ─────────────────────────────────────────────────────────────────
    //
    // These tests pin the contract that `try_lower_field_proj_chain`
    // emits a `FieldProj` chain for chained-receiver method calls
    // (`a.b.c.method()`) and bails (preserving the existing single-Call
    // lowering) for everything else.  Per-language end-to-end coverage
    // lives below in `phase2_e2e_*` tests; the unit tests here pin the
    // helper's behaviour without going through tree-sitter.

    /// Build a freshly-allocated empty SSA scratch state suitable for
    /// invoking `try_lower_field_proj_chain` in isolation.  Returns
    /// `(var_stacks, field_interner, ssa_blocks, value_defs, next_value)`.
    fn fresh_proj_scratch() -> (
        std::collections::HashMap<String, Vec<SsaValue>>,
        crate::ssa::ir::FieldInterner,
        Vec<SsaBlock>,
        Vec<ValueDef>,
        u32,
    ) {
        let blocks = vec![SsaBlock {
            id: BlockId(0),
            phis: Vec::new(),
            body: Vec::new(),
            terminator: Terminator::Unreachable,
            preds: SmallVec::new(),
            succs: SmallVec::new(),
        }];
        (
            std::collections::HashMap::new(),
            crate::ssa::ir::FieldInterner::new(),
            blocks,
            Vec::new(),
            0,
        )
    }

    /// Seed a single SSA value `SsaValue(0)` for `name` so the chain
    /// helper's base lookup succeeds.
    fn seed_var(
        var_stacks: &mut std::collections::HashMap<String, Vec<SsaValue>>,
        value_defs: &mut Vec<ValueDef>,
        next_value: &mut u32,
        name: &str,
    ) -> SsaValue {
        let v = SsaValue(*next_value);
        *next_value += 1;
        value_defs.push(ValueDef {
            var_name: Some(name.into()),
            cfg_node: NodeIndex::new(0),
            block: BlockId(0),
        });
        var_stacks.entry(name.into()).or_default().push(v);
        v
    }

    #[test]
    fn try_lower_field_proj_chain_too_few_segments_returns_none() {
        // 0 dots: bare callee → no chain.
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        seed_var(&mut vs, &mut defs, &mut nv, "obj");
        assert!(
            try_lower_field_proj_chain(
                "foo",
                &vs,
                &mut interner,
                0,
                BlockId(0),
                &mut nv,
                &mut blocks,
                &mut defs,
                NodeIndex::new(0),
                (0, 0),
            )
            .is_none()
        );

        // 1 dot: simple receiver, NOT decomposed (existing receiver channel
        // already handles `obj.method()` calls).
        assert!(
            try_lower_field_proj_chain(
                "obj.method",
                &vs,
                &mut interner,
                0,
                BlockId(0),
                &mut nv,
                &mut blocks,
                &mut defs,
                NodeIndex::new(0),
                (0, 0),
            )
            .is_none()
        );

        // No FieldProj instructions emitted; interner stays empty.
        assert!(blocks[0].body.is_empty());
        assert!(interner.is_empty());
    }

    #[test]
    fn try_lower_field_proj_chain_complex_token_returns_none() {
        // Each of these contains a token signaling complexity that breaks
        // the simple `<ident>.<ident>...` shape; helper must bail.
        let cases = [
            "Foo::bar::baz", // Rust path
            "ptr->field.f",  // C-style arrow
            "obj.f().g",     // intermediate call
            "vec[0].field",  // index expression
            "obj.f.<T>",     // template-ish
            "obj.f g",       // whitespace
            "obj?.f.g",      // optional chain
        ];
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        seed_var(&mut vs, &mut defs, &mut nv, "obj");
        for s in &cases {
            assert!(
                try_lower_field_proj_chain(
                    s,
                    &vs,
                    &mut interner,
                    0,
                    BlockId(0),
                    &mut nv,
                    &mut blocks,
                    &mut defs,
                    NodeIndex::new(0),
                    (0, 0),
                )
                .is_none(),
                "expected bail on complex callee {s}"
            );
        }
        assert!(blocks[0].body.is_empty());
        assert!(interner.is_empty());
    }

    #[test]
    fn try_lower_field_proj_chain_unknown_base_returns_none() {
        // The chain root must be a known SSA variable; otherwise the chain
        // root SSA value is unrecoverable and we must fall back.
        let (vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        // "ghost" intentionally not seeded.
        assert!(
            try_lower_field_proj_chain(
                "ghost.f.method",
                &vs,
                &mut interner,
                0,
                BlockId(0),
                &mut nv,
                &mut blocks,
                &mut defs,
                NodeIndex::new(0),
                (0, 0),
            )
            .is_none()
        );
        assert!(blocks[0].body.is_empty());
        assert!(interner.is_empty());
    }

    #[test]
    fn try_lower_field_proj_chain_basic_two_dots_emits_one_proj() {
        // `c.mu.Lock()` → emit one FieldProj, return (v_mu, "Lock").
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        let v_c = seed_var(&mut vs, &mut defs, &mut nv, "c");

        let (recv, method) = try_lower_field_proj_chain(
            "c.mu.Lock",
            &vs,
            &mut interner,
            0,
            BlockId(0),
            &mut nv,
            &mut blocks,
            &mut defs,
            NodeIndex::new(0),
            (10, 20),
        )
        .expect("chain decomposition should succeed");

        // The returned receiver is a NEW SsaValue (one past v_c).
        assert_eq!(recv, SsaValue(1));
        assert_eq!(method, "Lock");
        // Exactly one FieldProj op was emitted.
        assert_eq!(blocks[0].body.len(), 1);
        let inst = &blocks[0].body[0];
        match &inst.op {
            SsaOp::FieldProj {
                receiver,
                field,
                projected_type,
            } => {
                assert_eq!(*receiver, v_c);
                assert_eq!(interner.resolve(*field), "mu");
                assert!(projected_type.is_none());
            }
            other => panic!("expected FieldProj, got {other:?}"),
        }
        // Span propagated to the FieldProj instruction.
        assert_eq!(inst.span, (10, 20));
        assert_eq!(inst.var_name.as_deref(), Some("c.mu"));
        // value_defs has an entry for the new SSA value.
        assert_eq!(defs.last().unwrap().var_name.as_deref(), Some("c.mu"));
    }

    #[test]
    fn try_lower_field_proj_chain_three_dots_emits_two_projs_chained() {
        // `c.writer.header.set` → 2 FieldProj ops, chained: v_writer reads c,
        // v_header reads v_writer.
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        let v_c = seed_var(&mut vs, &mut defs, &mut nv, "c");

        let (recv, method) = try_lower_field_proj_chain(
            "c.writer.header.set",
            &vs,
            &mut interner,
            0,
            BlockId(0),
            &mut nv,
            &mut blocks,
            &mut defs,
            NodeIndex::new(0),
            (0, 0),
        )
        .expect("chain decomposition should succeed");
        assert_eq!(method, "set");
        assert_eq!(recv, SsaValue(2)); // v_c=0, v_writer=1, v_header=2

        assert_eq!(blocks[0].body.len(), 2, "expected 2 FieldProj ops");
        match &blocks[0].body[0].op {
            SsaOp::FieldProj {
                receiver, field, ..
            } => {
                assert_eq!(*receiver, v_c);
                assert_eq!(interner.resolve(*field), "writer");
            }
            other => panic!("expected FieldProj, got {other:?}"),
        }
        match &blocks[0].body[1].op {
            SsaOp::FieldProj {
                receiver, field, ..
            } => {
                assert_eq!(*receiver, SsaValue(1)); // chained on v_writer
                assert_eq!(interner.resolve(*field), "header");
            }
            other => panic!("expected FieldProj, got {other:?}"),
        }
        // var_names form a readable chain
        assert_eq!(blocks[0].body[0].var_name.as_deref(), Some("c.writer"));
        assert_eq!(
            blocks[0].body[1].var_name.as_deref(),
            Some("c.writer.header")
        );
    }

    #[test]
    fn try_lower_field_proj_chain_dedupes_field_names() {
        // Two separate chains that share a field name should reuse the
        // same FieldId via the per-body interner.
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        let v_a = seed_var(&mut vs, &mut defs, &mut nv, "a");
        let v_b = seed_var(&mut vs, &mut defs, &mut nv, "b");

        let _ = try_lower_field_proj_chain(
            "a.shared.f",
            &vs,
            &mut interner,
            0,
            BlockId(0),
            &mut nv,
            &mut blocks,
            &mut defs,
            NodeIndex::new(0),
            (0, 0),
        )
        .unwrap();
        let _ = try_lower_field_proj_chain(
            "b.shared.g",
            &vs,
            &mut interner,
            0,
            BlockId(0),
            &mut nv,
            &mut blocks,
            &mut defs,
            NodeIndex::new(0),
            (0, 0),
        )
        .unwrap();

        // Two FieldProj insts emitted, both pointing at the same FieldId.
        assert_eq!(blocks[0].body.len(), 2);
        let f0 = match &blocks[0].body[0].op {
            SsaOp::FieldProj { field, .. } => *field,
            _ => panic!(),
        };
        let f1 = match &blocks[0].body[1].op {
            SsaOp::FieldProj { field, .. } => *field,
            _ => panic!(),
        };
        assert_eq!(f0, f1, "dedup should reuse FieldId");
        assert_eq!(interner.len(), 1, "only one unique field name interned");
        let _ = (v_a, v_b);
    }

    #[test]
    fn try_lower_field_proj_chain_rejects_empty_segments() {
        // Defensive: leading/trailing/double dots are not a member chain.
        let (mut vs, mut interner, mut blocks, mut defs, mut nv) = fresh_proj_scratch();
        seed_var(&mut vs, &mut defs, &mut nv, "x");
        for s in [".x.f", "x..f", "x.f."] {
            assert!(
                try_lower_field_proj_chain(
                    s,
                    &vs,
                    &mut interner,
                    0,
                    BlockId(0),
                    &mut nv,
                    &mut blocks,
                    &mut defs,
                    NodeIndex::new(0),
                    (0, 0),
                )
                .is_none(),
                "expected bail on {s}"
            );
        }
        assert!(blocks[0].body.is_empty());
    }

    // ── End-to-end SSA decomposition tests via real tree-sitter parsing ──────────
    //
    // These exercise the integration between CFG construction (which sets
    // `info.call.callee = "c.mu.Lock"`) and SSA lowering.  We assert that
    // the resulting SsaBody contains a `FieldProj` op whose interned name
    // matches the source-level field name.

    fn parse_to_first_body(
        src: &[u8],
        lang: &str,
        ts_lang: tree_sitter::Language,
        path: &str,
    ) -> SsaBody {
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_lang).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let file_cfg = crate::cfg::build_cfg(&tree, src, lang, path, None);
        // Prefer the first non-top-level body (a function), fall back to top.
        let body = if file_cfg.bodies.len() > 1 {
            &file_cfg.bodies[1]
        } else {
            &file_cfg.bodies[0]
        };
        // Mirror the production lowering path: function bodies use
        // lower_to_ssa_with_params so formal parameters get synthetic
        // Param/SelfParam injections at block 0, without them, the
        // FieldProj chain helper has no SSA root to anchor to.
        if body.meta.name.is_some() {
            let func_name = body.meta.name.clone().unwrap_or_default();
            lower_to_ssa_with_params(
                &body.graph,
                body.entry,
                Some(&func_name),
                false,
                &body.meta.params,
            )
            .expect("SSA lowering should succeed")
        } else {
            lower_to_ssa(&body.graph, body.entry, None, true).expect("SSA lowering should succeed")
        }
    }

    /// Iterate every FieldProj instance in `body` along with its resolved
    /// field name.
    fn collect_field_projs(body: &SsaBody) -> Vec<(SsaValue, SsaValue, String)> {
        let mut out = Vec::new();
        for blk in &body.blocks {
            for inst in blk.phis.iter().chain(blk.body.iter()) {
                if let SsaOp::FieldProj {
                    receiver, field, ..
                } = &inst.op
                {
                    out.push((inst.value, *receiver, body.field_name(*field).to_string()));
                }
            }
        }
        out
    }

    /// Iterate every Call instance in `body` along with its callee + callee_text.
    fn collect_calls(body: &SsaBody) -> Vec<(String, Option<String>, Option<SsaValue>)> {
        let mut out = Vec::new();
        for blk in &body.blocks {
            for inst in blk.body.iter() {
                if let SsaOp::Call {
                    callee,
                    callee_text,
                    receiver,
                    ..
                } = &inst.op
                {
                    out.push((callee.clone(), callee_text.clone(), *receiver));
                }
            }
        }
        out
    }

    #[test]
    fn phase2_e2e_go_chained_receiver_emits_field_proj() {
        // Go: `c.writer.header.set(k, v)`, 3-segment receiver, 2 FieldProjs.
        // Chain root `c` is a function parameter so it is resolvable.
        let src = b"package p\nfunc f(c *T, k string, v string) { c.writer.header.set(k, v) }\n";
        let body = parse_to_first_body(
            src,
            "go",
            tree_sitter::Language::from(tree_sitter_go::LANGUAGE),
            "test.go",
        );
        let projs = collect_field_projs(&body);
        assert!(
            projs.len() >= 2,
            "expected ≥2 FieldProj ops for c.writer.header.<m>; got {projs:?}"
        );
        // Field names match the source-level field structure.
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"writer"),
            "missing 'writer' projection in {names:?}"
        );
        assert!(
            names.contains(&"header"),
            "missing 'header' projection in {names:?}"
        );

        // The Call op carries the bare method name and callee_text retains the path.
        let calls = collect_calls(&body);
        let bare = calls.iter().find(|(c, _, _)| c == "set");
        assert!(
            bare.is_some(),
            "expected a Call with bare callee 'set'; got {calls:?}"
        );
        let (_, ctext, recv) = bare.unwrap();
        assert!(recv.is_some(), "decomposed call must carry an SSA receiver");
        assert_eq!(
            ctext.as_deref(),
            Some("c.writer.header.set"),
            "callee_text should preserve the original textual path"
        );
    }

    #[test]
    fn phase2_e2e_python_chained_receiver_emits_field_proj() {
        // Python: `obj.client.session.send(p)`, 3-segment receiver.
        let src = b"def f(obj, p):\n    obj.client.session.send(p)\n";
        let body = parse_to_first_body(
            src,
            "python",
            tree_sitter::Language::from(tree_sitter_python::LANGUAGE),
            "test.py",
        );
        let projs = collect_field_projs(&body);
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"client") && names.contains(&"session"),
            "expected client + session projections, got {names:?}"
        );
        let calls = collect_calls(&body);
        assert!(
            calls.iter().any(|(c, ct, r)| c == "send"
                && ct.as_deref() == Some("obj.client.session.send")
                && r.is_some()),
            "expected bare 'send' Call with callee_text retained; got {calls:?}"
        );
    }

    #[test]
    fn phase2_e2e_javascript_chained_receiver_emits_field_proj() {
        // JS: `obj.foo.bar.baz()`, 3-segment receiver.
        let src = b"function f(obj) { obj.foo.bar.baz(); }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        let projs = collect_field_projs(&body);
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"foo") && names.contains(&"bar"),
            "expected foo + bar projections, got {names:?}"
        );
    }

    #[test]
    fn phase2_e2e_java_chained_receiver_emits_field_proj() {
        // Java: `obj.config.handler.run()`, 3-segment receiver chain through
        // a parameter `obj`.  We avoid `this.…` because `this` is a Java
        // keyword (not an identifier_node) so it isn't extracted as an
        // external use, outside SSA decomposition.s scope.
        let src = b"class C { void f(Object obj) { obj.config.handler.run(); } }";
        let body = parse_to_first_body(
            src,
            "java",
            tree_sitter::Language::from(tree_sitter_java::LANGUAGE),
            "test.java",
        );
        let projs = collect_field_projs(&body);
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"config") && names.contains(&"handler"),
            "expected config + handler projections, got {names:?}; full body:\n{body}"
        );
        let calls = collect_calls(&body);
        assert!(
            calls.iter().any(|(c, ct, r)| c == "run"
                && ct.as_deref() == Some("obj.config.handler.run")
                && r.is_some()),
            "expected bare 'run' Call with callee_text retained; got {calls:?}"
        );
    }

    #[test]
    fn phase2_e2e_simple_receiver_no_field_proj() {
        // REGRESSION: `obj.foo()`, single-dot receiver.  SSA lowering must NOT
        // decompose this into a FieldProj chain (existing receiver channel
        // already covers it).  Verify the body has zero FieldProj ops and
        // the Call's callee_text stays None.
        let src = b"function f(obj) { obj.foo(); }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        assert!(
            collect_field_projs(&body).is_empty(),
            "single-dot call should not generate FieldProj"
        );
        let calls = collect_calls(&body);
        assert!(
            calls.iter().any(|(_, ct, _)| ct.is_none()),
            "single-dot Call should have callee_text=None; calls={calls:?}"
        );
    }

    #[test]
    fn phase2_e2e_bare_call_no_field_proj() {
        // REGRESSION: a free-function call `foo()` must produce zero
        // FieldProj ops and an empty per-body interner.
        let src = b"function f() { foo(1, 2); }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        assert!(collect_field_projs(&body).is_empty());
        assert!(
            body.field_interner.is_empty(),
            "no chain → interner stays empty"
        );
    }

    #[test]
    fn phase2_e2e_global_root_chain_still_emits_field_proj() {
        // REGRESSION-NEGATIVE: when the chain root is a global identifier
        // (`Math.foo.bar()`), the lowerer's external-var synthesis makes
        // `Math` available as a synthetic Param, the chain still
        // decomposes, treating `Math` as the SSA receiver.  This is the
        // semantically correct outcome even for global-rooted chains: the
        // FieldProj op precisely captures the field-access structure.
        let src = b"function f() { Math.foo.bar(); }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        let projs = collect_field_projs(&body);
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"foo"),
            "expected 'foo' projection (chain root Math is a synthesized external var); got {names:?}"
        );
    }

    #[test]
    fn phase2_e2e_rust_method_call_through_field_emits_field_proj() {
        // Rust: `c.mu.lock()`, `c` is a function parameter, `mu` is a field,
        // `lock` is the method.  Verifies we generate FieldProj for `mu`.
        // (Rust paths like `std::env::var` use `::` and are excluded by
        // the helper's complex-token check.)
        let src = b"fn f(c: &T) { c.mu.lock(); }";
        let body = parse_to_first_body(
            src,
            "rust",
            tree_sitter::Language::from(tree_sitter_rust::LANGUAGE),
            "test.rs",
        );
        let projs = collect_field_projs(&body);
        let names: Vec<&str> = projs.iter().map(|(_, _, n)| n.as_str()).collect();
        assert!(
            names.contains(&"mu"),
            "expected 'mu' projection from c.mu.lock(); got {names:?}; body:\n{body}"
        );
        let calls = collect_calls(&body);
        assert!(
            calls
                .iter()
                .any(|(c, ct, r)| c == "lock" && ct.as_deref() == Some("c.mu.lock") && r.is_some()),
            "expected bare 'lock' Call with callee_text='c.mu.lock'; got {calls:?}"
        );
    }

    #[test]
    fn phase2_e2e_rust_path_call_does_not_emit_field_proj() {
        // REGRESSION: `std::env::var(...)` is a Rust path (uses `::`), NOT
        // a member-access chain.  Helper must bail.
        let src = br#"fn f() { let _ = std::env::var("X"); }"#;
        let body = parse_to_first_body(
            src,
            "rust",
            tree_sitter::Language::from(tree_sitter_rust::LANGUAGE),
            "test.rs",
        );
        assert!(
            collect_field_projs(&body).is_empty(),
            "Rust path expression must not be decomposed into FieldProj"
        );
    }

    #[test]
    fn phase2_e2e_field_interner_populated_only_when_chain_emitted() {
        // Helper invariant: a body with a chained call has a non-empty
        // interner; a body with no chained calls has an empty interner.
        let src_chain = b"function f(o) { o.a.b.c(); }";
        let src_plain = b"function f(o) { o.foo(); }";
        let body_chain = parse_to_first_body(
            src_chain,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        let body_plain = parse_to_first_body(
            src_plain,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        assert!(
            !body_chain.field_interner.is_empty(),
            "interner should hold the chain field names"
        );
        assert!(
            body_plain.field_interner.is_empty(),
            "single-dot call should not populate interner"
        );
    }

    #[test]
    fn phase2_e2e_field_proj_chain_preserves_receiver_dataflow() {
        // The FieldProj receiver chain must trace back to the chain root
        // (parameter `c` here) via `uses_iter()`.  This is the contract
        // every downstream consumer relies on for taint propagation.
        let src = b"function f(c) { c.a.b.m(); }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        let projs = collect_field_projs(&body);
        assert_eq!(projs.len(), 2, "expected 2 FieldProj ops, got {projs:?}");

        // The first FieldProj's receiver should be a parameter or external
        // var; the second FieldProj's receiver should be the first
        // FieldProj's value.
        let v_first = projs[0].0;
        let r_second = projs[1].1;
        assert_eq!(
            r_second, v_first,
            "second FieldProj must chain off the first's value"
        );
    }

    /// End-to-end: lowering an `obj.f = rhs` statement populates
    /// `SsaBody.field_writes` with the synthetic base-update Assign's
    /// `(receiver, FieldId)` mapping. A single-write shape suffices ,
    /// every formal gets a Param op at block 0 so the first write
    /// finds the formal in `var_stacks`.
    #[test]
    fn w1_end_to_end_field_write_records_side_table_when_parent_has_prior_def() {
        // Single write to `obj.cache`: the formal `obj` provides the
        // prior reaching def via the synthetic Param at block 0.
        let src = b"function f(obj) { obj.cache = 42; }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        assert!(
            !body.field_writes.is_empty(),
            "single `obj.cache = 42` on a JS formal must populate \
             field_writes via the formal's W1.b synthetic Param; got \
             body.field_writes={:?}\nbody:\n{body}",
            body.field_writes,
        );
        // Every recorded field name resolves to "cache".
        for (_rcv, fid) in body.field_writes.values() {
            assert_eq!(body.field_interner.resolve(*fid), "cache");
        }
    }

    /// W1.b: Python, single `obj.cache = 42` on a formal also
    /// populates `field_writes` thanks to the formal Param op.
    #[test]
    fn w1b_single_write_records_field_write_python() {
        let src = b"def f(obj):\n    obj.cache = 42\n";
        let body = parse_to_first_body(
            src,
            "python",
            tree_sitter::Language::from(tree_sitter_python::LANGUAGE),
            "test.py",
        );
        assert!(
            !body.field_writes.is_empty(),
            "Python single `obj.cache = 42` must populate field_writes; \
             got body.field_writes={:?}\nbody:\n{body}",
            body.field_writes,
        );
    }

    /// W1.b: Rust, single `obj.cache = 42` on a method-style formal
    /// (`fn f(obj: &mut O)`) also populates `field_writes`.
    #[test]
    fn w1b_single_write_records_field_write_rust() {
        let src = b"struct O { cache: i32 } fn f(obj: &mut O) { obj.cache = 42; }";
        let body = parse_to_first_body(
            src,
            "rust",
            tree_sitter::Language::from(tree_sitter_rust::LANGUAGE),
            "test.rs",
        );
        assert!(
            !body.field_writes.is_empty(),
            "Rust single `obj.cache = 42` must populate field_writes; \
             got body.field_writes={:?}\nbody:\n{body}",
            body.field_writes,
        );
    }

    /// REGRESSION: when the body takes a real handler-named formal
    /// (`userId`), that formal must NOT end up in
    /// `synthetic_externals` — the JS/TS / Java auto-seed pass relies
    /// on this distinction to seed only real formals as
    /// `Source(UserInput)` and skip closure captures.  Companion
    /// integration coverage for the empty-formals shape (arrow
    /// `() => {…}` lifting bubbled-up free vars as synthetic) lives
    /// in `tests/fixtures/fp_guards/framework_jest_test_callback_arrow/`
    /// — that fixture exercises the full CFG construction path which
    /// this unit test cannot reproduce in isolation.
    #[test]
    fn arrow_with_handler_formal_keeps_param_non_synthetic() {
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(NodeInfo {
            ast: crate::cfg::AstMeta {
                enclosing_func: Some("lookup".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Entry)
        });
        let use_node = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["userId".into()],
                ..Default::default()
            },
            ast: crate::cfg::AstMeta {
                enclosing_func: Some("lookup".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(NodeInfo {
            ast: crate::cfg::AstMeta {
                enclosing_func: Some("lookup".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Exit)
        });
        cfg.add_edge(entry, use_node, EdgeKind::Seq);
        cfg.add_edge(use_node, exit, EdgeKind::Seq);

        let formals = vec!["userId".to_string()];
        let body = lower_to_ssa_with_params(&cfg, entry, Some("lookup"), false, &formals)
            .expect("SSA lowering should succeed");
        let user_id_param = body
            .blocks
            .first()
            .and_then(|b| {
                b.body.iter().find(|inst| {
                    matches!(inst.op, SsaOp::Param { .. })
                        && inst.var_name.as_deref() == Some("userId")
                })
            })
            .expect("userId Param should be present");
        assert!(
            !body.synthetic_externals.contains(&user_id_param.value),
            "real formal `userId` must not be marked synthetic; \
             synthetic_externals={:?}",
            body.synthetic_externals,
        );
    }

    /// W1: a plain non-dotted assignment (`x = 1`) records nothing
    /// in `field_writes`.  Strict-additive: existing behaviour is
    /// unchanged for non-field-write shapes.
    #[test]
    fn w1_end_to_end_plain_assign_records_no_field_write() {
        let src = b"function f() { let x = 1; x = 2; }";
        let body = parse_to_first_body(
            src,
            "javascript",
            tree_sitter::Language::from(tree_sitter_javascript::LANGUAGE),
            "test.js",
        );
        assert!(
            body.field_writes.is_empty(),
            "plain assign must not populate field_writes; got {:?}",
            body.field_writes,
        );
    }

    // ─────────────────────────────────────────────────────────────────
    // SSA edge cases: loop induction, multi-variable phis, multiple
    // returns, switch-cases, and shadowing. These plug holes in the
    // dominator-frontier / variable-renaming coverage.
    // ─────────────────────────────────────────────────────────────────

    /// Loop induction variable: `x = x + 1` inside a loop is the
    /// canonical SSA challenge, the body uses `x` then redefines it,
    /// and the join with the entry definition must produce a phi that
    /// distinguishes the entry value from the body's redefinition.
    /// Induction-var pruning depends on this shape being lowered
    /// correctly.
    #[test]
    fn loop_self_assignment_induction_phi_is_distinct() {
        // Entry → x=0 → Loop header → [Body: use x; x = x_new] → Loop
        // The body both uses and defines x, modeling `x = x + 1`.
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let init_x = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let header = cfg.add_node(make_node(StmtKind::Loop));
        let body = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, init_x, EdgeKind::Seq);
        cfg.add_edge(init_x, header, EdgeKind::Seq);
        cfg.add_edge(header, body, EdgeKind::True);
        cfg.add_edge(body, header, EdgeKind::Back);
        cfg.add_edge(header, exit, EdgeKind::False);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // We expect THREE distinct SSA values for `x`:
        //   - init_x (entry value)
        //   - body's redefinition
        //   - the loop-header phi
        let x_defs: Vec<_> = ssa
            .value_defs
            .iter()
            .filter(|vd| vd.var_name.as_deref() == Some("x"))
            .collect();
        assert!(
            x_defs.len() >= 3,
            "expected ≥3 SSA values for x (init, phi, body-redef), got {}",
            x_defs.len()
        );

        // The header's phi for x must have exactly two operands (entry
        // value + back-edge value) and they must NOT both be the same
        // SsaValue (otherwise the renaming collapsed the two arms).
        let phi_ops = ssa
            .blocks
            .iter()
            .flat_map(|b| b.phis.iter())
            .find(|p| p.var_name.as_deref() == Some("x"))
            .and_then(|p| match &p.op {
                SsaOp::Phi(ops) => Some(ops.clone()),
                _ => None,
            })
            .expect("expected a Phi op for x at the loop header");
        assert_eq!(
            phi_ops.len(),
            2,
            "loop header phi for x should have 2 operands, got {}",
            phi_ops.len()
        );
        let unique: HashSet<_> = phi_ops.iter().map(|(_, v)| v).collect();
        assert_eq!(
            unique.len(),
            2,
            "phi operands must be distinct (entry vs back-edge), got {:?}",
            phi_ops
        );
    }

    /// Diamond join with two distinct variables defined in both arms:
    /// the merge block must contain a phi for EACH of the variables,
    /// not just one. Guards against single-variable phi insertion.
    #[test]
    fn diamond_join_produces_phi_per_variable() {
        // Entry → cond → [True: x=1; y=10] → join
        //              ↘ [False: x=2; y=20] ↗
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let cond = cfg.add_node(make_node(StmtKind::If));
        let true_def = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let true_def2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("y".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let false_def = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let false_def2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("y".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let join = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["x".into(), "y".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, cond, EdgeKind::Seq);
        cfg.add_edge(cond, true_def, EdgeKind::True);
        cfg.add_edge(true_def, true_def2, EdgeKind::Seq);
        cfg.add_edge(true_def2, join, EdgeKind::Seq);
        cfg.add_edge(cond, false_def, EdgeKind::False);
        cfg.add_edge(false_def, false_def2, EdgeKind::Seq);
        cfg.add_edge(false_def2, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        let phi_vars: HashSet<&str> = ssa
            .blocks
            .iter()
            .flat_map(|b| b.phis.iter())
            .filter_map(|p| p.var_name.as_deref())
            .collect();
        assert!(
            phi_vars.contains("x"),
            "expected phi for x at diamond join, got {:?}",
            phi_vars
        );
        assert!(
            phi_vars.contains("y"),
            "expected phi for y at diamond join, got {:?}",
            phi_vars
        );
    }

    /// Two reachable Return nodes from different branches must each
    /// produce a `Terminator::Return`. Common before: only the last
    /// CFG-Return survived as a real return, others were Goto'd to
    /// Exit. Regression for the early-return check.
    #[test]
    fn two_branches_with_returns_each_terminates_with_return() {
        // Entry → cond → [True: r1=1; return r1] / [False: r2=2; return r2]
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let cond = cfg.add_node(make_node(StmtKind::If));
        let r1 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("r1".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let ret1 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["r1".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Return)
        });
        let r2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("r2".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let ret2 = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["r2".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Return)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));

        cfg.add_edge(entry, cond, EdgeKind::Seq);
        cfg.add_edge(cond, r1, EdgeKind::True);
        cfg.add_edge(r1, ret1, EdgeKind::Seq);
        cfg.add_edge(ret1, exit, EdgeKind::Seq);
        cfg.add_edge(cond, r2, EdgeKind::False);
        cfg.add_edge(r2, ret2, EdgeKind::Seq);
        cfg.add_edge(ret2, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Count blocks ending with `Terminator::Return(_)`.
        let return_blocks = ssa
            .blocks
            .iter()
            .filter(|b| matches!(&b.terminator, Terminator::Return(_)))
            .count();
        assert_eq!(
            return_blocks, 2,
            "expected 2 Return-terminated blocks, got {}",
            return_blocks
        );
    }

    /// Variable defined ONLY in one branch of a conditional must be
    /// undef on the other path. The phi at the join should include an
    /// undef sentinel for the missing arm, guards against the
    /// renamer silently dropping the missing operand.
    #[test]
    fn conditional_define_only_one_arm_phi_has_undef_operand() {
        // Entry → cond → [True: x=1] → join (uses x)
        //              ↘ [False: nop] ↗
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let cond = cfg.add_node(make_node(StmtKind::If));
        let true_def = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                defines: Some("x".into()),
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let false_nop = cfg.add_node(make_node(StmtKind::Seq));
        let join = cfg.add_node(NodeInfo {
            taint: TaintMeta {
                uses: vec!["x".into()],
                ..Default::default()
            },
            ..make_node(StmtKind::Seq)
        });
        let exit = cfg.add_node(make_node(StmtKind::Exit));
        cfg.add_edge(entry, cond, EdgeKind::Seq);
        cfg.add_edge(cond, true_def, EdgeKind::True);
        cfg.add_edge(true_def, join, EdgeKind::Seq);
        cfg.add_edge(cond, false_nop, EdgeKind::False);
        cfg.add_edge(false_nop, join, EdgeKind::Seq);
        cfg.add_edge(join, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();

        // Find a phi for x and verify it has 2 operands. The "undef"
        // operand can manifest as a Nop-defined SsaValue or a sentinel
        //, both are acceptable; the invariant is that arity == preds.
        let x_phi_ops = ssa
            .blocks
            .iter()
            .flat_map(|b| b.phis.iter())
            .find(|p| p.var_name.as_deref() == Some("x"))
            .and_then(|p| match &p.op {
                SsaOp::Phi(ops) => Some(ops.clone()),
                _ => None,
            });
        if let Some(ops) = x_phi_ops {
            assert_eq!(
                ops.len(),
                2,
                "phi for x at the join must have 2 operands (one per pred), got {}",
                ops.len()
            );
        }
        // Acceptable alternative: SSA may skip phi insertion when one
        // arm is undef. The invariant we care about is that lowering
        // doesn't panic, which `lower_to_ssa(...).unwrap()` already
        // exercises.
    }

    /// `lower_to_ssa` on a CFG with NO definitions of any variable
    /// must still succeed and produce a body with at least entry/exit
    /// blocks. Regression for trivial-function lowering.
    #[test]
    fn empty_function_body_only_entry_and_exit_lowers_cleanly() {
        let mut cfg: Cfg = Graph::new();
        let entry = cfg.add_node(make_node(StmtKind::Entry));
        let exit = cfg.add_node(make_node(StmtKind::Exit));
        cfg.add_edge(entry, exit, EdgeKind::Seq);

        let ssa = lower_to_ssa(&cfg, entry, None, true).unwrap();
        assert!(
            !ssa.blocks.is_empty(),
            "even an empty body should produce at least one block"
        );
        // No phis (nothing converged), no value_defs except possibly
        // entry sentinels. We just assert it lowered without panic.
    }
}