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
use super::*;
use petgraph::visit::EdgeRef;
use tree_sitter::Language;

fn parse_and_build(src: &[u8], lang_str: &str, ts_lang: Language) -> (Cfg, NodeIndex) {
    let file_cfg = parse_to_file_cfg(src, lang_str, ts_lang);
    // If there's a function body, return it (most tests wrap code in a function).
    // Otherwise return the top-level body.
    let body = if file_cfg.bodies.len() > 1 {
        &file_cfg.bodies[1]
    } else {
        &file_cfg.bodies[0]
    };
    (body.graph.clone(), body.entry)
}

fn parse_to_file_cfg(src: &[u8], lang_str: &str, ts_lang: Language) -> FileCfg {
    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&ts_lang).unwrap();
    let tree = parser.parse(src, None).unwrap();
    build_cfg(&tree, src, lang_str, "test.js", None)
}

#[test]
fn js_try_catch_has_exception_edges() {
    let src = b"function f() { try { foo(); } catch (e) { bar(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    assert!(
        !exception_edges.is_empty(),
        "Expected at least one Exception edge"
    );
    // Verify source is a Call node
    for e in &exception_edges {
        assert_eq!(cfg[e.source()].kind, StmtKind::Call);
    }
}

/// When a classifiable call (here `eval`, a built-in JS sink) is nested
/// inside a multi-line statement, the CFG node's `classification_span()`
/// should point at the inner call, not at the outer statement's start ,
/// so finding display reports the line the dangerous call actually lives
/// on.  `ast.span` must still cover the whole outer statement for
/// structural passes that need the statement grain.
#[test]
fn inner_call_override_narrows_classification_span() {
    // Byte offsets chosen so the outer statement spans two lines:
    //   line 2 (row 1): `x = \``
    //   line 3 (row 2): `  ${eval('1')}`
    //   line 4 (row 3): `\`;`
    let src = b"function f() {\n  x = `\n  ${eval('1')}\n  `;\n}\n";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    // Find the node whose callee was overridden to `eval`.
    let sink = cfg
        .node_indices()
        .find(|&i| cfg[i].call.callee.as_deref() == Some("eval"))
        .expect("inner-call override should produce a node with callee=eval");

    let info = &cfg[sink];

    // The outer `ast.span` starts at the `x = ...` expression statement
    // on line 2; the inner eval call lives on line 3.
    let outer_byte = info.ast.span.0;
    let inner_byte = info.classification_span().0;
    assert!(
        inner_byte > outer_byte,
        "classification span should start *inside* the outer statement (outer={outer_byte}, inner={inner_byte})"
    );

    let line_of = |b: usize| src[..b].iter().filter(|&&c| c == b'\n').count() + 1;
    assert_eq!(line_of(outer_byte), 2, "outer ast.span on line 2");
    assert_eq!(line_of(inner_byte), 3, "classification_span on eval's line");

    // callee_span must be populated (that's the whole point).
    assert!(
        info.call.callee_span.is_some(),
        "inner-call override should record callee_span"
    );
}

/// Ruby (and any language without an `expression_statement` wrapper)
/// reaches `push_node` with `ast.kind() == "call"` (`Kind::CallMethod`)
/// for top-level statement-position calls.  The inner-call fallback at
/// `push_node` line ~1690 must include `Kind::CallFn | Kind::CallMethod
/// | Kind::CallMacro` in its kind gate, otherwise an unclassified outer
/// wrapper around a sink (e.g. `YAML.safe_load(File.read(filename))`,
/// `String.new(File.read(x))`, `JSON.parse(File.read(x))` — every
/// chain-style sink wrapper used in real Ruby helpers) loses the inner
/// sink's classification entirely.  Cross-function summary extraction
/// then misses the wrapper's `param_to_sink` and downstream callers
/// silently lose detection.  Regression guard for CVE-2023-38337
/// (rswag-api `parse_file → load_yaml/load_json → File.read` chain)
/// and CVE-2021-21288 (CarrierWave `download → OpenURI.open_uri`).
#[test]
fn ruby_inner_call_fallback_classifies_wrapper_around_file_read() {
    let src = b"def f(x)\n  YAML.safe_load(File.read(x))\nend\n";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    // The outer call `YAML.safe_load(...)` does not classify by itself;
    // the fallback must descend into its argument list and pick up the
    // inner `File.read(x)` Sink(FILE_IO) label.
    let sink = cfg
        .node_indices()
        .find(|&i| cfg[i].call.callee.as_deref() == Some("File.read"))
        .expect(
            "inner-call fallback should override the outer YAML.safe_load callee with File.read",
        );

    let info = &cfg[sink];
    assert!(
        info.taint
            .labels
            .iter()
            .any(|l| matches!(l, DataLabel::Sink(c) if c.contains(crate::labels::Cap::FILE_IO))),
        "wrapper-around-File.read node must carry the FILE_IO sink label"
    );
    // outer_callee should preserve the original callee text so cross-fn
    // summary lookup can still find the wrapping function.
    assert_eq!(
        info.call.outer_callee.as_deref(),
        Some("YAML.safe_load"),
        "outer_callee must preserve the original wrapping callee"
    );
}

/// Identical-shape regression guard for the *bare-function* call
/// variant (`outer(File.read(x))`) — exercises the `Kind::CallFn`
/// branch of the gate, where Ruby/Python/etc.'s top-level free
/// function calls lacking a method receiver land.
#[test]
fn ruby_inner_call_fallback_classifies_bare_outer_around_file_read() {
    let src = b"def f(x)\n  outer(File.read(x))\nend\n";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let sink = cfg
        .node_indices()
        .find(|&i| cfg[i].call.callee.as_deref() == Some("File.read"))
        .expect("inner-call fallback must override `outer` callee with File.read");

    let info = &cfg[sink];
    assert!(
        info.taint
            .labels
            .iter()
            .any(|l| matches!(l, DataLabel::Sink(c) if c.contains(crate::labels::Cap::FILE_IO))),
        "wrapper-around-File.read node must carry FILE_IO sink label"
    );
}

/// `classification_span()` must fall back to `ast.span` when no narrower
/// sub-expression was recorded, so existing structural code paths keep
/// working unchanged for nodes whose classification applies to the whole
/// outer node.
#[test]
fn classification_span_falls_back_to_ast_span() {
    let info = NodeInfo {
        ast: AstMeta {
            span: (100, 200),
            enclosing_func: None,
        },
        ..Default::default()
    };
    assert!(info.call.callee_span.is_none());
    assert_eq!(info.classification_span(), (100, 200));

    let narrowed = NodeInfo {
        ast: AstMeta {
            span: (100, 200),
            enclosing_func: None,
        },
        call: CallMeta {
            callee_span: Some((150, 170)),
            ..Default::default()
        },
        ..Default::default()
    };
    assert_eq!(narrowed.classification_span(), (150, 170));
    assert_eq!(narrowed.ast.span, (100, 200));
}

/// The narrowed `callee_span` must remain strictly narrower than
/// `ast.span` on real-world CFG nodes.  When the classification applies
/// to (or degenerates to) the outer node, `callee_span` is left `None`
/// so we don't bloat every labeled node with a redundant span copy.
#[test]
fn callee_span_unset_when_no_narrowing_is_possible() {
    // A bare `eval(x);` on one line: `first_call_ident` finds the
    // call_expression whose span is nearly the whole expression_statement
    // (different by the trailing `;`).  `classification_span` still
    // returns a sensible line, but the exact trimming is an
    // implementation detail.  What we assert here is the invariant:
    // if callee_span *is* set, it must be contained in ast.span.
    let src = b"function f() { eval(x); }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let sink = cfg
        .node_indices()
        .find(|&i| cfg[i].call.callee.as_deref() == Some("eval"))
        .expect("should find eval call");
    let info = &cfg[sink];
    if let Some(cs) = info.call.callee_span {
        assert!(
            cs.0 >= info.ast.span.0 && cs.1 <= info.ast.span.1,
            "callee_span {:?} must be contained in ast.span {:?}",
            cs,
            info.ast.span,
        );
        assert_ne!(
            cs, info.ast.span,
            "callee_span should only be set when it narrows ast.span"
        );
    }
}

#[test]
fn js_try_finally_no_exception_edges() {
    let src = b"function f() { try { foo(); } finally { cleanup(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    // No catch clause → no exception edges
    assert!(
        exception_edges.is_empty(),
        "Expected no Exception edges for try/finally without catch"
    );

    // Verify finally nodes are reachable from entry
    let mut reachable = HashSet::new();
    let mut bfs = petgraph::visit::Bfs::new(&cfg, _entry);
    while let Some(nx) = bfs.next(&cfg) {
        reachable.insert(nx);
    }
    assert_eq!(
        reachable.len(),
        cfg.node_count(),
        "All nodes should be reachable (finally connected to try body)"
    );
}

#[test]
fn java_try_catch_has_exception_edges() {
    let src = b"class Foo { void bar() { try { baz(); } catch (Exception e) { qux(); } } }";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "java", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    assert!(
        !exception_edges.is_empty(),
        "Expected at least one Exception edge in Java try/catch"
    );
    for e in &exception_edges {
        assert_eq!(cfg[e.source()].kind, StmtKind::Call);
    }
}

#[test]
fn js_try_catch_finally_all_reachable() {
    let src = b"function f() { try { foo(); } catch (e) { bar(); } finally { baz(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, entry) = parse_and_build(src, "javascript", ts_lang);

    // All nodes should be reachable
    let mut reachable = HashSet::new();
    let mut bfs = petgraph::visit::Bfs::new(&cfg, entry);
    while let Some(nx) = bfs.next(&cfg) {
        reachable.insert(nx);
    }
    assert_eq!(
        reachable.len(),
        cfg.node_count(),
        "All nodes should be reachable in try/catch/finally"
    );

    // Should have exception edges
    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    assert!(!exception_edges.is_empty());
}

#[test]
fn js_throw_in_try_catch_has_exception_edge() {
    let src = b"function f() { try { throw new Error('bad'); } catch (e) { handle(e); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    assert!(
        !exception_edges.is_empty(),
        "throw inside try should create exception edge to catch"
    );
}

#[test]
fn java_multiple_catch_clauses() {
    let src = b"class Foo { void bar() { try { baz(); } catch (IOException e) { a(); } catch (Exception e) { b(); } } }";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "java", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    // Should have exception edges to both catch clauses
    assert!(
        exception_edges.len() >= 2,
        "Expected exception edges to multiple catch clauses, got {}",
        exception_edges.len()
    );
}

#[test]
fn js_catch_param_defines_variable() {
    let src = b"function f() { try { foo(); } catch (e) { bar(e); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    // Find the synthetic catch-param node
    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert_eq!(
        catch_param_nodes.len(),
        1,
        "Expected exactly one catch_param node"
    );
    let cp = &cfg[catch_param_nodes[0]];
    assert_eq!(cp.taint.defines.as_deref(), Some("e"));
    assert_eq!(cp.kind, StmtKind::Seq);

    // Exception edges should target the synthetic node
    let exception_targets: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .map(|e| e.target())
        .collect();
    assert!(exception_targets.iter().all(|&t| t == catch_param_nodes[0]));
}

#[test]
fn java_catch_param_extracted() {
    let src = b"class Foo { void bar() { try { baz(); } catch (Exception e) { qux(e); } } }";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "java", ts_lang);

    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert_eq!(
        catch_param_nodes.len(),
        1,
        "Expected exactly one catch_param node in Java"
    );
    assert_eq!(
        cfg[catch_param_nodes[0]].taint.defines.as_deref(),
        Some("e")
    );
}

#[test]
fn js_catch_no_param_no_synthetic() {
    // catch {} with no parameter should not create a catch_param node
    let src = b"function f() { try { foo(); } catch { bar(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert!(
        catch_param_nodes.is_empty(),
        "catch without parameter should not create a catch_param node"
    );
}

// ─────────────────────────────────────────────────────────────────
//  Ruby begin/rescue/ensure tests
// ─────────────────────────────────────────────────────────────────

#[test]
fn ruby_begin_rescue_has_exception_edges() {
    let src = b"def f()\n  begin\n    foo()\n  rescue => e\n    bar(e)\n  end\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let exception_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .collect();
    assert!(
        !exception_edges.is_empty(),
        "begin/rescue should produce exception edges"
    );
}

#[test]
fn ruby_rescue_catch_param_defines_variable() {
    let src = b"def f()\n  begin\n    foo()\n  rescue StandardError => e\n    bar(e)\n  end\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert_eq!(
        catch_param_nodes.len(),
        1,
        "Expected exactly one catch_param node in Ruby rescue"
    );
    let cp = &cfg[catch_param_nodes[0]];
    assert_eq!(cp.taint.defines.as_deref(), Some("e"));
    assert_eq!(cp.kind, StmtKind::Seq);

    // Exception edges should target the synthetic node
    let exception_targets: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .map(|e| e.target())
        .collect();
    assert!(exception_targets.iter().all(|&t| t == catch_param_nodes[0]));
}

#[test]
fn ruby_begin_rescue_ensure_complete() {
    let src =
        b"def f()\n  begin\n    foo()\n  rescue => e\n    bar(e)\n  ensure\n    baz()\n  end\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    // Should have exception edges
    let exception_count = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .count();
    assert!(
        exception_count > 0,
        "begin/rescue/ensure should have exception edges"
    );

    // All nodes should be reachable (no orphaned nodes beyond entry/exit)
    let node_count = cfg.node_count();
    assert!(node_count > 3, "CFG should have multiple nodes");
}

#[test]
fn ruby_rescue_no_variable() {
    // bare rescue without => e
    let src = b"def f()\n  begin\n    foo()\n  rescue\n    bar()\n  end\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    // No catch_param node should be created
    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert!(
        catch_param_nodes.is_empty(),
        "rescue without variable should not create a catch_param node"
    );

    // But exception edges should still exist
    let exception_count = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .count();
    assert!(
        exception_count > 0,
        "rescue without variable should still have exception edges"
    );
}

#[test]
fn ruby_body_statement_implicit_begin() {
    // def method body with inline rescue (no explicit begin)
    let src = b"def f()\n  foo()\nrescue => e\n  bar(e)\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let exception_count = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .count();
    assert!(
        exception_count > 0,
        "implicit begin via body_statement should produce exception edges"
    );

    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert_eq!(
        catch_param_nodes.len(),
        1,
        "implicit begin rescue should have one catch_param node"
    );
    assert_eq!(
        cfg[catch_param_nodes[0]].taint.defines.as_deref(),
        Some("e")
    );
}

#[test]
fn ruby_multiple_rescue_clauses() {
    let src = b"def f()\n  begin\n    foo()\n  rescue IOError => e\n    handle_io(e)\n  rescue => e\n    handle_other(e)\n  end\nend";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let catch_param_nodes: Vec<_> = cfg.node_indices().filter(|&n| cfg[n].catch_param).collect();
    assert_eq!(
        catch_param_nodes.len(),
        2,
        "Two rescue clauses should produce two catch_param nodes"
    );

    // Both should define "e"
    for &cp in &catch_param_nodes {
        assert_eq!(cfg[cp].taint.defines.as_deref(), Some("e"));
    }

    // Exception edges should target both synthetic nodes
    let exception_targets: std::collections::HashSet<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Exception))
        .map(|e| e.target())
        .collect();
    for &cp in &catch_param_nodes {
        assert!(
            exception_targets.contains(&cp),
            "Exception edges should target each catch_param node"
        );
    }
}

// ─────────────────────────────────────────────────────────────────
//  Short-circuit evaluation tests
// ─────────────────────────────────────────────────────────────────

/// Helper: collect all If nodes from the CFG.
fn if_nodes(cfg: &Cfg) -> Vec<NodeIndex> {
    cfg.node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::If)
        .collect()
}

/// Helper: check if an edge of the given kind exists from `src` to `dst`.
fn has_edge(cfg: &Cfg, src: NodeIndex, dst: NodeIndex, kind_match: fn(&EdgeKind) -> bool) -> bool {
    cfg.edges(src)
        .any(|e| e.target() == dst && kind_match(e.weight()))
}

#[test]
fn js_if_and_short_circuit() {
    // `if (a && b) { then(); }`
    // Should produce 2 If nodes: [a] --True--> [b]
    // False from a → else-path, False from b → else-path
    let src = b"function f() { if (a && b) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        2,
        "Expected 2 If nodes for `a && b`, got {}",
        ifs.len()
    );

    // Find which is `a` and which is `b` by condition_vars
    let a_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"a".to_string()))
        .copied()
        .unwrap();
    let b_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"b".to_string()))
        .copied()
        .unwrap();

    // True edge from a to b
    assert!(
        has_edge(&cfg, a_node, b_node, |e| matches!(e, EdgeKind::True)),
        "Expected True edge from a to b"
    );

    // Both a and b should have False edges going somewhere (else-path)
    let a_false: Vec<_> = cfg
        .edges(a_node)
        .filter(|e| matches!(e.weight(), EdgeKind::False))
        .collect();
    let b_false: Vec<_> = cfg
        .edges(b_node)
        .filter(|e| matches!(e.weight(), EdgeKind::False))
        .collect();
    assert!(!a_false.is_empty(), "Expected False edge from a");
    assert!(!b_false.is_empty(), "Expected False edge from b");
}

#[test]
fn js_if_or_short_circuit() {
    // `if (a || b) { then(); }`
    // Should produce 2 If nodes: [a] --False--> [b]
    // True from a → then-path, True from b → then-path
    let src = b"function f() { if (a || b) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        2,
        "Expected 2 If nodes for `a || b`, got {}",
        ifs.len()
    );

    let a_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"a".to_string()))
        .copied()
        .unwrap();
    let b_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"b".to_string()))
        .copied()
        .unwrap();

    // False edge from a to b
    assert!(
        has_edge(&cfg, a_node, b_node, |e| matches!(e, EdgeKind::False)),
        "Expected False edge from a to b"
    );

    // Both a and b should have True edges
    let a_true: Vec<_> = cfg
        .edges(a_node)
        .filter(|e| matches!(e.weight(), EdgeKind::True))
        .collect();
    let b_true: Vec<_> = cfg
        .edges(b_node)
        .filter(|e| matches!(e.weight(), EdgeKind::True))
        .collect();
    assert!(!a_true.is_empty(), "Expected True edge from a");
    assert!(!b_true.is_empty(), "Expected True edge from b");
}

#[test]
fn js_if_nested_and_or() {
    // `if (a && (b || c)) { then(); }`
    // 3 If nodes: [a] --True--> [b], [b] --False--> [c]
    // True from b or c → then; False from a or c → else
    let src = b"function f() { if (a && (b || c)) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        3,
        "Expected 3 If nodes for `a && (b || c)`, got {}",
        ifs.len()
    );

    let a_node = ifs
        .iter()
        .find(|&&n| {
            let vars = &cfg[n].condition_vars;
            vars.contains(&"a".to_string()) && vars.len() == 1
        })
        .copied()
        .unwrap();
    let b_node = ifs
        .iter()
        .find(|&&n| {
            let vars = &cfg[n].condition_vars;
            vars.contains(&"b".to_string()) && vars.len() == 1
        })
        .copied()
        .unwrap();
    let c_node = ifs
        .iter()
        .find(|&&n| {
            let vars = &cfg[n].condition_vars;
            vars.contains(&"c".to_string()) && vars.len() == 1
        })
        .copied()
        .unwrap();

    // a --True--> b
    assert!(has_edge(&cfg, a_node, b_node, |e| matches!(
        e,
        EdgeKind::True
    )));
    // b --False--> c
    assert!(has_edge(&cfg, b_node, c_node, |e| matches!(
        e,
        EdgeKind::False
    )));
}

#[test]
fn js_while_and_short_circuit() {
    // `while (a && b) { body(); }`
    // Loop header + 2 If nodes, back-edge goes to header
    let src = b"function f() { while (a && b) { body(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        2,
        "Expected 2 If nodes in while condition, got {}",
        ifs.len()
    );

    // There should be a Loop header
    let loop_headers: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect();
    assert_eq!(loop_headers.len(), 1, "Expected 1 Loop header");
    let header = loop_headers[0];

    // Back-edges should go to header
    let back_edges: Vec<_> = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Back))
        .collect();
    assert!(!back_edges.is_empty(), "Expected back edges");
    for e in &back_edges {
        assert_eq!(
            e.target(),
            header,
            "Back edge should go to loop header, not into condition chain"
        );
    }
}

#[test]
fn python_if_and() {
    // Python uses `boolean_operator` with `and` token
    let src = b"def f():\n    if a and b:\n        pass\n";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "python", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        2,
        "Expected 2 If nodes for Python `a and b`, got {}",
        ifs.len()
    );

    let a_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"a".to_string()))
        .copied()
        .unwrap();
    let b_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"b".to_string()))
        .copied()
        .unwrap();

    assert!(
        has_edge(&cfg, a_node, b_node, |e| matches!(e, EdgeKind::True)),
        "Expected True edge from a to b in Python and"
    );
}

#[test]
fn ruby_unless_and() {
    // `unless a && b`, chain built, branches swapped
    // Body should run when condition is false
    let src = b"def f\n  unless a && b\n    x\n  end\nend\n";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "ruby", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        2,
        "Expected 2 If nodes for Ruby `unless a && b`, got {}",
        ifs.len()
    );

    let a_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"a".to_string()))
        .copied()
        .unwrap();
    let b_node = ifs
        .iter()
        .find(|&&n| cfg[n].condition_vars.contains(&"b".to_string()))
        .copied()
        .unwrap();

    // Still has True edge from a to b (the chain is the same)
    assert!(
        has_edge(&cfg, a_node, b_node, |e| matches!(e, EdgeKind::True)),
        "Expected True edge from a to b in unless"
    );

    // For `unless`, the False exits should connect to the body with False edge
    // (since body runs when condition is false)
    let a_false_targets: Vec<_> = cfg
        .edges(a_node)
        .filter(|e| matches!(e.weight(), EdgeKind::False))
        .map(|e| e.target())
        .collect();
    // a's false exit should connect to the body (not to a pass-through)
    // because for `unless (a && b)`, when a is false the full condition is false,
    // meaning the body should execute
    assert!(
        !a_false_targets.is_empty(),
        "a should have False edges in unless"
    );
}

#[test]
fn while_short_circuit_continue() {
    // `while (a && b) { if (cond) { continue; } body(); }`
    // Verify continue goes to loop header
    let src = b"function f() { while (a && b) { if (cond) { continue; } body(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let loop_headers: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect();
    assert_eq!(loop_headers.len(), 1);
    let header = loop_headers[0];

    // Continue nodes should have back-edge to header
    let continue_nodes: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Continue)
        .collect();
    assert!(!continue_nodes.is_empty(), "Expected continue node");
    for &cont in &continue_nodes {
        assert!(
            has_edge(&cfg, cont, header, |e| matches!(e, EdgeKind::Back)),
            "Continue should have back-edge to loop header"
        );
    }
}

#[test]
fn negated_boolean_no_decomposition() {
    // `!(a && b)` should NOT be decomposed (De Morgan out of scope)
    let src = b"function f() { if (!(a && b)) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    // Should be exactly 1 If node (no decomposition)
    assert_eq!(
        ifs.len(),
        1,
        "Negated boolean should NOT be decomposed, got {} If nodes",
        ifs.len()
    );
}

#[test]
fn js_triple_and_chain() {
    // `if (a && b && c) { then(); }`
    // Tree-sitter parses as `(a && b) && c` → left-to-right chain
    let src = b"function f() { if (a && b && c) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        3,
        "Expected 3 If nodes for `a && b && c`, got {}",
        ifs.len()
    );
}

#[test]
fn js_or_precedence_with_and() {
    // `if (a || b && c) { then(); }`
    // Tree-sitter respects precedence: `a || (b && c)`
    // → [a] --False--> [b] --True--> [c]
    // True from a or c → then; False from c (and b) → else
    let src = b"function f() { if (a || b && c) { then(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(
        ifs.len(),
        3,
        "Expected 3 If nodes for `a || b && c`, got {}",
        ifs.len()
    );
}

// ── first_call_ident tests ──────────────────────────────────────────

/// Helper: parse source with a given language, return the root tree-sitter node.
fn parse_tree(src: &[u8], ts_lang: Language) -> tree_sitter::Tree {
    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&ts_lang).unwrap();
    parser.parse(src, None).unwrap()
}

#[test]
fn first_call_ident_skips_lambda_body() {
    // `process(lambda: eval(dangerous))`, Python-style.
    // first_call_ident should return "process", not "eval".
    let src = b"process(lambda: eval(dangerous))";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let tree = parse_tree(src, ts_lang);
    let root = tree.root_node();
    let result = first_call_ident(root, "python", src);
    assert_eq!(result.as_deref(), Some("process"));
}

#[test]
fn first_call_ident_skips_arrow_function_body() {
    // `process(() => eval(dangerous))`, JS arrow function in argument.
    let src = b"process(() => eval(dangerous))";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let tree = parse_tree(src, ts_lang);
    let root = tree.root_node();
    let result = first_call_ident(root, "javascript", src);
    assert_eq!(result.as_deref(), Some("process"));
}

#[test]
fn first_call_ident_skips_named_function_in_arg() {
    // `process(function inner() { eval(dangerous); })`, named function expression in arg.
    let src = b"process(function inner() { eval(dangerous); })";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let tree = parse_tree(src, ts_lang);
    let root = tree.root_node();
    let result = first_call_ident(root, "javascript", src);
    assert_eq!(result.as_deref(), Some("process"));
}

#[test]
fn first_call_ident_normal_nested_call() {
    // `outer(inner(x))`, inner is NOT behind a function boundary, should be reachable.
    let src = b"outer(inner(x))";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let tree = parse_tree(src, ts_lang);
    let root = tree.root_node();
    let result = first_call_ident(root, "javascript", src);
    // first_call_ident returns the first call it encounters (outer)
    assert_eq!(result.as_deref(), Some("outer"));
}

#[test]
fn first_call_ident_finds_call_not_blocked_by_function() {
    // Ensure a call at the same level as a function literal is still found.
    // `[function() {}, actual_call()]`, array with function and call.
    let src = b"[function() {}, actual_call()]";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let tree = parse_tree(src, ts_lang);
    let root = tree.root_node();
    let result = first_call_ident(root, "javascript", src);
    assert_eq!(result.as_deref(), Some("actual_call"));
}

// ── Callee classification with nested function regression ───────────

#[test]
fn callee_not_resolved_from_nested_function_arg() {
    // `safe_wrapper(function() { eval(user_input); })`, the CFG for the
    // outer call should resolve the callee as "safe_wrapper", never "eval".
    let src = b"function f() { safe_wrapper(function() { eval(user_input); }); }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);

    // Find the node whose callee is "safe_wrapper"
    let body = &file_cfg.bodies[1]; // function body
    let has_safe = body
        .graph
        .node_weights()
        .any(|info| info.call.callee.as_deref() == Some("safe_wrapper"));
    assert!(has_safe, "expected a node with callee 'safe_wrapper'");

    // The outer body should NOT have a node with callee "eval" attributed
    // to the outer expression, eval lives inside the nested function body.
    let outer_eval = body.graph.node_weights().any(|info| {
        info.call.callee.as_deref() == Some("eval") && info.ast.enclosing_func.is_none()
    });
    assert!(
        !outer_eval,
        "eval should not appear as a callee in the outer scope from a nested function"
    );
}

// ── NodeInfo sub-struct refactor tests ──────────────────────────────

#[test]
fn nodeinfo_default_is_valid() {
    let n = NodeInfo::default();
    assert_eq!(n.kind, StmtKind::Seq);
    assert!(n.call.callee.is_none());
    assert!(n.call.outer_callee.is_none());
    assert_eq!(n.call.call_ordinal, 0);
    assert!(n.call.arg_uses.is_empty());
    assert!(n.call.receiver.is_none());
    assert!(n.call.sink_payload_args.is_none());
    assert!(n.taint.labels.is_empty());
    assert!(n.taint.const_text.is_none());
    assert!(n.taint.defines.is_none());
    assert!(n.taint.uses.is_empty());
    assert!(n.taint.extra_defines.is_empty());
    assert_eq!(n.ast.span, (0, 0));
    assert!(n.ast.enclosing_func.is_none());
    assert!(!n.all_args_literal);
    assert!(!n.catch_param);
    assert!(n.condition_text.is_none());
    assert!(n.condition_vars.is_empty());
    assert!(!n.condition_negated);
    assert!(n.arg_callees.is_empty());
    assert!(n.cast_target_type.is_none());
    assert!(n.bin_op.is_none());
    assert!(n.bin_op_const.is_none());
    assert!(!n.managed_resource);
    assert!(!n.in_defer);
    assert!(!n.is_eq_with_const);
}

#[test]
fn callmeta_default() {
    let c = CallMeta::default();
    assert!(c.callee.is_none());
    assert!(c.outer_callee.is_none());
    assert_eq!(c.call_ordinal, 0);
    assert!(c.arg_uses.is_empty());
    assert!(c.receiver.is_none());
    assert!(c.sink_payload_args.is_none());
}

#[test]
fn taintmeta_default() {
    let t = TaintMeta::default();
    assert!(t.labels.is_empty());
    assert!(t.const_text.is_none());
    assert!(t.defines.is_none());
    assert!(t.uses.is_empty());
    assert!(t.extra_defines.is_empty());
}

#[test]
fn astmeta_default() {
    let a = AstMeta::default();
    assert_eq!(a.span, (0, 0));
    assert!(a.enclosing_func.is_none());
}

#[test]
fn synthetic_catch_param_node_structure() {
    let n = NodeInfo {
        kind: StmtKind::Seq,
        ast: AstMeta {
            span: (100, 100),
            enclosing_func: Some("handle_request".into()),
        },
        taint: TaintMeta {
            defines: Some("e".into()),
            ..Default::default()
        },
        call: CallMeta {
            callee: Some("catch(e)".into()),
            ..Default::default()
        },
        catch_param: true,
        ..Default::default()
    };
    assert_eq!(n.kind, StmtKind::Seq);
    assert_eq!(n.ast.span, (100, 100));
    assert_eq!(n.ast.enclosing_func.as_deref(), Some("handle_request"));
    assert_eq!(n.taint.defines.as_deref(), Some("e"));
    assert_eq!(n.call.callee.as_deref(), Some("catch(e)"));
    assert!(n.catch_param);
    assert!(n.taint.labels.is_empty());
    assert!(n.call.arg_uses.is_empty());
}

#[test]
fn synthetic_passthrough_node_structure() {
    let n = NodeInfo {
        kind: StmtKind::Seq,
        ast: AstMeta {
            span: (50, 50),
            enclosing_func: Some("main".into()),
        },
        ..Default::default()
    };
    assert_eq!(n.kind, StmtKind::Seq);
    assert_eq!(n.ast.span, (50, 50));
    assert!(n.taint.defines.is_none());
    assert!(n.call.callee.is_none());
    assert!(!n.catch_param);
}

#[test]
fn normal_call_node_structure() {
    let n = NodeInfo {
        kind: StmtKind::Call,
        call: CallMeta {
            callee: Some("eval".into()),
            receiver: Some("window".into()),
            call_ordinal: 3,
            arg_uses: vec![vec!["x".into()], vec!["y".into()]],
            sink_payload_args: Some(vec![0]),
            ..Default::default()
        },
        taint: TaintMeta {
            labels: {
                let mut v = SmallVec::new();
                v.push(crate::labels::DataLabel::Sink(
                    crate::labels::Cap::CODE_EXEC,
                ));
                v
            },
            defines: Some("result".into()),
            uses: vec!["x".into(), "y".into()],
            ..Default::default()
        },
        ast: AstMeta {
            span: (10, 50),
            enclosing_func: Some("handler".into()),
        },
        ..Default::default()
    };
    assert_eq!(n.call.callee.as_deref(), Some("eval"));
    assert_eq!(n.call.receiver.as_deref(), Some("window"));
    assert_eq!(n.call.call_ordinal, 3);
    assert_eq!(n.call.arg_uses.len(), 2);
    assert_eq!(n.call.sink_payload_args.as_deref(), Some(&[0usize][..]));
    assert_eq!(n.taint.labels.len(), 1);
    assert_eq!(n.taint.defines.as_deref(), Some("result"));
    assert_eq!(n.taint.uses, vec!["x", "y"]);
    assert_eq!(n.ast.span, (10, 50));
    assert_eq!(n.ast.enclosing_func.as_deref(), Some("handler"));
}

#[test]
fn condition_node_preserves_fields() {
    let n = NodeInfo {
        kind: StmtKind::If,
        ast: AstMeta {
            span: (0, 20),
            enclosing_func: None,
        },
        condition_text: Some("x > 0".into()),
        condition_vars: vec!["x".into()],
        condition_negated: true,
        ..Default::default()
    };
    assert_eq!(n.kind, StmtKind::If);
    assert_eq!(n.condition_text.as_deref(), Some("x > 0"));
    assert_eq!(n.condition_vars, vec!["x"]);
    assert!(n.condition_negated);
}

#[test]
fn clone_preserves_all_sub_structs() {
    let original = NodeInfo {
        kind: StmtKind::Call,
        call: CallMeta {
            callee: Some("foo".into()),
            callee_text: Some("obj.foo".into()),
            outer_callee: Some("bar".into()),
            callee_span: Some((7, 17)),
            call_ordinal: 5,
            arg_uses: vec![vec!["a".into()]],
            receiver: Some("obj".into()),
            sink_payload_args: Some(vec![1, 2]),
            kwargs: vec![("shell".into(), vec!["True".into()])],
            arg_string_literals: vec![Some("lit".into())],
            destination_uses: None,
            gate_filters: Vec::new(),
            is_constructor: false,
        },
        taint: TaintMeta {
            labels: {
                let mut v = SmallVec::new();
                v.push(crate::labels::DataLabel::Source(crate::labels::Cap::all()));
                v
            },
            const_text: Some("42".into()),
            defines: Some("r".into()),
            uses: vec!["a".into(), "b".into()],
            extra_defines: vec!["c".into()],
        },
        ast: AstMeta {
            span: (10, 100),
            enclosing_func: Some("main".into()),
        },
        all_args_literal: true,
        catch_param: true,
        ..Default::default()
    };
    let cloned = original.clone();
    assert_eq!(cloned.call.callee, original.call.callee);
    assert_eq!(cloned.call.outer_callee, original.call.outer_callee);
    assert_eq!(cloned.call.call_ordinal, original.call.call_ordinal);
    assert_eq!(cloned.call.arg_uses, original.call.arg_uses);
    assert_eq!(cloned.call.receiver, original.call.receiver);
    assert_eq!(
        cloned.call.sink_payload_args,
        original.call.sink_payload_args
    );
    assert_eq!(cloned.call.kwargs, original.call.kwargs);
    assert_eq!(cloned.taint.labels.len(), original.taint.labels.len());
    assert_eq!(cloned.taint.const_text, original.taint.const_text);
    assert_eq!(cloned.taint.defines, original.taint.defines);
    assert_eq!(cloned.taint.uses, original.taint.uses);
    assert_eq!(cloned.taint.extra_defines, original.taint.extra_defines);
    assert_eq!(cloned.ast.span, original.ast.span);
    assert_eq!(cloned.ast.enclosing_func, original.ast.enclosing_func);
    assert_eq!(cloned.all_args_literal, original.all_args_literal);
    assert_eq!(cloned.catch_param, original.catch_param);
}

#[test]
fn cfg_output_equivalence_js_catch() {
    // This test verifies that the refactored NodeInfo produces the same
    // CFG structure as before for a JS try/catch.
    let src = b"function f() { try { foo(x); } catch(e) { bar(e); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let body = file_cfg.first_body();

    // Verify catch-param node exists with correct nested field access
    let catch_params: Vec<_> = body
        .graph
        .node_weights()
        .filter(|n| n.catch_param)
        .collect();
    assert_eq!(catch_params.len(), 1);
    assert_eq!(catch_params[0].taint.defines.as_deref(), Some("e"));
    assert!(
        catch_params[0]
            .call
            .callee
            .as_deref()
            .unwrap()
            .starts_with("catch(")
    );
}

#[test]
fn cfg_output_equivalence_condition_chain() {
    // Verify If nodes use the correct sub-struct paths
    let src = b"function f(x) { if (x > 0) { sink(x); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let if_nodes: Vec<_> = cfg
        .node_weights()
        .filter(|n| n.kind == StmtKind::If)
        .collect();
    assert!(!if_nodes.is_empty());
    // Condition text and vars should be on the If node directly
    let if_node = if_nodes[0];
    assert!(if_node.condition_text.is_some() || !if_node.condition_vars.is_empty());
    // Labels should be empty on If nodes (they're structural)
    assert!(if_node.taint.labels.is_empty());
}

#[test]
fn make_empty_node_info_uses_sub_structs() {
    let n = make_empty_node_info(StmtKind::Entry, (0, 100), Some("test_func"));
    assert_eq!(n.kind, StmtKind::Entry);
    assert_eq!(n.ast.span, (0, 100));
    assert_eq!(n.ast.enclosing_func.as_deref(), Some("test_func"));
    assert!(n.call.callee.is_none());
    assert!(n.taint.defines.is_none());
    assert!(n.taint.uses.is_empty());
}

// ── Import alias binding tests ──────────────────────────────────

#[test]
fn js_import_alias_bindings() {
    let src = b"import { getInput as fetchInput } from './source';";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 1);
    let b = &file_cfg.import_bindings["fetchInput"];
    assert_eq!(b.original, "getInput");
    assert_eq!(b.module_path.as_deref(), Some("./source"));
}

#[test]
fn js_same_name_import_not_recorded() {
    let src = b"import { exec } from 'child_process';";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

#[test]
fn python_import_alias_bindings() {
    let src = b"from os import getenv as fetch_env";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "python", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 1);
    let b = &file_cfg.import_bindings["fetch_env"];
    assert_eq!(b.original, "getenv");
    assert_eq!(b.module_path.as_deref(), Some("os"));
}

#[test]
fn python_multiple_aliased_imports() {
    let src = b"from source import get_input as fetch_input, run_query as exec_query";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "python", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 2);
    assert_eq!(
        file_cfg.import_bindings["fetch_input"].original,
        "get_input"
    );
    assert_eq!(file_cfg.import_bindings["exec_query"].original, "run_query");
}

#[test]
fn python_same_name_import_not_recorded() {
    let src = b"from os import getenv";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "python", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

#[test]
fn php_namespace_alias_bindings() {
    let src = b"<?php\nuse App\\Security\\Sanitizer as Clean;\n";
    let ts_lang = Language::from(tree_sitter_php::LANGUAGE_PHP);
    let file_cfg = parse_to_file_cfg(src, "php", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 1);
    let b = &file_cfg.import_bindings["Clean"];
    assert_eq!(b.original, "Sanitizer");
    assert_eq!(b.module_path.as_deref(), Some("App\\Security\\Sanitizer"));
}

#[test]
fn php_no_alias_not_recorded() {
    let src = b"<?php\nuse App\\Security\\Sanitizer;\n";
    let ts_lang = Language::from(tree_sitter_php::LANGUAGE_PHP);
    let file_cfg = parse_to_file_cfg(src, "php", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

#[test]
fn rust_use_as_alias_bindings() {
    let src = b"use std::collections::HashMap as Map;";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "rust", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 1);
    let b = &file_cfg.import_bindings["Map"];
    assert_eq!(b.original, "HashMap");
    assert_eq!(b.module_path.as_deref(), Some("std::collections::HashMap"));
}

#[test]
fn rust_no_alias_not_recorded() {
    let src = b"use std::collections::HashMap;";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "rust", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

#[test]
fn rust_nested_use_as_alias() {
    let src = b"use std::io::{Read as IoRead, Write};";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "rust", ts_lang);
    assert_eq!(file_cfg.import_bindings.len(), 1);
    let b = &file_cfg.import_bindings["IoRead"];
    assert_eq!(b.original, "Read");
}

/// `format!("{x}")` uses x even though x is captured via the format
/// string's named-argument syntax rather than as a separate AST
/// argument.  Without this lift, taint stops at the macro boundary
/// for any caller whose format string reads a tainted variable by
/// name (matrix-rust-sdk CVE-2025-53549, log!() / println!() across
/// most Rust 1.58+ codebases).
#[test]
fn rust_format_macro_named_arg_lifted_into_uses() {
    let src = b"fn f() { let x = 1; let y = format!(\"v={x}\"); }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    let mut found = false;
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.taint.defines.as_deref() == Some("y") {
            assert!(
                info.taint.uses.iter().any(|u| u == "x"),
                "expected `x` in uses for `let y = format!(\"v={{x}}\")`; got {:?}",
                info.taint.uses
            );
            found = true;
        }
    }
    assert!(found, "no node found defining `y`");
}

#[test]
fn rust_format_macro_named_arg_with_format_spec() {
    let src = b"fn f() { let x = 1; let y = format!(\"{x:?}\"); }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    let mut found = false;
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.taint.defines.as_deref() == Some("y") {
            assert!(
                info.taint.uses.iter().any(|u| u == "x"),
                "expected `x` lifted past `{{x:?}}` format spec; got {:?}",
                info.taint.uses
            );
            found = true;
        }
    }
    assert!(found, "no node found defining `y`");
}

#[test]
fn rust_format_macro_escaped_braces_not_lifted() {
    // `{{` and `}}` are escapes for literal `{` / `}`, NOT named
    // argument captures.  No identifier should be lifted from the
    // sequence between them.
    let src = b"fn f() { let q = format!(\"{{x}}\"); }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.taint.defines.as_deref() == Some("q") {
            assert!(
                !info.taint.uses.iter().any(|u| u == "x"),
                "must not lift `x` from escaped `{{{{x}}}}`; got {:?}",
                info.taint.uses
            );
        }
    }
}

#[test]
fn rust_format_macro_positional_index_not_lifted() {
    // Positional placeholders like `{0}` reference args by position,
    // not by name.  Don't accidentally treat a digit as an identifier.
    let src = b"fn f() { let a = 1; let q = format!(\"{0}\", a); }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.taint.defines.as_deref() == Some("q") {
            assert!(
                !info.taint.uses.iter().any(|u| u == "0"),
                "must not lift digit-only positional placeholder; got {:?}",
                info.taint.uses
            );
            assert!(
                info.taint.uses.iter().any(|u| u == "a"),
                "expected `a` in uses (positional arg) for `format!(\"{{0}}\", a)`; got {:?}",
                info.taint.uses
            );
        }
    }
}

#[test]
fn rust_println_macro_named_arg_lifted() {
    let src = b"fn f() { let user = String::from(\"x\"); println!(\"hi {user}\"); }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    let mut found = false;
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.call.callee.as_deref() == Some("println") {
            assert!(
                info.taint.uses.iter().any(|u| u == "user"),
                "expected `user` lifted into println! uses; got {:?}",
                info.taint.uses
            );
            found = true;
        }
    }
    assert!(found, "no println! macro_invocation node found");
}

#[test]
fn go_no_import_bindings() {
    let src = b"package main\nimport alias \"fmt\"\n";
    let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "go", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

#[test]
fn java_no_import_bindings() {
    let src = b"import java.util.List;";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "java", ts_lang);
    assert!(file_cfg.import_bindings.is_empty());
}

// ── Promisify alias binding tests ───────────────────────────────

#[test]
fn js_promisify_alias_member_expression() {
    let src = b"const execAsync = util.promisify(child_process.exec);";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let alias = file_cfg
        .promisify_aliases
        .get("execAsync")
        .expect("execAsync should be recorded");
    assert_eq!(alias.wrapped, "child_process.exec");
}

#[test]
fn js_promisify_alias_bare_identifier() {
    // `promisify` imported directly from util (destructured).
    let src = b"const run = promisify(foo);";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    assert_eq!(
        file_cfg
            .promisify_aliases
            .get("run")
            .map(|a| a.wrapped.as_str()),
        Some("foo")
    );
}

#[test]
fn js_promisify_labels_carry_to_alias_call() {
    // The post-pass should union `child_process.exec`'s Sink(SHELL_ESCAPE)
    // into every call site of the alias.
    let src = b"const runAsync = util.promisify(child_process.exec);\n\
                    function f(userCmd) { runAsync(userCmd); }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    assert!(file_cfg.promisify_aliases.contains_key("runAsync"));
    let any_runasync_sink = file_cfg.bodies.iter().any(|b| {
        b.graph.node_weights().any(|n| {
            n.call.callee.as_deref() == Some("runAsync")
                && n.taint.labels.iter().any(|lbl| {
                    matches!(
                        lbl,
                        crate::labels::DataLabel::Sink(c)
                            if c.intersects(crate::labels::Cap::SHELL_ESCAPE)
                    )
                })
        })
    });
    assert!(
        any_runasync_sink,
        "runAsync call site should inherit child_process.exec's SHELL_ESCAPE sink"
    );
}

#[test]
fn js_promisify_ignored_for_non_js_langs() {
    let src = b"const x = util.promisify(exec)";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "python", ts_lang);
    assert!(file_cfg.promisify_aliases.is_empty());
}

#[test]
fn js_promisify_non_call_value_ignored() {
    // RHS is not a promisify call, no binding should be captured.
    let src = b"const execAsync = child_process.exec;";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    assert!(file_cfg.promisify_aliases.is_empty());
}

#[test]
fn sql_placeholder_detection() {
    // Positive cases
    assert!(has_sql_placeholders("SELECT * FROM users WHERE id = $1"));
    assert!(has_sql_placeholders("SELECT * FROM users WHERE id = ?"));
    assert!(has_sql_placeholders("SELECT * FROM users WHERE id = %s"));
    assert!(has_sql_placeholders("INSERT INTO t (a, b) VALUES ($1, $2)"));
    assert!(has_sql_placeholders("SELECT * FROM t WHERE x = :name"));
    assert!(has_sql_placeholders("WHERE id = ? AND name = ?"));

    // Negative cases
    assert!(!has_sql_placeholders("SELECT * FROM users"));
    assert!(!has_sql_placeholders("SELECT * FROM users WHERE id = 1"));
    assert!(!has_sql_placeholders("SELECT $dollar FROM t")); // $d not $N
    assert!(!has_sql_placeholders("SELECT * FROM t WHERE x = $0")); // $0 not valid
    assert!(!has_sql_placeholders("ratio = 50%")); // %<not s>
}

#[test]
fn c_function_extracts_param_names() {
    let src = b"void handle_command(int cmd, char *arg) { }";
    let ts_lang = Language::from(tree_sitter_c::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "c", ts_lang);
    let params: Vec<_> = file_cfg
        .summaries
        .values()
        .flat_map(|s| s.param_names.iter().cloned())
        .collect();
    assert!(
        params.contains(&"cmd".to_string()),
        "expected 'cmd' in params, got: {:?}",
        params
    );
    assert!(
        params.contains(&"arg".to_string()),
        "expected 'arg' in params, got: {:?}",
        params
    );
}

#[test]
fn cpp_function_extracts_param_names() {
    let src = b"void process(int x, std::string name) { }";
    let ts_lang = Language::from(tree_sitter_cpp::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "cpp", ts_lang);
    let params: Vec<_> = file_cfg
        .summaries
        .values()
        .flat_map(|s| s.param_names.iter().cloned())
        .collect();
    assert!(
        params.contains(&"x".to_string()),
        "expected 'x' in params, got: {:?}",
        params
    );
    assert!(
        params.contains(&"name".to_string()),
        "expected 'name' in params, got: {:?}",
        params
    );
}

// ── callee-site metadata extraction ──────────────────────────────────

/// Callees collected into `LocalFuncSummary` should now carry structured
/// arity, receiver, and qualifier fields, not just a bare name.
#[test]
fn local_summary_callees_carry_arity_and_receiver() {
    // Two calls: one is a plain function call with 2 args, the other is
    // a method call on an explicit receiver.
    let src = br"
            function outer(x, y) {
                helper(x, y);
                obj.method(x);
            }
        ";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let summaries = &file_cfg.summaries;

    // Pull the outer function's summary.
    let (_key, outer) = summaries
        .iter()
        .find(|(k, _)| k.name == "outer")
        .expect("outer summary should exist");

    // Both calls should be recorded.
    let helper_site = outer
        .callees
        .iter()
        .find(|c| c.name == "helper")
        .expect("helper call should be recorded with structured metadata");
    assert_eq!(
        helper_site.arity,
        Some(2),
        "helper has 2 positional args at the call site"
    );
    assert_eq!(
        helper_site.receiver, None,
        "helper is not a method call — no receiver"
    );

    // JS `obj.method(x)` is a CallFn in tree-sitter-javascript whose
    // `function` child is a `member_expression`.  push_node now unwraps
    // that member expression and populates the structured `receiver`
    // field directly, so `qualifier` stays `None`.
    let method_site = outer
        .callees
        .iter()
        .find(|c| c.name.ends_with("method"))
        .expect("method call should be recorded");
    assert_eq!(method_site.arity, Some(1), "method has 1 positional arg");
    assert_eq!(
        method_site.receiver.as_deref(),
        Some("obj"),
        "js CallFn over member_expression should populate structured receiver"
    );
    assert_eq!(
        method_site.qualifier, None,
        "qualifier is suppressed once receiver is populated"
    );
}

/// JS `obj.method(x)` is modeled as `call_expression` whose `function`
/// child is a `member_expression`.  Kind::CallFn push_node must surface
/// the receiver identifier through `CallMeta.receiver`.
#[test]
fn local_summary_callees_js_method_receiver() {
    let src = br"
            function outer(obj, x) {
                obj.method(x);
            }
        ";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let (_key, outer) = file_cfg
        .summaries
        .iter()
        .find(|(k, _)| k.name == "outer")
        .expect("js outer summary should exist");

    let method_site = outer
        .callees
        .iter()
        .find(|c| c.name.ends_with("method"))
        .expect("js method call should be recorded");
    assert_eq!(method_site.arity, Some(1));
    assert_eq!(
        method_site.receiver.as_deref(),
        Some("obj"),
        "js CallFn over member_expression should populate structured receiver"
    );
}

/// Python `obj.method(x)` is modeled as `call` whose `function` child is
/// an `attribute`.  Kind::CallFn push_node must surface the receiver
/// identifier through `CallMeta.receiver`.
#[test]
fn local_summary_callees_python_method_receiver() {
    let src = b"
def outer(obj, x):
    obj.method(x)
";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "python", ts_lang);
    let (_key, outer) = file_cfg
        .summaries
        .iter()
        .find(|(k, _)| k.name == "outer")
        .expect("python outer summary should exist");

    let method_site = outer
        .callees
        .iter()
        .find(|c| c.name.ends_with("method"))
        .expect("python method call should be recorded");
    assert_eq!(method_site.arity, Some(1));
    assert_eq!(
        method_site.receiver.as_deref(),
        Some("obj"),
        "python CallFn over attribute should populate structured receiver"
    );
}

/// Java `obj.method(x)` IS classified as CallMethod (via
/// `method_invocation`), so the structured `receiver` field
/// should be populated directly rather than falling through to
/// the `qualifier` dotted-name fallback.
#[test]
fn local_summary_callees_java_method_receiver() {
    let src = br"
class Outer {
    void outer(Bar obj, int x) {
        obj.method(x);
    }
}
";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "java", ts_lang);
    let (_key, outer) = file_cfg
        .summaries
        .iter()
        .find(|(k, _)| k.name == "outer")
        .expect("java outer summary should exist");

    let method_site = outer
        .callees
        .iter()
        .find(|c| c.name.ends_with("method"))
        .expect("java method call should be recorded");
    assert_eq!(method_site.arity, Some(1));
    assert_eq!(
        method_site.receiver.as_deref(),
        Some("obj"),
        "java CallMethod should populate the structured receiver field"
    );
}

/// Python keyword arguments should be captured separately from positional
/// `arg_uses` and surfaced through `CallMeta.kwargs` as `(name, uses)`.
#[test]
fn call_node_kwargs_populated_for_python() {
    let src = b"
def outer(cmd):
    subprocess.run(cmd, shell=True, check=False)
";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "python", ts_lang);
    let call_node = cfg
        .node_weights()
        .find(|n| {
            n.kind == StmtKind::Call && n.call.callee.as_deref().is_some_and(|c| c.ends_with("run"))
        })
        .expect("subprocess.run call node should exist");

    // Receiver (`subprocess`) is a separate channel on `CallMeta.receiver`;
    // `arg_uses` holds positional arguments only. Keyword args must not
    // appear in positional slots.
    assert_eq!(
        call_node.call.arg_uses.len(),
        1,
        "arg_uses should be [cmd] — receiver is separate, kwargs are not positional"
    );
    assert_eq!(call_node.call.arg_uses[0], vec!["cmd".to_string()]);
    assert_eq!(call_node.call.receiver.as_deref(), Some("subprocess"));

    let kwargs = &call_node.call.kwargs;
    assert_eq!(kwargs.len(), 2, "two keyword arguments expected");
    assert_eq!(kwargs[0].0, "shell");
    assert_eq!(kwargs[1].0, "check");
}

/// Languages without keyword-argument grammar should leave `kwargs` empty.
#[test]
fn call_node_kwargs_empty_for_javascript() {
    let src = br"
            function outer(cmd) {
                child_process.exec(cmd, { shell: true });
            }
        ";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
    let call_node = cfg
        .node_weights()
        .find(|n| {
            n.kind == StmtKind::Call
                && n.call
                    .callee
                    .as_deref()
                    .is_some_and(|c| c.ends_with("exec"))
        })
        .expect("child_process.exec call node should exist");
    assert!(
        call_node.call.kwargs.is_empty(),
        "JS object-literal arg is not a keyword_argument — kwargs should stay empty"
    );
}

/// Ordinals on callees should match `CallMeta.call_ordinal` so
/// downstream consumers can address a specific call site.
#[test]
fn local_summary_callees_have_distinct_ordinals() {
    let src = br"
            function outer() {
                a();
                a();
                b();
            }
        ";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let (_key, outer) = file_cfg
        .summaries
        .iter()
        .find(|(k, _)| k.name == "outer")
        .unwrap();

    // Dedup key is (name, arity, receiver, qualifier, ordinal), the two
    // `a()` sites have different ordinals, so both must appear.
    let a_sites: Vec<_> = outer.callees.iter().filter(|c| c.name == "a").collect();
    assert_eq!(
        a_sites.len(),
        2,
        "two a() calls should produce two entries with distinct ordinals, got: {:?}",
        a_sites
    );
    let ord0 = a_sites[0].ordinal;
    let ord1 = a_sites[1].ordinal;
    assert_ne!(ord0, ord1, "ordinals must differ across sites");
}

// ─────────────────────────────────────────────────────────────────────
//  Anonymous function body naming via syntactic context
//  (derive_anon_fn_name_from_context coverage)
// ─────────────────────────────────────────────────────────────────────

fn js_body_names(src: &[u8]) -> Vec<String> {
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    file_cfg
        .bodies
        .iter()
        .filter_map(|b| b.meta.func_key.as_ref().map(|k| k.name.clone()))
        .collect()
}

fn js_body_kinds(src: &[u8]) -> Vec<BodyKind> {
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    file_cfg.bodies.iter().map(|b| b.meta.kind).collect()
}

#[test]
fn anon_fn_named_from_var_declarator_js() {
    let src = b"var handler = function(x) { child_process.exec(x); };";
    let names = js_body_names(src);
    assert!(
        names.iter().any(|n| n == "handler"),
        "expected body named `handler` from var declarator, got: {:?}",
        names
    );
}

#[test]
fn anon_arrow_named_from_const_declarator_js() {
    let src = b"const run = (x) => { eval(x); };";
    let names = js_body_names(src);
    assert!(
        names.iter().any(|n| n == "run"),
        "expected body named `run` from const arrow declarator, got: {:?}",
        names
    );
}

#[test]
fn anon_fn_named_from_member_assignment_js() {
    let src = b"this.run = function(x) { eval(x); };";
    let names = js_body_names(src);
    assert!(
        names.iter().any(|n| n == "run"),
        "expected body named `run` from member assignment, got: {:?}",
        names
    );
}

#[test]
fn anon_fn_passed_as_arg_stays_anonymous_js() {
    // Function literal passed directly as argument has no stable
    // syntactic binding → must remain a synthetic anon name.
    let src = b"apply(function(x) { eval(x); });";
    let names = js_body_names(src);
    let kinds = js_body_kinds(src);
    assert!(
        kinds.contains(&BodyKind::AnonymousFunction),
        "expected at least one AnonymousFunction body, got: {:?}",
        kinds
    );
    assert!(
        names.iter().any(|n| is_anon_fn_name(n)),
        "expected synthetic anon name on FuncKey for call-argument fn literal, got: {:?}",
        names
    );
    assert!(
        !names.iter().any(|n| n == "apply"),
        "must not leak callee name onto its argument function, got: {:?}",
        names
    );
}

#[test]
fn named_fn_declaration_unchanged_js() {
    let src = b"function real_name(x) { eval(x); }";
    let names = js_body_names(src);
    assert!(
        names.iter().any(|n| n == "real_name"),
        "named declaration must retain its name, got: {:?}",
        names
    );
}

#[test]
fn anon_fn_named_from_short_var_decl_go() {
    let src = b"package main\nfunc main() { run := func(x string) { exec(x) }; run(\"hi\") }";
    let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "go", ts_lang);
    let names: Vec<String> = file_cfg
        .bodies
        .iter()
        .filter_map(|b| b.meta.func_key.as_ref().map(|k| k.name.clone()))
        .collect();
    assert!(
        names.iter().any(|n| n == "run"),
        "expected func literal body keyed as `run` via Go short-var decl, got: {:?}",
        names
    );
}

#[test]
fn iife_callee_resolves_to_anon_body_js() {
    // `(function(arg){eval(arg);})(q)`, the CallFn arm must produce
    // a synthetic anon callee name so that taint can match the
    // inline body's FuncKey.
    let src = b"(function(arg){ eval(arg); })(q);";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    let top = &file_cfg.bodies[0];
    let callee_names: Vec<String> = top
        .graph
        .node_indices()
        .filter_map(|i| top.graph[i].call.callee.clone())
        .collect();
    assert!(
        callee_names.iter().any(|c| is_anon_fn_name(c)),
        "IIFE call site should record synthetic anon callee, got: {:?}",
        callee_names
    );
}

/// Helper: collect every Sanitizer cap set that landed on any CFG node in
/// the function body for a Rust snippet.  Used by the replace-chain
/// detector tests.
fn rust_body_sanitizer_caps(src: &[u8]) -> Vec<Cap> {
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "rust", ts_lang);
    cfg.node_indices()
        .flat_map(|i| cfg[i].taint.labels.clone())
        .filter_map(|l| match l {
            DataLabel::Sanitizer(c) => Some(c),
            _ => None,
        })
        .collect()
}

#[test]
fn replace_chain_strips_file_io_for_path_traversal_literals() {
    // `.replace("..", "").replace("/", "_")` should earn FILE_IO stripping.
    let src = br#"
fn sanitize_input(s: &str) -> String {
    s.replace("..", "").replace("/", "_")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.iter().any(|c| c.contains(Cap::FILE_IO)),
        "Expected a Sanitizer(FILE_IO) on the replace chain; got {:?}",
        caps
    );
}

#[test]
fn replace_chain_strips_html_escape_for_angle_brackets() {
    // Stripping `<` and `>` earns HTML_ESCAPE, not FILE_IO.
    let src = br#"
fn strip_tags(s: &str) -> String {
    s.replace("<", "").replace(">", "")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.iter().any(|c| c.contains(Cap::HTML_ESCAPE)),
        "Expected a Sanitizer(HTML_ESCAPE) on angle-bracket strip; got {:?}",
        caps
    );
    assert!(
        !caps.iter().any(|c| c.contains(Cap::FILE_IO)),
        "Angle-bracket strip should NOT earn FILE_IO credit; got {:?}",
        caps
    );
}

#[test]
fn replace_chain_rejects_unrecognised_literals() {
    // `.replace("foo", "bar")` contains no dangerous pattern, must NOT be
    // credited as a sanitizer.  Preserves the FP→TN guard: replace calls
    // that don't strip anything dangerous must stay transparent to taint.
    let src = br#"
fn rewrite(s: &str) -> String {
    s.replace("foo", "bar").replace("baz", "qux")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.is_empty(),
        "Generic replace chain should not earn sanitizer credit; got {:?}",
        caps
    );
}

#[test]
fn replace_chain_rejects_when_replacement_reintroduces_pattern() {
    // `.replace("x", "..")` strips `x` but *reintroduces* `..`, be
    // maximally conservative and abandon all credit for this chain.
    let src = br#"
fn evil(s: &str) -> String {
    s.replace("x", "..")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.is_empty(),
        "Replacement reintroducing dangerous pattern must kill credit; got {:?}",
        caps
    );
}

#[test]
fn replace_chain_rejects_dynamic_arg() {
    // `.replace(var, "")`, search is not a literal; pattern analysis can
    // say nothing about what was stripped.  Must not earn credit.
    let src = br#"
fn dynamic(s: &str, needle: &str) -> String {
    s.replace(needle, "")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.is_empty(),
        "Dynamic replace arg must not earn credit; got {:?}",
        caps
    );
}

#[test]
fn replace_chain_rejects_non_identifier_base() {
    // `get_s().replace("..", "")`, innermost receiver is a call, not a
    // parameter.  We have no reason to believe `get_s()` returns a value
    // that benefits the caller; refuse credit.
    let src = br#"
fn base_is_call() -> String {
    get_s().replace("..", "")
}
"#;
    let caps = rust_body_sanitizer_caps(src);
    assert!(
        caps.is_empty(),
        "Non-identifier chain base must not earn credit; got {:?}",
        caps
    );
}

// ── is_numeric_length_access detector ─────────────────────────────────

fn find_node_defining<'a>(cfg: &'a Cfg, var: &str) -> Option<&'a NodeInfo> {
    cfg.node_indices()
        .map(|i| &cfg[i])
        .find(|n| n.taint.defines.as_deref() == Some(var))
}

#[test]
fn numeric_length_access_detected_on_js_property_read() {
    // `var count = items.length`, property access on a member expression
    // should mark the CFG node as a numeric-length access so the
    // type-fact analysis infers TypeKind::Int for `count`.
    let src = br#"function f(items) {
            var count = items.length;
            return count;
        }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
    let node = find_node_defining(&cfg, "count").expect("defines count");
    assert!(
        node.is_numeric_length_access,
        "Expected is_numeric_length_access=true for `count = items.length`"
    );
}

#[test]
fn numeric_length_access_detected_on_js_zero_arg_method_call() {
    // `var n = str.length()`, zero-arg method call form (uncommon in JS
    // but present in other languages).  Detector should unwrap a
    // zero-arg call around a member expression.
    let src = br#"function f(list) {
            var n = list.size();
            return n;
        }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
    let node = find_node_defining(&cfg, "n").expect("defines n");
    assert!(
        node.is_numeric_length_access,
        "Expected is_numeric_length_access=true for `n = list.size()`"
    );
}

#[test]
fn numeric_length_access_ignores_unrelated_properties() {
    // `var v = arr.foo`, arbitrary property reads must not be flagged.
    let src = br#"function f(arr) {
            var v = arr.foo;
            return v;
        }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
    let node = find_node_defining(&cfg, "v").expect("defines v");
    assert!(
        !node.is_numeric_length_access,
        "is_numeric_length_access must stay false for unrelated property `arr.foo`"
    );
}

#[test]
fn numeric_length_access_ignores_method_calls_with_args() {
    // `var r = s.indexOf('x')`, the detector must reject any call with
    // positional arguments because those aren't pure length reads.
    let src = br#"function f(s) {
            var r = s.indexOf('x');
            return r;
        }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
    let node = find_node_defining(&cfg, "r").expect("defines r");
    assert!(
        !node.is_numeric_length_access,
        "is_numeric_length_access must stay false for arg-bearing calls"
    );
}

//── subscript lowering tests ────────────────────────

/// Scope for tests that flip `NYX_POINTER_ANALYSIS=1` so the CFG-side
/// subscript synthesis activates.  The env-var is restored afterwards
/// so the rest of the test suite stays bit-identical to the unset
/// state.  Mirrors the env-var serialisation pattern used elsewhere in
/// the test suite (see `tests/pointer_disabled_bit_identity.rs`).
use std::sync::Mutex;
static POINTER_ENV_GUARD: Mutex<()> = Mutex::new(());

fn with_pointer_env<R>(value: Option<&str>, f: impl FnOnce() -> R) -> R {
    let _lock = POINTER_ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
    let prev = std::env::var("NYX_POINTER_ANALYSIS").ok();
    unsafe {
        match value {
            Some(v) => std::env::set_var("NYX_POINTER_ANALYSIS", v),
            None => std::env::remove_var("NYX_POINTER_ANALYSIS"),
        }
    }
    let r = f();
    unsafe {
        match prev {
            Some(v) => std::env::set_var("NYX_POINTER_ANALYSIS", v),
            None => std::env::remove_var("NYX_POINTER_ANALYSIS"),
        }
    }
    r
}

fn with_pointer_on<R>(f: impl FnOnce() -> R) -> R {
    with_pointer_env(Some("1"), f)
}

fn count_nodes_with_callee(cfg: &Cfg, callee: &str) -> usize {
    cfg.node_indices()
        .filter(|i| cfg[*i].call.callee.as_deref() == Some(callee))
        .count()
}

fn find_node_with_callee<'a>(cfg: &'a Cfg, callee: &str) -> Option<&'a NodeInfo> {
    cfg.node_indices()
        .map(|i| &cfg[i])
        .find(|n| n.call.callee.as_deref() == Some(callee))
}

#[test]
fn js_subscript_read_lowers_to_index_get_call() {
    with_pointer_on(|| {
        // `arr[0]` as a sink call argument should be pre-emitted as a
        // synth `__index_get__` call before the consuming sink.
        let src = br#"function f(arr) {
            sink(arr[0]);
        }"#;
        let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_get__")
            .expect("__index_get__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("arr"));
        assert_eq!(node.call.arg_uses.len(), 1, "expect one arg group (index)");
        assert_eq!(node.call.arg_uses[0], vec!["0"]);
        assert!(
            node.taint
                .defines
                .as_deref()
                .is_some_and(|d| d.starts_with("__nyx_idxget_")),
            "synth defines should use the __nyx_idxget_ prefix"
        );
    });
}

#[test]
fn js_subscript_write_lowers_to_index_set_call() {
    with_pointer_on(|| {
        let src = br#"function f(arr, v) {
            arr[0] = v;
        }"#;
        let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_set__")
            .expect("__index_set__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("arr"));
        assert_eq!(
            node.call.arg_uses.len(),
            2,
            "expect arg_uses [[idx], [val]]"
        );
        assert_eq!(node.call.arg_uses[0], vec!["0"]);
        assert_eq!(node.call.arg_uses[1], vec!["v"]);
    });
}

#[test]
fn py_subscript_read_lowers_to_index_get_call() {
    with_pointer_on(|| {
        let src = br#"def f(arr):
    sink(arr[0])
"#;
        let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "python", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_get__")
            .expect("python: __index_get__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("arr"));
    });
}

#[test]
fn py_subscript_write_lowers_to_index_set_call() {
    with_pointer_on(|| {
        let src = br#"def f(arr, v):
    arr[0] = v
"#;
        let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "python", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_set__")
            .expect("python: __index_set__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("arr"));
        assert_eq!(node.call.arg_uses.len(), 2);
        assert_eq!(node.call.arg_uses[1], vec!["v"]);
    });
}

#[test]
fn go_index_expr_read_lowers_to_index_get_call() {
    with_pointer_on(|| {
        let src = br#"package main
func f(arr []string) {
    sink(arr[0])
}
"#;
        let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "go", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_get__")
            .expect("go: __index_get__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("arr"));
    });
}

#[test]
fn go_index_expr_write_lowers_to_index_set_call() {
    with_pointer_on(|| {
        let src = br#"package main
func f(m map[string]int, k string, v int) {
    m[k] = v
}
"#;
        let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "go", ts_lang);
        let node = find_node_with_callee(&cfg, "__index_set__")
            .expect("go: __index_set__ node should be present");
        assert_eq!(node.call.receiver.as_deref(), Some("m"));
        assert_eq!(node.call.arg_uses.len(), 2);
        assert_eq!(node.call.arg_uses[0], vec!["k"]);
        assert_eq!(node.call.arg_uses[1], vec!["v"]);
    });
}

#[test]
fn pointer_disabled_skips_subscript_synthesis() {
    // Strict-additive contract: when NYX_POINTER_ANALYSIS=0 the CFG
    // must contain zero __index_get__/__index_set__ nodes regardless
    // of the source shape.  This is the off-by-default invariant the
    // bit-identity gate relies on.
    with_pointer_env(Some("0"), || {
        let src = br#"function f(arr, v) {
            sink(arr[0]);
            arr[1] = v;
        }"#;
        let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
        let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
        assert_eq!(count_nodes_with_callee(&cfg, "__index_get__"), 0);
        assert_eq!(count_nodes_with_callee(&cfg, "__index_set__"), 0);
    });
}

// ─────────────────────────────────────────────────────────────────
//   Gap-filling: switch / for / do-while / nested loops / re-throw
// ─────────────────────────────────────────────────────────────────

/// JS `switch` should produce one synthetic dispatch `If` node per
/// case (default excluded when at the tail), plus True edges into
/// each case body. Verifies the discriminant cascade is wired.
#[test]
fn js_switch_cascade_has_one_if_per_case() {
    let src = br#"function f(x) {
        switch (x) {
            case 1: a(); break;
            case 2: b(); break;
            default: c();
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    // Two non-default cases => 2 dispatch If nodes (the tail default
    // is wired via the previous header's False edge, not its own If).
    assert_eq!(
        if_nodes(&cfg).len(),
        2,
        "switch with 2 explicit cases + default should emit 2 dispatch If nodes"
    );

    // Each dispatch If must have at least one True and one False edge
    // (True → case body, False → next case / default).
    for i in if_nodes(&cfg) {
        let trues = cfg
            .edges(i)
            .filter(|e| matches!(e.weight(), EdgeKind::True))
            .count();
        let falses = cfg
            .edges(i)
            .filter(|e| matches!(e.weight(), EdgeKind::False))
            .count();
        assert!(
            trues >= 1,
            "case dispatch should have at least one True edge"
        );
        assert!(
            falses >= 1,
            "case dispatch should have at least one False edge"
        );
    }
}

/// Default case in the *middle* of a switch must be reordered to the
/// tail so the dispatch cascade stays a clean True/False chain. The
/// observable CFG shape (number of If nodes, presence of True/False
/// edges per dispatch) should match the all-default-at-tail case.
#[test]
fn js_switch_default_in_middle_reorders_to_tail() {
    let src = br#"function f(x) {
        switch (x) {
            case 1: a(); break;
            default: c(); break;
            case 2: b(); break;
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    // 2 non-default cases ⇒ 2 If dispatch nodes (default reordered to tail).
    assert_eq!(
        if_nodes(&cfg).len(),
        2,
        "default-in-middle should still produce one If per non-default case"
    );
}

/// JS switch fall-through (`case 1: a(); case 2: b();`), case 1's
/// exit should flow into case 2's body so taint from `first()`
/// reaches `second()`'s sinks.
///
/// We assert two things:
///   (a) Reachability: `second()` is reachable from `first()` over
///       forward edges. This is the semantic property taint analysis
///       depends on; checking it directly avoids over-fitting to the
///       structural shape.
///   (b) `first()` has a non-Back forward out-edge that lands inside
///       the case-2 sub-graph (the actual fall-through wire), so we
///       prove there *is* a fall-through edge, not just an
///       Entry→…→Exit path that happens to walk through both calls
///       via the dispatch chain.
///
/// Note on the structural shape: case bodies are wrapped in synthetic
/// Seq passthrough nodes (one per surrounding scope), so the
/// fall-through edge from `first()` lands on the *first wrapper
/// Seq node* of case 2, not on `second()` itself. Asserting that
/// `second()` has ≥2 in-edges would therefore be wrong, the True
/// edge from the case-2 dispatch If targets the wrapper node, and
/// only a single Seq chain leads from there to `second()`.
#[test]
fn js_switch_fallthrough_no_break() {
    use std::collections::HashSet;
    let src = br#"function f(x) {
        switch (x) {
            case 1: first();
            case 2: second(); break;
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let first = cfg
        .node_indices()
        .find(|&n| cfg[n].call.callee.as_deref() == Some("first"))
        .expect("expected a Call node for `first`");
    let second = cfg
        .node_indices()
        .find(|&n| cfg[n].call.callee.as_deref() == Some("second"))
        .expect("expected a Call node for `second`");

    // (a) Reachability from first → second over forward (non-Back) edges.
    let mut seen: HashSet<NodeIndex> = HashSet::new();
    let mut stack = vec![first];
    while let Some(n) = stack.pop() {
        if !seen.insert(n) {
            continue;
        }
        for e in cfg.edges(n) {
            if matches!(e.weight(), EdgeKind::Seq | EdgeKind::True | EdgeKind::False) {
                stack.push(e.target());
            }
        }
    }
    assert!(
        seen.contains(&second),
        "fall-through: `second` must be reachable from `first` over forward edges"
    );

    // (b) Prove the fall-through edge exists: `first()` must have at
    //     least one outgoing forward edge whose target is *not*
    //     reachable from the function entry without first going
    //     through `first()`. The straightforward check: `first()`
    //     itself must have at least one outgoing Seq edge (the
    //     fall-through wire is always Seq).
    let first_seq_outs = cfg
        .edges(first)
        .filter(|e| matches!(e.weight(), EdgeKind::Seq))
        .count();
    assert!(
        first_seq_outs >= 1,
        "fall-through: `first()` must have a Seq out-edge (the fall-through wire)"
    );
}

/// `for (i = 0; i < 10; i++) { body(); }` should produce a Loop node
/// with at least one Back edge from the body back to the loop header.
#[test]
fn js_for_loop_has_back_edge() {
    let src = br#"function f() { for (let i = 0; i < 10; i++) { body(); } }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let loop_nodes: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect();
    assert_eq!(loop_nodes.len(), 1, "expected exactly one Loop node");

    let back_edges = cfg
        .edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Back))
        .count();
    assert!(
        back_edges >= 1,
        "for loop must have at least one Back edge to its header"
    );
}

/// `do { ... } while (cond);` is mapped to `Kind::While` for many
/// languages but the grammar puts the body *before* the condition.
/// The CFG must still produce a Loop node and at least one Back edge.
#[test]
fn js_do_while_has_loop_node_and_back_edge() {
    let src = br#"function f() { do { body(); } while (cond); }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let loop_count = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .count();
    assert_eq!(loop_count, 1, "do-while should produce one Loop node");
    assert!(
        cfg.edge_references()
            .any(|e| matches!(e.weight(), EdgeKind::Back)),
        "do-while must have at least one Back edge"
    );
}

/// In `outer: while (a) { while (b) { break; } }`, the `break`
/// terminates only the *inner* loop. Equivalent for our CFG: the
/// break's predecessors should reach the inner loop's exit frontier
/// without crossing the outer loop's body again. We can verify this
/// structurally: there must be exactly two Loop nodes and at least
/// one Break node whose forward (Seq) successor is *not* the outer
/// header.
#[test]
fn js_nested_while_break_targets_inner_loop() {
    let src = br#"function f() {
        while (a) {
            while (b) { break; }
            inner_after();
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let loops: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect();
    assert_eq!(loops.len(), 2, "expected two Loop nodes");

    let breaks: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Break)
        .collect();
    assert_eq!(breaks.len(), 1, "expected exactly one Break node");

    // The inner loop body's break should NOT close back via Back edge
    // onto the outer header (outer header is loops[0] in source order).
    let outer_header = loops[0];
    let brk = breaks[0];
    let crosses_outer = cfg
        .edges(brk)
        .any(|e| e.target() == outer_header && matches!(e.weight(), EdgeKind::Back));
    assert!(
        !crosses_outer,
        "inner break must not back-edge onto the outer loop header"
    );
}

/// `continue` in the inner loop must back-edge onto the *inner*
/// header, not the outer. With nested while loops we expect exactly
/// one Continue node and at least one Back edge originating at it
/// going to the inner (second-emitted) Loop header.
#[test]
fn js_nested_while_continue_targets_inner_loop() {
    let src = br#"function f() {
        while (a) {
            while (b) { continue; }
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let loops: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect();
    assert_eq!(loops.len(), 2, "expected two Loop nodes");
    let outer_header = loops[0];
    let inner_header = loops[1];

    let cont = cfg
        .node_indices()
        .find(|&n| cfg[n].kind == StmtKind::Continue)
        .expect("expected Continue node");

    let back_edges_from_cont: Vec<_> = cfg
        .edges(cont)
        .filter(|e| matches!(e.weight(), EdgeKind::Back))
        .collect();
    assert!(
        !back_edges_from_cont.is_empty(),
        "continue must originate at least one Back edge"
    );
    assert!(
        back_edges_from_cont
            .iter()
            .any(|e| e.target() == inner_header),
        "continue's Back edge must target the inner loop header"
    );
    assert!(
        !back_edges_from_cont
            .iter()
            .any(|e| e.target() == outer_header),
        "continue must not back-edge onto the outer loop header"
    );
}

/// `throw` inside a `catch` block should still register a throw
/// target so a surrounding outer try (or function-level exit) can
/// receive it. We verify here that the throw produces a Throw node
/// even when it is reached only via an Exception edge from the inner
/// try body (i.e. the re-throw path is preserved structurally).
#[test]
fn js_throw_inside_catch_emits_throw_node() {
    let src = br#"function f() {
        try {
            try { foo(); } catch (e) { throw e; }
        } catch (e2) {
            handle();
        }
    }"#;
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let throws: Vec<_> = cfg
        .node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Throw)
        .collect();
    assert_eq!(
        throws.len(),
        1,
        "expected exactly one Throw node for the inner re-throw"
    );

    // The outer `catch (e2)` body must be reachable. Check that the
    // `handle()` call exists and has at least one incoming edge.
    let handle = cfg
        .node_indices()
        .find(|&n| cfg[n].call.callee.as_deref() == Some("handle"))
        .expect("expected `handle()` call node");
    let in_edges = cfg
        .edges_directed(handle, petgraph::Direction::Incoming)
        .count();
    assert!(in_edges >= 1, "outer catch body must be reachable");
}

/// Empty if/else branches (e.g., `if (a) {} else {}`) must not panic
/// and the resulting CFG must still have a single If node with both
/// True and False edges going somewhere reachable. This guards
/// against off-by-one bugs in `then_first_node`/exits handling.
#[test]
fn js_if_with_empty_branches_does_not_panic() {
    let src = b"function f() { if (a) {} else {} return; }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);

    let ifs = if_nodes(&cfg);
    assert_eq!(ifs.len(), 1, "expected one If node");
    let i = ifs[0];

    let trues: Vec<_> = cfg
        .edges(i)
        .filter(|e| matches!(e.weight(), EdgeKind::True))
        .collect();
    let falses: Vec<_> = cfg
        .edges(i)
        .filter(|e| matches!(e.weight(), EdgeKind::False))
        .collect();
    assert!(!trues.is_empty(), "empty-then If must still emit True edge");
    assert!(
        !falses.is_empty(),
        "empty-else If must still emit False edge"
    );
}

/// A function body with no statements should still produce a
/// well-formed CFG (entry/exit only); no panic, no orphan nodes from
/// `build_sub` returning an empty exit set.
#[test]
fn js_empty_function_body_well_formed() {
    let src = b"function f() {}";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
    // We expect 2 bodies: top-level + the function body. Both must be
    // valid graphs with at least an entry node.
    assert!(
        file_cfg.bodies.len() >= 2,
        "expected at least 2 bodies (top-level + function)"
    );
    for body in &file_cfg.bodies {
        assert!(
            body.graph.node_count() >= 1,
            "every body must have at least one node"
        );
    }
}

// ─────────────────────────────────────────────────────────────────────
//  Loop CFG structure: every loop variant must produce a Loop header
//  with at least one Back edge that targets that header. Without these
//  invariants the SSA loop-induction-variable phi placement is wrong
//  and the abstract-interp widening points are missed.
// ─────────────────────────────────────────────────────────────────────

fn loop_headers(cfg: &Cfg) -> Vec<NodeIndex> {
    cfg.node_indices()
        .filter(|&n| cfg[n].kind == StmtKind::Loop)
        .collect()
}

fn back_edges(cfg: &Cfg) -> Vec<(NodeIndex, NodeIndex)> {
    cfg.edge_references()
        .filter(|e| matches!(e.weight(), EdgeKind::Back))
        .map(|e| (e.source(), e.target()))
        .collect()
}

fn assert_loop_with_back_edge(cfg: &Cfg, label: &str) {
    let headers = loop_headers(cfg);
    assert!(
        !headers.is_empty(),
        "{label}: expected at least one Loop header, found none"
    );
    let backs = back_edges(cfg);
    assert!(
        !backs.is_empty(),
        "{label}: expected at least one Back edge"
    );
    for (_, dst) in &backs {
        assert!(
            headers.contains(dst),
            "{label}: Back edge target {:?} is not a Loop header (headers={:?})",
            dst,
            headers
        );
    }
}

#[test]
fn js_for_loop_back_edge() {
    let src = b"function f() { for (let i = 0; i < 10; i++) { body(i); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    assert_loop_with_back_edge(&cfg, "js classic for");
}

#[test]
fn js_do_while_back_edge() {
    let src = b"function f() { do { body(); } while (cond()); }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    assert_loop_with_back_edge(&cfg, "js do-while");
}

#[test]
fn js_for_in_back_edge() {
    let src = b"function f() { for (let k in obj) { use(k); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    assert_loop_with_back_edge(&cfg, "js for-in");
}

#[test]
fn js_for_of_back_edge() {
    let src = b"function f() { for (const x of items) { use(x); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    // for-of is usually classified the same as for-in / for via
    // for_in_statement. Still, body-with-back-edge invariant must hold.
    assert_loop_with_back_edge(&cfg, "js for-of");
}

#[test]
fn python_for_loop_back_edge() {
    let src = b"def f():\n    for x in items:\n        use(x)\n";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "python", ts_lang);
    assert_loop_with_back_edge(&cfg, "python for");
}

#[test]
fn python_while_loop_back_edge() {
    let src = b"def f():\n    while cond():\n        use(x)\n";
    let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "python", ts_lang);
    assert_loop_with_back_edge(&cfg, "python while");
}

#[test]
fn java_enhanced_for_back_edge() {
    let src = b"class A { void f(int[] xs) { for (int x : xs) { use(x); } } }";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "java", ts_lang);
    assert_loop_with_back_edge(&cfg, "java enhanced-for");
}

#[test]
fn java_do_while_back_edge() {
    let src = b"class A { void f() { do { body(); } while (cond()); } }";
    let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "java", ts_lang);
    assert_loop_with_back_edge(&cfg, "java do-while");
}

#[test]
fn cpp_range_for_back_edge() {
    let src = b"void f(int* xs) { for (int x : range) { use(x); } }";
    let ts_lang = Language::from(tree_sitter_cpp::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "cpp", ts_lang);
    assert_loop_with_back_edge(&cfg, "cpp range-for");
}

#[test]
fn c_do_while_back_edge() {
    let src = b"void f() { do { body(); } while (cond()); }";
    let ts_lang = Language::from(tree_sitter_c::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "c", ts_lang);
    assert_loop_with_back_edge(&cfg, "c do-while");
}

#[test]
fn go_for_loop_back_edge() {
    let src = b"package p\nfunc f() { for i := 0; i < 10; i++ { body(i) } }";
    let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "go", ts_lang);
    assert_loop_with_back_edge(&cfg, "go for");
}

/// Pins the structural fix in `def_use` Kind::For arm for Go's
/// `for ident, ident := range iter` shape.  Tree-sitter wraps the binding
/// pattern + iterable in a `range_clause` child of the `for_statement`
/// (rather than direct `left`/`right` fields like Python / JS).  Without
/// this, the loop binding never becomes a CFG def and taint from the
/// iterable cannot reach uses of the binding inside the loop body.
/// Original gap: CVE-2026-41422 (daptin) goqu.L SQL injection.
#[test]
fn go_for_range_loop_binding_is_defined() {
    let src = b"package p\nfunc f(xs []string) { for _, p := range xs { use(p) } }";
    let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "go", ts_lang);

    let loop_node = cfg
        .node_indices()
        .find(|&n| matches!(cfg[n].kind, StmtKind::Loop))
        .expect("for-range loop should produce a Loop header");
    let info = &cfg[loop_node];
    let all_defs: Vec<&str> = info
        .taint
        .defines
        .iter()
        .map(String::as_str)
        .chain(info.taint.extra_defines.iter().map(String::as_str))
        .collect();
    assert!(
        all_defs.contains(&"p"),
        "loop binding `p` should appear in defines/extra_defines, got {:?}",
        all_defs
    );
    assert!(
        info.taint.uses.iter().any(|u| u == "xs"),
        "iterable `xs` should appear in uses, got {:?}",
        info.taint.uses
    );
}

#[test]
fn ruby_while_back_edge() {
    let src = b"def f\n  while cond\n    body\n  end\nend\n";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "ruby", ts_lang);
    assert_loop_with_back_edge(&cfg, "ruby while");
}

#[test]
fn ruby_until_back_edge() {
    // `until cond` is `while not cond`; should still produce a loop.
    let src = b"def f\n  until done\n    body\n  end\nend\n";
    let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "ruby", ts_lang);
    assert_loop_with_back_edge(&cfg, "ruby until");
}

#[test]
fn php_foreach_back_edge() {
    let src = b"<?php function f($items) { foreach ($items as $x) { use($x); } }";
    let ts_lang = Language::from(tree_sitter_php::LANGUAGE_PHP);
    let (cfg, _) = parse_and_build(src, "php", ts_lang);
    assert_loop_with_back_edge(&cfg, "php foreach");
}

#[test]
fn rust_for_loop_back_edge() {
    let src = b"fn f() { for x in 0..10 { use_fn(x); } }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "rust", ts_lang);
    assert_loop_with_back_edge(&cfg, "rust for");
}

#[test]
fn rust_while_loop_back_edge() {
    let src = b"fn f() { while cond() { body(); } }";
    let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "rust", ts_lang);
    assert_loop_with_back_edge(&cfg, "rust while");
}

#[test]
fn nested_loops_two_headers_two_back_edges() {
    // Nested loops must produce two distinct loop headers and a back
    // edge for each. This guards against headers being collapsed and
    // back edges being mis-routed to the outer header.
    let src = b"function f() { for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { use(i, j); } } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    let headers = loop_headers(&cfg);
    assert_eq!(headers.len(), 2, "expected 2 loop headers in nested loops");
    let backs = back_edges(&cfg);
    assert!(
        backs.len() >= 2,
        "expected ≥2 back edges in nested loops, got {}",
        backs.len()
    );
    // Every back edge must target one of the two headers.
    for (_, dst) in &backs {
        assert!(headers.contains(dst), "back edge target not a loop header");
    }
    // Each header should be the target of at least one back edge.
    let mut hit = std::collections::HashSet::new();
    for (_, dst) in &backs {
        hit.insert(*dst);
    }
    assert_eq!(
        hit.len(),
        2,
        "each header must receive at least one back edge"
    );
}

#[test]
fn loop_with_break_no_back_edge_from_break() {
    // A `break` short-circuits the loop body, its edge must NOT be a
    // back edge to the header (it leaves the loop entirely).
    let src = b"function f() { while (cond()) { if (done()) break; body(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    let headers = loop_headers(&cfg);
    assert_eq!(headers.len(), 1, "expected 1 loop header");
    let header = headers[0];

    // Find any Break node and verify none of its outgoing edges are
    // Back edges to the header.
    for n in cfg.node_indices() {
        if cfg[n].kind != StmtKind::Break {
            continue;
        }
        for e in cfg.edges(n) {
            assert!(
                !(matches!(e.weight(), EdgeKind::Back) && e.target() == header),
                "break must not produce a back edge to the loop header"
            );
        }
    }
}

#[test]
fn loop_with_continue_back_edge_to_header() {
    // `continue` must produce a Back edge to the loop header.
    let src = b"function f() { while (cond()) { if (skip()) continue; body(); } }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
    let headers = loop_headers(&cfg);
    assert_eq!(headers.len(), 1);
    let header = headers[0];

    let mut found = false;
    for n in cfg.node_indices() {
        if cfg[n].kind != StmtKind::Continue {
            continue;
        }
        for e in cfg.edges(n) {
            if matches!(e.weight(), EdgeKind::Back) && e.target() == header {
                found = true;
            }
        }
    }
    assert!(
        found,
        "expected at least one Back edge from a Continue node to the loop header"
    );
}

/// Regression guard for the 2026-04-27 chained-method-call inner-gate
/// rebinding (CVE-2025-64430 hunt session).  Without the fix, the outer
/// `.on('error', cb)` call swallows classification of the inner
/// `http.get(uri, cb)` so neither the gate label nor `sink_payload_args`
/// are populated for this CFG node.
#[test]
fn chained_method_call_rebinds_to_inner_gated_sink() {
    // Use `https.get` (a gated SSRF sink) so the gate fires only when
    // the inner-call rebinding works.  The outer `.on(...)` is a plain
    // method call that does not classify on its own.
    let src = b"function f(uri) { https.get(uri, r => {}).on('error', e => {}); }";
    let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
    let (cfg, _) = parse_and_build(src, "javascript", ts_lang);

    // Find a Call node whose `text` was rebound to the inner gated callee.
    let mut found = false;
    for n in cfg.node_indices() {
        let info = &cfg[n];
        if info.kind != StmtKind::Call {
            continue;
        }
        let Some(callee) = info.call.callee.as_deref() else {
            continue;
        };
        // The inner callee is `https.get`; the outer chained `.on` should
        // no longer be the recorded callee for this node.
        if callee.ends_with("https.get") {
            // The inner-gate path must have populated sink_payload_args
            // (the gate's payload arg is position 0, the URL string).
            assert!(
                info.call.sink_payload_args.is_some(),
                "expected sink_payload_args to be populated for chained \
                 inner-gate https.get; got None on call node with callee {callee:?}"
            );
            found = true;
            break;
        }
    }
    assert!(
        found,
        "expected at least one Call node whose callee was rebound from \
         the outer `.on(...)` to the inner `https.get` after the chained- \
         call inner-gate rebinding fired"
    );
}